コード例 #1
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var session = SessionFactory.GetCurrentSession();

            //var transaction = session.Transaction;
            //if (transaction != null && transaction.IsActive)
            //{
            //    transaction.Commit();
            //}

            Trace.WriteLine(string.Format("Thread:{0} Session:{1} OnActionExecuted", Thread.CurrentThread.ManagedThreadId, session.GetHashCode()));

            session = CurrentSessionContext.Unbind(SessionFactory);
            session.Close();
        }
コード例 #2
0
ファイル: EkipeForm.cs プロジェクト: stankela/bilten
        private void addEkipaCmd()
        {
            EkipaForm form;

            try
            {
                form = new EkipaForm(null, ActiveRezTakmicenje.Id, !viseKola);
                if (form.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
            }
            catch (InfrastructureException ex)
            {
                MessageDialogs.showError(ex.Message, this.Text);
                return;
            }

            ISession session = null;

            try
            {
                using (session = NHibernateHelper.Instance.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        // ponovo ucitaj takmicenje zato sto je dodata ekipa
                        rezTakmicenja[tabControl1.SelectedIndex] = loadRezTakmicenje(ActiveRezTakmicenje.Id);
                    }
            }
            catch (Exception ex)
            {
                if (session != null && session.Transaction != null && session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
                MessageDialogs.showMessage(ex.Message, this.Text);
                return;
            }
            finally
            {
                CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory);
            }

            setEkipe(ActiveRezTakmicenje.Takmicenje1.Ekipe);
            setSelectedEkipa((Ekipa)form.Entity);
            onEkipeCellMouseClick();
        }
コード例 #3
0
        public void Rollback()
        {
            ISession session = CurrentSessionContext.Unbind(this.sessionFactory);

            if (session == null)
            {
                return;
            }

            if (session.Transaction.IsActive)
            {
                session.Transaction.Rollback();
            }

            session.Dispose();
        }
コード例 #4
0
        public void PreProceed(string methodName)
        {
            ISession session = this.sessionFactory.OpenSession();

            if (session == null)
            {
                return;
            }

            if (this.Guard(methodName))
            {
                session.BeginTransaction(IsolationLevel.ReadUncommitted);
            }

            CurrentSessionContext.Bind(session);
        }
コード例 #5
0
ファイル: Pipelines.cs プロジェクト: naimeshpatel/Crux
        public static Func <NancyContext, Response> BeforeEveryRequest(IContainer requestContainer)
        {
            return(ctx => {
                var unitOfWork = requestContainer.GetInstance <INHibernateUnitOfWork>();
                var scope = unitOfWork.CreateTransactionalScope(UnitOfWorkTransactionOptions.DirtyReads());
                var session = unitOfWork.CurrentSession;

                ctx.Items.Add(REQUEST_TRANSACTIONAL_SCOPE_KEY, scope);

                CurrentSessionContext.Bind(session);

                session.BeginTransaction();

                return ctx.Response;
            });
        }
コード例 #6
0
        internal static void UnbindAndCloseSession(ISessionFactory nhSessionFactory)
        {
            if (nhSessionFactory == null || nhSessionFactory.IsClosed)
            {
                return;
            }

            LogHelper.TraceIfEnabled <EntityRepositoryFactory>("Unbinding session and closing it");

            var session = CurrentSessionContext.Unbind(nhSessionFactory);

            if (session != null && session.IsOpen)
            {
                session.Close();
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            ISession session = CurrentSessionContext.Unbind(NHibernateConfiguration.SessionFactory);

            if (session == null)
            {
                return;
            }

            if (session.IsOpen)
            {
                session.Close();
            }

            session.Dispose();
        }
コード例 #8
0
        void IManageUnitsOfWork.Begin()
        {
            if (SessionFactory == null)
            {
                return;
            }

            var session = SessionFactory.OpenSession();

            CurrentSessionContext.Bind(session);

            if (NoAmbientTransaction())
            {
                session.BeginTransaction();
            }
        }
コード例 #9
0
        public ISession GetCurrentSession()
        {
            ISession session = null;

            if (CurrentSessionContext.HasBind(sessionFactory))
            {
                session = sessionFactory.GetCurrentSession();
            }
            else
            {
                session = sessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            }

            return(session);
        }
コード例 #10
0
        /// <summary>
        /// Invokes the supplied function with a Session, handling the details of binding/unbinding with the <see cref="CurrentSessionContext"/>.
        /// </summary>
        /// <param name="validation">The function to be invoked.</param>
        /// <returns>The return value from the supplied function.</returns>
        protected bool ValidateUsingSession(Func <ISession, bool> validation)
        {
            var shouldReleaseBind = EnsureSessionContextBinding();

            try
            {
                return(validation(Session));
            }
            finally
            {
                if (shouldReleaseBind)
                {
                    CurrentSessionContext.Unbind(SessionFactory);
                }
            }
        }
コード例 #11
0
        private bool EnsureSessionBinding()
        {
            if (!CurrentSessionContext.HasBind(_sessionFactory))
            {
                _session = _sessionFactory.OpenSession();
                CurrentSessionContext.Bind(_session);
                return(true);
            }

            if (!_sessionFactory.GetCurrentSession().IsOpen)
            {
                throw new Exception("CurrentSessionContext has binding to a session that is not open.");
            }

            return(false);
        }
コード例 #12
0
ファイル: DataManager.cs プロジェクト: SHAREVIEW/yokogawasvc
        internal UnitOfWork(ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;

            if (!CurrentSessionContext.HasBind(_sessionFactory))
            {
                _session = _sessionFactory.OpenSession();
                CurrentSessionContext.Bind(_session);
            }
            else
            {
                _session = _sessionFactory.GetCurrentSession();
            }

            _transaction = _session.BeginTransaction();
        }
コード例 #13
0
        public override void Init()
        {
            this.BeginRequest += (sender, e) =>
            {
                var session = NHibernateSessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            };

            this.EndRequest += (sender, e) =>
            {
                var session = CurrentSessionContext.Unbind(NHibernateSessionFactory);

                session.Dispose();
            };
            base.Init();
        }
コード例 #14
0
        //Desaloca a sessão do NHibernate no contexto da aplicação
        public void UnBindSession()
        {
            ISession session = CurrentSessionContext.Unbind(_sessionFactory.GetSessionFactory());

            if (session == null)
            {
                return;
            }
            session.Clear();
            if (session.IsOpen)
            {
                session.Close();
            }
            session.Dispose();
            session = null;
        }
コード例 #15
0
        private static ISession GetSession()
        {
            ISession session;

            if (CurrentSessionContext.HasBind(NHConfig.SessionFactory))
            {
                session = NHConfig.SessionFactory.GetCurrentSession();
            }
            else
            {
                session = NHConfig.SessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            }

            return(session);
        }
コード例 #16
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result;

            using (TransactionScope tx = new TransactionScope())
            {
                result = getNext()(input, getNext);
                if (result.Exception == null)
                {
                    _sessionFactory.GetCurrentSession().Flush();
                    tx.Complete();
                }
            }
            CurrentSessionContext.Bind(_sessionFactory.OpenSession());
            return(result);
        }
コード例 #17
0
        /// <summary>
        /// Saves the specified entity.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity">The entity.</param>
        /// <param name="callback">The callback.</param>
        public void Save <T>(T entity, Action <object, Exception> callback) where T : class, IEntity
        {
            Exception error  = null;
            object    result = null;

            try
            {
                using (var session = GetSession())
                {
                    using (var tx = session.BeginTransaction())
                    {
                        session.Evict(entity);

                        if (!entity.IsPersisted)
                        {
                            session.SaveOrUpdate(entity);
                        }
                        else
                        {
                            entity = session.Merge(entity);
                        }

                        session.Flush();

                        tx.Commit();

                        if (tx.WasCommitted)
                        {
                            if (!CurrentSessionContext.HasBind(SessionFactoryProvider.SessionFactory))
                            {
                                CurrentSessionContext.Bind(session);
                            }

                            session.Refresh(entity);
                            result = entity;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                error = e;
                Log(e, "Saving to DB", new EntityDescriptor(entity));
            }

            callback(result, error);
        }
コード例 #18
0
ファイル: ElementForm.cs プロジェクト: stankela/gimnastika
        public ElementForm(Nullable <int> elementId, Sprava sprava,
                           Element parent, bool persistEntity)
        {
            InitializeComponent();

            try
            {
                using (ISession session = NHibernateHelper.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        this.parent    = parent;
                        this.varijanta = parent != null;
                        initUI(sprava == Sprava.Preskok);
                        this.persistEntity = persistEntity;

                        if (elementId == null)
                        {
                            editMode = false;
                            element  = createNewEntity();
                            if (sprava != Sprava.Undefined)
                            {
                                setComboSprava(sprava);
                            }
                        }
                        else
                        {
                            editMode = true;
                            element  = getEntityById(elementId.Value);
                            saveOldData(element);
                            updateUIFromEntity(element);
                        }

                        // TODO: Kada je sprava Undefined, moze da se desi da je combo sprava omogucen a textbox Vrednost
                        // onemogucen. Ako se kasnije izabere Preskok za spravu, textbox Vrednost bi trebalo omoguciti.
                        // Ova situacija moze da se desi u 2 od 4 konstruktora za ElementForm (u ostala 2 je cmbSprava
                        // uvek onemogucen).
                        cmbSprava.Enabled = sprava == Sprava.Undefined;
                        initHandlers();
                    }
            }
            finally
            {
                // TODO: Dodaj sve catch blokove koji fale (i ovde i u programu za Clanove)
                CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
            }
        }
コード例 #19
0
        public static void DisposeSession()
        {
            var session = CurrentSessionContext.Unbind(CurrentFactory);

            if (session != null)
            {
                if (session.IsConnected && session.Connection != null)
                {
                    session.Connection.Close();
                }
                if (session.IsOpen)
                {
                    session.Close();
                }
                session.Dispose();
            }
        }
コード例 #20
0
ファイル: NHPersistenceContext.cs プロジェクト: HojjatK/roham
 public void Dispose()
 {
     if (!_isDisposed)
     {
         try
         {
             var contextSession = CurrentSessionContext.Unbind(_sessionFactory);
             if (contextSession != _session)
             {
                 throw new Exception("Unbinded session is not the same as closing session");
             }
             if (_session.IsOpen)
             {
                 try
                 {
                     if (_session.Transaction != null && _session.Transaction.IsActive)
                     {
                         // TODO: log a warning
                         _session.Transaction.Rollback();
                     }
                 }
                 finally
                 {
                     _session.Close();
                 }
             }
         }
         finally
         {
             if (_session != null)
             {
                 try
                 {
                     if (_session.Transaction != null)
                     {
                         _session.Transaction.Dispose();
                     }
                 }
                 finally
                 {
                     _session.Dispose();
                 }
             }
         }
     }
 }
コード例 #21
0
        private void Context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var currentSessions = HttpContext.Current.Session[NHibernateSessionKey] as ISession[];

            if (currentSessions != null)
            {
                // Bind the conversation to the context
                foreach (ISession session in currentSessions)
                {
                    CurrentSessionContext.Bind(session);
                }
            }
            foreach (ISessionFactory factory in sfp)
            {
                factory.GetCurrentSession().BeginTransaction();
            }
        }
        private void Application_EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(
                NHibernateHelper.SessionFactory);

            if (session != null)
            {
                try
                {
                    session.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    //Server.Transfer("...", true); // Error page
                }
            }
コード例 #23
0
        protected void deleteCommand()
        {
            DomainObject entity = (DomainObject)getSelectedEntity();

            if (entity == null)
            {
                return;
            }
            if (!MessageDialogs.queryConfirmation(deleteConfirmationMessage(entity), this.Text))
            {
                return;
            }

            try
            {
                using (ISession session = NHibernateHelper.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        if (refIntegrityDeleteDlg(entity))
                        {
                            delete(entity);
                            session.Transaction.Commit();
                            onEntityDeleted(entity);
                        }
                    }
            }
            catch (InfrastructureException ex)
            {
                string errMsg = deleteErrorMessage(entity);
                MessageDialogs.showError(
                    String.Format("{0} \n\n{1}", errMsg, ex.Message),
                    this.Text);
            }
            catch (Exception ex)
            {
                string errMsg = deleteErrorMessage(entity);
                MessageDialogs.showError(
                    String.Format("{0} \n\n{1}", errMsg, ex.Message),
                    this.Text);
            }
            finally
            {
                CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
            }
        }
コード例 #24
0
        public IDisposable OpenScope()
        {
            if (CurrentSessionContext.HasBind(sessionFactory))
            {
                //return new FlushDisposer(sessionFactory.GetCurrentSession());
                return(new NullDisposable());
            }

            var session = sessionFactory.OpenSession();

            session.BeginTransaction();
            session.FlushMode = FlushMode.Commit;

            CurrentSessionContext.Bind(session);

            return(new CurrentSessionContextDisposer(sessionFactory));
        }
コード例 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PersistenceContext"/> class.
        /// </summary>
        /// <param name="createNewScope">if set to <c>true</c> [create new scope].</param>
        internal PersistenceContext(bool createNewScope)
        {
            afterCommitActions = new List <Action>();

            if (!CurrentSessionContext.HasBind(PersistenceHelper.SessionFactory))
            {
                var session = PersistenceHelper.SessionFactory.OpenSession();

                CurrentSessionContext.Bind(session);
                Transaction = session.BeginTransaction();
                //TransactionScope = new TransactionScope();
            }

            Session = PersistenceHelper.SessionFactory.GetCurrentSession();
            //Session.FlushMode = FlushMode.Auto;
            Commits = new List <bool>();
        }
        public void Ambient_session_can_be_accessed_from_anywhere_in_the_code()
        {
            using (var session = SessionFactory.OpenSession())
            {
                //This goes to the infrastructure (WCF Message Inspector, ASP.NET Http Module)
                CurrentSessionContext.Bind(session);
                HandleWebRequest();
                CurrentSessionContext.Unbind(SessionFactory);
            }

            //Validate
            using (var session = SessionFactory.OpenSession())
            {
                var customer = session.Get <Customer>(FirstCustomerId);
                customer.FirstName.Should().Be("John");
            }
        }
コード例 #27
0
    private IDictionary <ClanGodinaMesec, ISet> getDolasciMapJedanDnevniTrening()
    {
        ISession session = null;

        try
        {
            using (session = NHibernateHelper.Instance.OpenSession())
                using (session.BeginTransaction())
                {
                    CurrentSessionContext.Bind(session);
                    IDictionary <ClanGodinaMesec, ISet> dolasciMap = new Dictionary <ClanGodinaMesec, ISet>();
                    foreach (DolazakNaTrening d in DAOFactoryFactory.DAOFactory.GetDolazakNaTreningDAO().FindAll())
                    {
                        ClanGodinaMesec key = new ClanGodinaMesec(d.Clan.Id, d.DatumDolaska.Value.Year,
                                                                  d.DatumDolaska.Value.Month);
                        if (!dolasciMap.ContainsKey(key))
                        {
                            ISet daniSet = new HashedSet();
                            daniSet.Add(d.DatumDolaska.Value.Day);
                            dolasciMap.Add(key, daniSet);
                        }
                        else
                        {
                            ISet daniSet = dolasciMap[key];
                            if (!daniSet.Contains(d.DatumDolaska.Value.Day))
                            {
                                daniSet.Add(d.DatumDolaska.Value.Day);
                            }
                        }
                    }
                    return(dolasciMap);
                }
        }
        catch (Exception ex)
        {
            if (session != null && session.Transaction != null && session.Transaction.IsActive)
            {
                session.Transaction.Rollback();
            }
            throw new InfrastructureException(ex.Message, ex);
        }
        finally
        {
            CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory);
        }
    }
コード例 #28
0
        public void ReturnTrueWhenContainsEntity()
        {
            var ent = new InheritedEntity();

            ConfigurationManager.Instance.AddInMemorySqLiteEnvironment <InheritedEntityMap>("Test");
            var conn    = ConfigurationManager.Instance.GetConfiguration("Test").GetConnection();
            var fact    = ConfigurationManager.Instance.GetConfiguration("Test").GetSessionFactory();
            var session = fact.OpenSession(conn);

            ConfigurationManager.Instance.GetConfiguration("Test").BuildSchema(session);
            CurrentSessionContext.Bind(session);

            var repos = new InheritedRepository(fact);

            repos.Add(ent);
            Assert.IsTrue(repos.Contains(ent));
        }
コード例 #29
0
        public SessionContext()
        {
            try
            {
                CurrentSession();
                DisposeSession();
            }
// ReSharper disable EmptyGeneralCatchClause
            catch
// ReSharper restore EmptyGeneralCatchClause
            {}
            finally
            {
                var session = GenFormApplication.SessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            }
        }
コード例 #30
0
    private void Application_BeginRequest(object sender, EventArgs e)
    {
        ISession session = NHibernateHelper.OpenSession();

        session.BeginTransaction();
        CurrentSessionContext.Bind(session);
        session.EnableFilter("allaircrafts").SetParameter("Status", (short)2);
        session.EnableFilter("alloperators").SetParameter("Status", 2);
        session.EnableFilter("allbids").SetParameter("Status", (short)2);
        session.EnableFilter("allrequests").SetParameter("Status", (short)2);
        session.EnableFilter("allagents").SetParameter("Status", 2);
        session.EnableFilter("allcustomers").SetParameter("Status", 2);
        session.EnableFilter("alloperatorrequests").SetParameter("Status", (short)2);
        session.EnableFilter("allemptylegs").SetParameter("Status", 2);
        session.EnableFilter("allemptylegoffers").SetParameter("Status", 2);
        session.EnableFilter("allfixedpricecharters").SetParameter("Status", 2);
    }