public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            ISession session = CurrentSessionContext.Unbind(NHibernateConfiguration.SessionFactory);

            if (session == null)
            {
                return;
            }

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

            session.Dispose();
        }
        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 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();
        }
Exemple #4
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);
                }
            }
        }
        //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;
        }
Exemple #6
0
        public void Rollback()
        {
            ISession session = CurrentSessionContext.Unbind(this.sessionFactory);

            if (session == null)
            {
                return;
            }

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

            session.Dispose();
        }
Exemple #7
0
        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);
            }
        }
Exemple #8
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);
            }
        }
        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");
            }
        }
Exemple #10
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);
        }
    }
Exemple #11
0
 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();
                 }
             }
         }
     }
 }
        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();
            }
        }
        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
                }
            }
        // Evento executado toda vez que uma requisição finaliza
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var session = CurrentSessionContext.Unbind(sessionFactory);

            if (session == null)
            {
                return;
            }
            try
            {
                session.Flush();
                if (session.Transaction.IsActive)
                {
                    if (HttpContext.Current.Server.GetLastError() == null)
                    {
                        try
                        {
                            session.Transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            var destino = Request.UrlReferrer.AbsoluteUri;

                            if (!destino.Contains("ConstraintViolation"))
                            {
                                destino += (destino.Contains("?") ? "&" : "?") + "ConstraintViolation=true";
                            }

                            Response.Redirect(destino);

                            session.Transaction.Rollback();
                        }
                    }
                    else
                    {
                        session.Transaction.Rollback();
                    }
                }
            }
            finally
            {
                Transaction.Current = null;
                session.Dispose();
            }
        }
        private void btnDeleteKategorija_Click(object sender, EventArgs e)
        {
            if (SelectedKategorija == null)
            {
                return;
            }
            string msgFmt = "Da li zelite da izbrisete kategoriju '{0}'?";

            if (!MessageDialogs.queryConfirmation(String.Format(msgFmt, SelectedKategorija), this.Text))
            {
                return;
            }

            ISession session = null;

            try
            {
                using (session = NHibernateHelper.Instance.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        deleteKategorija(SelectedKategorija);

                        Takmicenje t = DAOFactoryFactory.DAOFactory.GetTakmicenjeDAO().FindById(takmicenjeId);
                        t.LastModified = DateTime.Now;
                        session.Transaction.Commit();

                        // reload kategorije
                        setKategorije(DAOFactoryFactory.DAOFactory.GetTakmicarskaKategorijaDAO().FindByTakmicenje(takmicenjeId));
                    }
            }
            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);
            }
        }
        private void btnAddKategorija_Click(object sender, EventArgs e)
        {
            TakmicarskaKategorijaForm form = null;

            try
            {
                form = new TakmicarskaKategorijaForm(null, takmicenjeId);
                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);
                        // reload kategorije
                        setKategorije(DAOFactoryFactory.DAOFactory.GetTakmicarskaKategorijaDAO().FindByTakmicenje(takmicenjeId));
                        SelectedKategorija = (TakmicarskaKategorija)form.Entity;
                    }
            }
            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);
            }
        }
Exemple #17
0
        public KategorijeGimnasticaraForm()
        {
            // NOTE: Kada form nasledjuje drugi form koji ima genericki parametar,
            // dizajner nece da ga prikaze. Zato sam izbacio fajl
            // GimnasticariForm.Designer.cs (jer je nepotreban) i poziv
            // InitializeComponent(). Ukoliko form treba da dodaje neke kontrole
            // (osim onih koje je nasledio), to treba da se radi programski.

            this.Text          = "Kategorije gimnasticara";
            pnlFilter.Visible  = false;
            btnRefresh.Visible = false;
            dataGridViewUserControl1.GridColumnHeaderMouseClick +=
                new EventHandler <GridColumnHeaderMouseClickEventArgs>(DataGridViewUserControl_GridColumnHeaderMouseClick);
            InitializeGridColumns();

            ISession session = null;

            try
            {
                using (session = NHibernateHelper.Instance.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        IList <KategorijaGimnasticara> kategorije
                            = DAOFactoryFactory.DAOFactory.GetKategorijaGimnasticaraDAO().FindAll();
                        SetItems(kategorije);
                        dataGridViewUserControl1.sort <KategorijaGimnasticara>(
                            new string[] { "Naziv" },
                            new ListSortDirection[] { ListSortDirection.Ascending });
                        updateEntityCount();
                    }
            }
            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);
            }
        }
Exemple #18
0
 public BiracClanaDialog()
 {
     InitializeComponent();
     try
     {
         using (ISession session = NHibernateHelper.Instance.OpenSession())
             using (session.BeginTransaction())
             {
                 CurrentSessionContext.Bind(session);
                 loadData();
                 initUI();
             }
     }
     finally
     {
         CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory);
     }
 }
Exemple #19
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                var session = CurrentSessionContext.Unbind(sessionFactory);
                if (session == null)
                {
                    return;
                }

                session.Flush();
                if (session.GetCurrentTransaction()?.IsActive == true)
                {
                    session.GetCurrentTransaction().Commit();
                }
                session.Dispose();
            }
        }
Exemple #20
0
 public void CommitTransaction()
 {
     try
     {
         if (CurrentSessionContext.HasBind(_sessionFactory))
         {
             using (ISession session = _sessionFactory.GetCurrentSession())
             {
                 session.Transaction.Commit();
                 CurrentSessionContext.Unbind(_sessionFactory);
             }
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemple #21
0
        public static ISession GetSession()
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                CurrentSessionContext.Bind(sessionFactory.OpenSession());
            }

            var session = sessionFactory.GetCurrentSession();

            if (!session.IsOpen || !session.IsConnected)
            {
                CurrentSessionContext.Unbind(sessionFactory);
                session = sessionFactory.OpenSession();
                CurrentSessionContext.Bind(session);
            }
            session.FlushMode = FlushMode.Commit;
            return(session);
        }
Exemple #22
0
 private void initialize()
 {
     try
     {
         using (ISession session = NHibernateHelper.OpenSession())
             using (session.BeginTransaction())
             {
                 CurrentSessionContext.Bind(session);
                 grupe = DAOFactoryFactory.DAOFactory.GetGrupaDAO().FindAll();
                 initUI();
                 showEntityDetails();
             }
     }
     finally
     {
         CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
     }
 }
Exemple #23
0
 public OsnovniPodaciVezbeForm()
 {
     InitializeComponent();
     try
     {
         using (ISession session = NHibernateHelper.OpenSession())
             using (session.BeginTransaction())
             {
                 CurrentSessionContext.Bind(session);
                 pravila = new List <PraviloOceneVezbe>(DAOFactoryFactory.DAOFactory.GetPraviloOceneVezbeDAO().FindAll());
                 initUI();
             }
     }
     finally
     {
         CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
     }
 }
Exemple #24
0
        public void CloseSession()
        {
            ISession session = Session;

            if (Settings.IsWebEnvironment)
            {
                if (CurrentSessionContext.HasBind(SessionFactory))
                {
                    session = CurrentSessionContext.Unbind(SessionFactory);
                }
            }

            if (session?.Transaction?.IsActive ?? false)
            {
                session.Transaction.Rollback();
            }
            session?.Dispose();
        }
Exemple #25
0
        public void PostProceed(string methodName)
        {
            ISession session = CurrentSessionContext.Unbind(this.sessionFactory);

            if (session == null)
            {
                return;
            }

            if (this.Guard(methodName))
            {
                if (session.Transaction.IsActive)
                {
                    session.Transaction.Commit();
                }
            }
            session.Dispose();
        }
        public void Handle(T message)
        {
            ISession session = _sessionFactory.OpenSession();

            CurrentSessionContext.Bind(session);
            ITransaction trans = session.BeginTransaction();

            try
            {
                DoHandle(message);
                trans.Commit();
            }
            finally
            {
                CurrentSessionContext.Unbind(_sessionFactory);
                session.Dispose();
            }
        }
Exemple #27
0
        public GimnasticariForm()
        {
            this.Text       = "Gimnasticari";
            this.ClientSize = new System.Drawing.Size(Screen.PrimaryScreen.WorkingArea.Width - 20, 540);
            this.btnUveziIzBiltena.Visible = true;
            this.btnUveziIzBiltena.Click  += btnUveziIzBiltena_Click;
            this.btnPrintPreview.Visible   = true;
            this.btnPrintPreview.Text      = "Rezultati";
            this.btnPrintPreview.Click    += btnRezultati_Click;

            dataGridViewUserControl1.GridColumnHeaderMouseClick +=
                new EventHandler <GridColumnHeaderMouseClickEventArgs>(DataGridViewUserControl_GridColumnHeaderMouseClick);
            dataGridViewUserControl1.ShowBooleanFalse = false;
            InitializeGridColumns();

            ISession session = null;

            try
            {
                using (session = NHibernateHelper.Instance.OpenSession())
                    using (session.BeginTransaction())
                    {
                        CurrentSessionContext.Bind(session);
                        IList <Gimnasticar> gimnasticari = DAOFactoryFactory.DAOFactory.GetGimnasticarDAO().FindAll();
                        SetItems(gimnasticari);
                        dataGridViewUserControl1.sort <Gimnasticar>(
                            new string[] { "Prezime", "Ime" },
                            new ListSortDirection[] { ListSortDirection.Ascending, ListSortDirection.Ascending });
                        updateEntityCount();
                    }
            }
            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);
            }
        }
        /// <summary>
        /// The processing.
        /// </summary>
        /// <param name="file">
        /// The file.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override bool Processing(FileInfo file, IJobExecutionContext context)
        {
            try
            {
                var oidManager = ObjectFactory.GetInstance <IOidManager>();
                var oid        = oidManager.SingleOrDefault(x => x.Id == Oid);
                var queue      = new ConcurrentQueue <Organisation>();
                using (var orgCollection = Task.Factory.StartNew(
                           () =>
                {
                    var session =
                        ObjectFactory.GetInstance <ISessionFactory>().OpenSession();
                    CurrentSessionContext.Bind(session);
                    var res = PrepairXml(file, queue, oid);
                    var sessionFactory =
                        ObjectFactory.GetInstance <ISessionFactory>();
                    session = CurrentSessionContext.Unbind(sessionFactory);

                    if (session != null)
                    {
                        if (session.Transaction != null &&
                            session.Transaction.IsActive)
                        {
                            session.Transaction.Dispose();
                        }

                        session.Flush();
                        session.Clear();
                        session.Close();
                        session.Dispose();
                    }

                    return(res);
                }))
                {
                    return(SaveToBase(queue, orgCollection, context));
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
        /// <summary>
        ///   Close the persistence session.
        /// </summary>
        public virtual void CloseSession()
        {
            try
            {
                if (!IsSessionOpened)
                {
                    Log.Info("Closing NHibernate Session - Session is not open");
                    return;
                }

                Log.Info("Closing NHibernate Session");
                CurrentSession.Close();
                CurrentSession.Dispose();
            }
            finally
            {
                CurrentSessionContext.Unbind(sessionFactory);
            }
        }
Exemple #30
0
        /// <summary>
        /// Pauses the conversation. Call this (or <see cref="EndConversation"/>) from Application_EndRequest
        /// </summary>
        public void PauseConversation()
        {
            ISession session = CurrentSessionContext.Unbind(SessionFactory);

            if (session == null)
            {
                return;
            }
            try
            {
                session.Transaction.Commit(); //with flushMode=Never, this closes connections but doesn't flush
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
                throw;
            }
            //we don't close the session, and it's still in Asp SessionState
        }