示例#1
0
 public IList <T> Consultar()
 {
     using (NHibernate.ISession session = SessionFactory.AbrirSession())
     {
         return((from c in session.Query <T>() select c).ToList());
     }
 }
示例#2
0
        /// <summary>
        /// DbService.getAll<User>();
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>

        public static ICollection <T> GetAll <T>()
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                return(session.CreateCriteria(typeof(T)).List <T>());
            }
        }
示例#3
0
 public T RetornarPorId(int Id)
 {
     using (NHibernate.ISession session = SessionFactory.AbrirSession())
     {
         return(session.Get <T>(Id));
     }
 }
示例#4
0
        /// <summary>
        /// 根据查询条件创建Criteria
        /// </summary>
        /// <param name="session"></param>
        /// <param name="searchExpression"></param>
        /// <param name="searchOrders"></param>
        /// <param name="hasCollection"></param>
        /// <returns></returns>
        public static NHibernate.ICriteria CreateCriteria(NHibernate.ISession session, ISearchExpression searchExpression,
                                                          IList <ISearchOrder> searchOrders, ref bool hasCollection)
        {
            hasCollection = false;
            int paramCnt = 0;

            NHibernate.ICriteria           criteria = session.CreateCriteria(typeof(T), "Current");
            Dictionary <string, ICriteria> aliases  = new Dictionary <string, ICriteria>();

            aliases.Add("Current", criteria);

            NHibernate.Criterion.ICriterion criterion = GetCriterion(session.SessionFactory, ref criteria, aliases, searchExpression, ref hasCollection, ref paramCnt);
            if (criterion != null)
            {
                criteria.Add(criterion);
            }
            if (paramCnt > 2100)
            {
                throw new NotSupportedException("您输入的参数过多,系统最多只支持2100个参数!");
            }

            if (searchOrders != null)
            {
                foreach (ISearchOrder so in searchOrders)
                {
                    criteria.AddOrder(GetOrder(ref criteria, aliases, so));
                }
            }

            return(aliases["Current"]);
        }
        private void RegisterAccount(NHibernate.ISession session, UserAccountEF user, string aggregatorGroupId)
        {
            switch (user.UserType)
            {
            case RegisterType.Contrator:
                ContractorUser cu = new ContractorUser();
                cu.AggGroupId     = aggregatorGroupId;
                cu.ContractStatus = (int)ContractStatusCodes.Signing;
                cu.UserId         = user.Id;
                session.SaveAsync(cu);
                Task t = _userManager.AddToRoleAsync(user, UserRoleTypes.Contractor);
                t.Wait();
                break;

            //case RegisterType.Supervisor:
            //    var role_add_result = await _userManager.AddToRoleAsync(user, UserRoleTypes.Supervisor);
            //    //_userManager.AddClaimAsync(user, new Claim())
            //    SupervisorUser supervisorUser = new SupervisorUserEF();
            //    supervisorUser.UserId = user.Id;
            //    await _accountContext.SupervisorUsers.AddAsync(supervisorUser);
            //    break;
            case RegisterType.Aggregator:
                Task ta = _userManager.AddToRoleAsync(user, UserRoleTypes.Aggregator);
                ta.Wait();
                //_userManager.AddClaimAsync(user, new Claim())
                AggregatorUser aggregatorUser = new AggregatorUser();
                aggregatorUser.AggGroupId = aggregatorGroupId;
                aggregatorUser.UserId     = user.Id;
                session.SaveAsync(aggregatorUser);
                break;
            }
        }
示例#6
0
 public static T Find <T>(int id)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         return(session.Get <T>(id));
     }
 }
示例#7
0
        /// <getTasksByUserwithDetail>
        /// Get Tasks By User with Detail
        /// </summary>
        /// <param name="USerId">User id.(Guid)</param>
        /// <param name="days">Number of Days.(int)</param>
        /// <returns>Return values in the form of array list.(ArrayList)</returns>
        public ArrayList getTasksByUserwithDetail(Guid USerId, int days, Guid GroupId)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    //Proceed action, to get details of task. //ts.UserId=:userid and //.SetParameter("userid", USerId)
                    //var queryString = @"SELECT * FROM Tasks ts LEFT JOIN User u on ts.AssignTaskTo=u.Id where ts.UserId=:userid and AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                    //var queryString = @"SELECT * FROM Tasks ts LEFT JOIN User u on ts.AssignTaskTo=u.Id where ts.GroupId=:GroupId and  AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                    try
                    {
                        var queryString = @"select * from tasks where (AssignTaskTo =:userid or UserId =:userid) and GroupId =:GroupId and  AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                        var query       = session.CreateSQLQuery(queryString)
                                          .SetParameter("userid", USerId)
                                          .SetParameter("GroupId", GroupId);
                        //.SetParameter("GroupId", GroupId);

                        ArrayList alstTask = new ArrayList();

                        foreach (var item in query.List())
                        {
                            alstTask.Add(item);
                        }
                        return(alstTask);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                } //End Transaction
            }     //End Session
        }
示例#8
0
 public ActionResult Create(NewTopicModel topic)
 {
     using (NHibernate.ISession session = nHibernateHelper.OpenSession())
     {
         using (ITransaction transaction = session.BeginTransaction())
         {
             var aTopic = new Topic
             {
                 Category = session.Query <Category>().Single(x => x.Id == topic.CategoryId),
                 Name     = topic.Name,
                 Date     = DateTime.Now,
                 User     = session.Query <User>().Single(x => x.Email == User.Identity.Name),
                 IsClosed = false,
             };
             var initMsg = new ForumMessage
             {
                 Text  = topic.InitialText,
                 User  = aTopic.User,
                 Date  = aTopic.Date,
                 Topic = aTopic,
             };
             aTopic.Messages.Add(initMsg);
             session.SaveOrUpdate(aTopic);
             session.SaveOrUpdate(initMsg);
             transaction.Commit();
             var dbTopic = session.Query <Topic>().Single(x => x.Name == aTopic.Name && x.Date == aTopic.Date);
             return(CreatedAtRoute("GetTopic", new { id = dbTopic.Id }, new TopicAPIModel(dbTopic)));
         }
     }
 }
示例#9
0
 /// <updateTask>
 /// Update Task
 /// </summary>
 /// <param name="task">Set Values in a Tasks Class Property and Pass the Object of Tasks Class.(Domein.Tasks)</param>
 public void updateTask(Tasks task)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to update task
                 session.CreateQuery("Update Tasks set TaskMessage =:TaskMessage,UserId =:UserId,AssignTaskTo =:AssignTaskTo,TaskStatus=:TaskStatus,AssignDate=:AssignDate where Id = :taskid and UserId = :userid")
                 .SetParameter("TaskMessage", task.TaskMessage)
                 .SetParameter("UserId", task.UserId)
                 .SetParameter("AssignTaskTo", task.AssignTaskTo)
                 .SetParameter("TaskStatus", task.TaskStatus)
                 .SetParameter("AssignDate", task.AssignDate)
                 .SetParameter("taskid", task.Id)
                 .SetParameter("userid", task.UserId)
                 .ExecuteUpdate();
                 transaction.Commit();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 // return 0;
             }
         } //End Transaction
     }     //End Session
 }
示例#10
0
        public List <Domain.Socioboard.Domain.Tasks> getAllTasksOfUserBYDays(Guid Userid, Guid GroupId, int days)
        {
            List <Domain.Socioboard.Domain.Tasks> alstTask = new List <Domain.Socioboard.Domain.Tasks>();

            try
            {
                //Creates a database connection and opens up a session
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    //After Session creation, start Transaction.
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        DateTime AssignDate = DateTime.Now;
                        string   AssinDate  = AssignDate.AddDays(-days).ToString("yyyy-MM-dd HH:mm:ss");
                        //Proceed action, to get all task of user.
                        //NHibernate.IQuery query = session.CreateQuery("from Tasks where (UserId = :Userid or AssignTaskTo =:Userid) and GroupId =:GroupId and AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)");
                        NHibernate.IQuery query = session.CreateQuery("from Tasks where UserId = :Userid  and GroupId =:GroupId and AssignDate>=:AssinDate");
                        query.SetParameter("Userid", Userid);
                        query.SetParameter("GroupId", GroupId);
                        query.SetParameter("AssinDate", AssinDate);

                        foreach (var item in query.Enumerable())
                        {
                            alstTask.Add((Domain.Socioboard.Domain.Tasks)item);
                        }
                    } //End Transaction
                }     //End Session
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.StackTrace);
            }
            return(alstTask);
        }
示例#11
0
 /// <deleteTask>
 /// Delete Task
 /// </summary>
 /// <param name="taskid">Task id.(String)</param>
 /// <param name="userid">User id.(Guid)</param>
 /// <returns>Return 1 for true and 0 for false.(int)</returns>
 public int deleteTask(string taskid, Guid userid)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to delete task by task id and user id.
                 NHibernate.IQuery query = session.CreateQuery("delete from Task where Id = :taskid and UserId = :userid")
                                           .SetParameter("taskid", taskid)
                                           .SetParameter("userid", userid);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return(isUpdated);
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return(0);
             }
         } //End Transaction
     }     //End Session
 }
示例#12
0
        public int UpdateQuery(GroupCampaign groupCamp)
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    var query = session.CreateQuery("Update GroupCampaign set Account=:Account,PicFilePath=:PicFilePath,VideoFilePath=:VideoFilePath,MessageFilepath=:MessageFilepath,ScheduleTime=:ScheduleTime,CmpStartTime=:CmpStartTime,Accomplish=:Accomplish,NoOfMessage=:NoOfMessage,MessageMode=:MessageMode,MessageType=:MessageType,TextMessage=:TextMessage where GroupCampaignName=:GroupCampaignName and Module =:module");
                    //session.SaveOrUpdate(groupCamp);
                    query.SetParameter("GroupCampaignName", groupCamp.GroupCampaignName);
                    query.SetParameter("Account", groupCamp.Account);
                    query.SetParameter("PicFilePath", groupCamp.PicFilePath);
                    query.SetParameter("VideoFilePath", groupCamp.VideoFilePath);
                    query.SetParameter("MessageFilepath", groupCamp.MessageFilePath);
                    query.SetParameter("ScheduleTime", groupCamp.ScheduleTime);
                    query.SetParameter("CmpStartTime", groupCamp.CmpStartTime);
                    query.SetParameter("Accomplish", groupCamp.Accomplish);
                    query.SetParameter("NoOfMessage", groupCamp.NoOfMessage);

                    query.SetParameter("MessageMode", groupCamp.MessageMode);
                    query.SetParameter("MessageType", groupCamp.MessageType);
                    query.SetParameter("TextMessage", groupCamp.TextMessage);
                    query.SetParameter("module", groupCamp.Module);
                    int res = query.ExecuteUpdate();
                    transaction.Commit();
                    return(res);
                }
            }
        }
示例#13
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="database">The database.</param>
 /// <param name="crypto">The crypto.</param>
 /// <param name="sessionFactory">The session factory.</param>
 public UserRepository(ISession session, IDatabase database, ICrypto crypto, ISessionFactory sessionFactory)
 {
     _session = session;
     _database = database;
     _crypto = crypto;
     _sessionFactory = sessionFactory;
 }
        public ActionResult Edit(int id, Tarefa tarefa)
        {
            try
            {
                // TODO: Add update logic here
                using (NHibernate.ISession session = NHibernateHelper.AbreSessao())
                {
                    var tarefaAlterado = session.Get <Tarefa>(id);
                    tarefaAlterado.Id            = tarefa.Id;
                    tarefaAlterado.Titulo        = tarefa.Titulo;
                    tarefaAlterado.Descricao     = tarefa.Descricao;
                    tarefaAlterado.Data_Cadastro = tarefa.Data_Cadastro;
                    tarefaAlterado.Data_Entrega  = tarefa.Data_Entrega;
                    using (ITransaction transacao = session.BeginTransaction())
                    {
                        session.Save(tarefaAlterado);
                        transacao.Commit();
                    }
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
示例#15
0
 public ActionResult <ISet <CategoryAPIModel> > GetAll()
 {
     using (NHibernate.ISession session = nHibernateHelper.OpenSession())
     {
         return(session.Query <Category>().Select(x => new CategoryAPIModel(x, false)).ToHashSet());
     }
 }
示例#16
0
        public GroupingControlForm(NHibernate.ISessionFactory sessionFactory)
        {
            InitializeComponent();

            this.session = sessionFactory.OpenSession();

            tlvGroupedFiles.CanExpandGetter += x => (((tlvBranch)x).Data is SpectrumSourceGroup && ((tlvBranch)x).Children.Any());
            tlvGroupedFiles.ChildrenGetter  += getChildren;
            tlvGroups.AspectGetter          += x =>
            {
                var nodeTracker      = ((tlvBranch)x);
                var offsetCorrection = 0;
                while (nodeTracker.Parent.Text != null)
                {
                    offsetCorrection++;
                    nodeTracker = nodeTracker.Parent;
                }
                return(((tlvBranch)x).Text + new string(' ', offsetCorrection *7));
            };
            tlvGroups.AutoCompleteEditor = false;

            tlvGroups.ImageGetter += delegate(object x) { return((((tlvBranch)x).Data is SpectrumSourceGroup) ? Properties.Resources.XPfolder_closed : Properties.Resources.file); };

            ApplyDefaultGroups(null, null);
        }
示例#17
0
        public ActionResult Edit(int id, Cat cat)
        {
            try
            {
                using (NHibernate.ISession session = _sessionFactory.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        var catUpdate = session.Get <Cat>(id);

                        if (catUpdate != null && ModelState.IsValid)
                        {
                            catUpdate.Name = cat.Name;
                            catUpdate.Sex  = cat.Sex;
                            cat.Weight     = cat.Weight;
                            session.Merge <Cat>(cat);
                            transaction.Commit();
                        }
                    }
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                return(View(ex));
            }
        }
示例#18
0
 /// <DeleteDiscoverySearchByUserid>
 /// Delete DiscoverySearch from database by userId(Guid)
 /// </summary>
 /// <param name="userid">UserId of DiscoverySearch(Guid)</param>
 /// <returns>Return integer 1 for true 0 for false</returns>
 public int DeleteDiscoverySearchByUserid(Guid userid)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action to delete discoverysearch by userid.
                 NHibernate.IQuery query = session.CreateQuery("delete from DiscoverySearch where UserId = :userid")
                                           .SetParameter("userid", userid);
                 int isUpdated = query.ExecuteUpdate();
                 transaction.Commit();
                 return(isUpdated);
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return(0);
             }
         } //End Transaction
     }     //End session
 }
示例#19
0
        /// <summary>
        /// 通过EPCID查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="isSetSupplier"></param>
        /// <param name="isSetSpec"></param>
        /// <returns></returns>
        public AscmContainer GetByEpcId(string epcId, string sessionKey = null)
        {
            AscmContainer ascmContainer = null;

            try
            {
                NHibernate.ISession session = YnDaoHelper.GetInstance().nHibernateHelper.GetCurrentSession();
                if (sessionKey != null)
                {
                    session = YnDaoHelper.GetInstance().nHibernateHelper.GetCurrentSession(sessionKey);
                }
                NHibernate.IQuery query = session.CreateQuery("from AscmContainer where rfid='" + epcId + "' ");
                if (query.List().Count > 0)
                {
                    ascmContainer = query.UniqueResult <AscmContainer>();
                    if (!string.IsNullOrEmpty(ascmContainer.supplierId.ToString()))
                    {
                        ascmContainer.supplier = MideaAscm.Services.Base.AscmSupplierService.GetInstance().Get(ascmContainer.supplierId, sessionKey);
                    }
                    if (!string.IsNullOrEmpty(ascmContainer.specId.ToString()))
                    {
                        ascmContainer.containerSpec = MideaAscm.Services.SupplierPreparation.AscmContainerSpecService.GetInstance().Get(ascmContainer.specId, sessionKey);
                    }
                }
            }
            catch (Exception ex)
            {
                YnBaseClass2.Helper.LogHelper.GetLog().Error("查询失败(Find AscmContainer)", ex);
                throw ex;
            }
            return(ascmContainer);
        }
示例#20
0
        /// <getResultsFromKeyword>
        /// Get result from database by keyword
        /// </summary>
        /// <param name="keyword">Keyword of DiscoverySearch(string)</param>
        /// <returns>List of all results by Keyword</returns>
        public List <Domain.Myfashion.Domain.DiscoverySearch> getResultsFromKeyword(string keyword)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //proceed action to get all results by Keyword.
                        List <Domain.Myfashion.Domain.DiscoverySearch> lst = session.CreateQuery("from DiscoverySearch where SearchKeyword = :keyword")
                                                                             .SetParameter("keyword", keyword)
                                                                             .List <Domain.Myfashion.Domain.DiscoverySearch>()
                                                                             .ToList <Domain.Myfashion.Domain.DiscoverySearch>();

                        #region Oldcode
                        //foreach (DiscoverySearch item in query.Enumerable())
                        //{
                        //    lst.Add(item);
                        //}
                        #endregion
                        return(lst);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return(null);
                    }
                } //End Transaction
            }     //End session
        }
示例#21
0
        public GroupingControlForm(NHibernate.ISessionFactory sessionFactory)
        {
            InitializeComponent();

            this.session = sessionFactory.OpenSession();

            tlvGroupedFiles.CanExpandGetter += x => (((tlvBranch)x).Data is SpectrumSourceGroup && ((tlvBranch)x).Children.Any());
            tlvGroupedFiles.ChildrenGetter += getChildren;
            tlvGroups.AspectGetter += x =>
                                          {
                                              var nodeTracker = ((tlvBranch) x);
                                              var offsetCorrection = 0;
                                              while (nodeTracker.Parent.Text != null)
                                              {
                                                  offsetCorrection++;
                                                  nodeTracker = nodeTracker.Parent;
                                              }
                                              return ((tlvBranch) x).Text + new string(' ',offsetCorrection*7);
                                          };
            tlvGroups.AutoCompleteEditor = false;

            tlvGroups.ImageGetter += delegate(object x) { return (((tlvBranch)x).Data is SpectrumSourceGroup) ? Properties.Resources.XPfolder_closed : Properties.Resources.file; };

            ApplyDefaultGroups(null, null);
        }
示例#22
0
 /// <summary>
 /// 得到最新的一次流转记录
 /// 根据EPCID得到
 /// </summary>
 /// <param name="strEpcId">根据EPCID</param>
 /// <returns></returns>
 public string Get(string strEpcId)
 {
     try
     {
         using (NHibernate.ISession session = YnDaoHelper.GetInstance().nHibernateHelper.GetCurrentSession())
         {
             if (session.IsOpen)
             {
                 NHibernate.IQuery query      = session.CreateQuery("from AscmTagLog where readTime in (select to_char(max(to_date(readTime,'yyyy-MM-dd HH24:mi:ss')),'yyyy-MM-dd HH24:mi:ss') from AscmTagLog  where epcId='" + strEpcId + "' ) and epcId='" + strEpcId + "' ");
                 AscmTagLog        ascmTagLog = query.UniqueResult <AscmTagLog>();
                 if (ascmTagLog != null)
                 {
                     object obj = YnDaoHelper.GetInstance().nHibernateHelper.GetObject("select address from AscmReadingHead  where id=" + ascmTagLog.readingHeadId + "");
                     ascmTagLog.place = obj.ToString();
                     return
                         (YnBaseClass2.Helper.ObjectHelper.Serialize <AscmTagLog>(ascmTagLog));
                 }
                 else
                 {
                     return(null);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         YnBaseClass2.Helper.LogHelper.GetLog().Error("查询失败(Get AscmContainer)", ex);
         throw ex;
     }
     return(null);
 }
 /// <summary>
 /// 保存ISession
 /// </summary>
 /// <param name="value"></param>
 public void Set(NHibernate.ISession value)
 {
     if (value != null)
     {
         HttpContext.Current.Items["SessionNhb"] = value;
     }
 }
示例#24
0
 public NetworkController(
     NHibernate.ISession session,
     NHibernate.ISessionFactory sessionFactory)
 {
     _session        = session ?? throw new ArgumentNullException(nameof(session));
     _sessionFactory = sessionFactory ?? throw new ArgumentNullException(nameof(sessionFactory));
 }
示例#25
0
        public DefaultQuery(ISession nhsession, Services.ISession session)
        {
            _session   = session;
            _nhsession = nhsession;

            _joins = new Dictionary <string, IQueryOver <Document> >();
        }
示例#26
0
        /// <getAllTasksOfUser>
        /// Get All Tasks Of User
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns>Return values in the form of array list.(ArrayList)</returns>
        public ArrayList getAllTasksOfUser(Guid UserId, Guid GroupId)
        {
            ArrayList alstTask = new ArrayList();

            try
            {
                //Creates a database connection and opens up a session
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    //After Session creation, start Transaction.
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        //Proceed action, to get all task of user.
                        NHibernate.IQuery query = session.CreateQuery("from Tasks where UserId = :UserId and AssignTaskTo !=:UserId and GroupId =:GroupId");
                        query.SetParameter("UserId", UserId);
                        query.SetParameter("UserId", UserId);
                        query.SetParameter("GroupId", GroupId);


                        foreach (var item in query.Enumerable())
                        {
                            alstTask.Add(item);
                        }
                    } //End Transaction
                }     //End Session
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.StackTrace);
            }
            return(alstTask);
        }
示例#27
0
 public ActionResult <ISet <UserAPIModel> > GetAll()
 {
     using (NHibernate.ISession session = nHibernateHelper.OpenSession())
     {
         return(session.Query <User>().Select(x => new UserAPIModel(x)).ToHashSet());
     }
 }
示例#28
0
        /// <checkTaskExists>
        /// checkTaskExists
        /// </summary>
        /// <param name="TaskId">Task id.(String)</param>
        /// <param name="Userid">User id.(Guid)</param>
        /// <returns>True and False.(bool)</returns>
        public bool checkTaskExists(string TaskId, Guid Userid)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //Proceed action, to get task details by userid and task id.
                        NHibernate.IQuery query = session.CreateQuery("from Task where UserId = :userid and Id = :taskid");
                        query.SetParameter("userid", Userid);
                        query.SetParameter("taskid", TaskId);
                        var result = query.UniqueResult();

                        if (result == null)
                        {
                            return(false);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return(true);
                    }
                } //End Transaction
            }     //End Session
        }
示例#29
0
        public ActionResult Registration(Models.RegistrationModel reg_model)
        {
            if (Session["session_key"] != null)
            {
                return(RedirectToAction("index"));
            }
            using (NHibernate.ISession session = NHibernateSessionManeger.OpenSession())
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    NHibernate.IQuery query = session.CreateQuery("FROM Users WHERE name = '" + reg_model.Name + "'");
                    if (query.List <Models.Users>().Count() > 0)
                    {
                        ViewData["ErrorMessage"] = "    Пользователь с ником " + reg_model.Name + " уже занят   ";
                        return(View());
                    }

                    var usr = new Models.Users();
                    usr.Email = reg_model.Email;
                    usr.Name  = reg_model.Name;
                    var    salt             = Guid.NewGuid().ToByteArray();
                    string hashsed_password = Convert.ToBase64String(CryptSharp.Utility.SCrypt.ComputeDerivedKey(System.Text.UTF8Encoding.UTF8.GetBytes(reg_model.Password), salt, 16384, 8, 1, null, 128));
                    usr.HashPassword = hashsed_password;
                    usr.Salt         = Convert.ToBase64String(salt);
                    session.Save(usr);

                    return(RedirectToAction("authorization"));
                }
            }
        }
示例#30
0
 /// <updateTaskStatus>
 /// update Task Status
 /// </summary>
 /// <param name="TaskId">Task id.(guid)</param>
 /// <param name="UserId">User id.(Guid)</param>
 /// <param name="status">Status.(Bool)</param>
 public void updateTaskStatus(Guid TaskId, Guid UserId, bool status)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 //Proceed action, to get Task status and completion date by user id and task id.
                 session.CreateQuery("Update Tasks set TaskStatus=:TaskStatus, CompletionDate=:completedate where Id = :taskid and UserId = :userid")
                 .SetParameter("userid", UserId)
                 .SetParameter("taskid", TaskId)
                 .SetParameter("TaskStatus", status)
                 .SetParameter("completedate", DateTime.Now)
                 .ExecuteUpdate();
                 transaction.Commit();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 // return 0;
             }
         } //End Transaction
     }     //End Session
 }
示例#31
0
        public void AfterInvoke(object correlationState)
        {
            foreach (ISessionFactory sessionFactory in sfp)
            {
                ISession session = CurrentSessionContext.Unbind(sessionFactory);
                if (!session.IsOpen)
                {
                    continue;
                }

                try
                {
                    session.Flush();
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Commit();
                    }
                }
                catch (Exception)
                {
                    if (session.Transaction.IsActive)
                    {
                        session.Transaction.Rollback();
                    }
                    throw;
                }
                finally
                {
                    session.Close();
                    session.Dispose();
                }
            }
        }
        public void Initialize()
        {
            ShouldNotBeDisposed();

            CurrentSession = this.sessionFactory.CreateSession();

            isInitialized = true;
        }
示例#33
0
        public object Save <T>(T entity) where T : class
        {
            NH.ISession session = Session;
            object      obj     = session.Save(entity);

            session.Flush();
            return(obj);
        }
示例#34
0
        /// <summary>
        /// Save session factory statistics
        /// </summary>
        /// <param name="UUID"></param>
        /// <returns>Session factory</returns>
        public NHibernateProfiler.Common.Entity.Statistics.SessionFactory GetSessionFactoryStatistics(
            string UUID)
        {
            this.c_currentSessionFactoryStatisticsSession = this.c_sessionFactory.OpenSession();

            return c_currentSessionFactoryStatisticsSession.CreateCriteria<NHibernateProfiler.Common.Entity.Statistics.SessionFactory>()
                .Add(NHibernate.Criterion.Expression.Eq("UUID", UUID))
                .UniqueResult<NHibernateProfiler.Common.Entity.Statistics.SessionFactory>();
        }
示例#35
0
 public void Dispose()
 {
     if (_useSingleSession) return;
     if (transaction!=null && transaction != null)
     {
         transaction.Rollback();
         transaction.Dispose();
         transaction = null;
     }
     Session.Dispose();
     Session = null;
 }
示例#36
0
 public SessionWrapper(NHibernate.ISession s)
 {
     session = s;
 }
示例#37
0
        public void TestInitialize ()
        {
            TestContext.SetTestOutputSubdirectory(TestContext.FullyQualifiedTestClassName + "/" + TestContext.TestName);
            Directory.CreateDirectory(TestContext.TestOutputPath());
            File.Copy(TestContext.TestOutputPath("../testModel.idpDB"), TestContext.TestOutputPath("testModel.idpDB"));
            Directory.SetCurrentDirectory(TestContext.TestOutputPath());

            var sessionFactory = SessionFactoryFactory.CreateSessionFactory(TestContext.TestOutputPath("testModel.idpDB"));
            session = sessionFactory.OpenSession();
        }
示例#38
0
        void OpenFiles (IList<string> filepaths, TreeNode rootNode = null)
        {
            try
            {
                var xml_filepaths = filepaths.Where(filepath => !filepath.EndsWith(".idpDB"));
                var idpDB_filepaths = filepaths.Where(filepath => filepath.EndsWith(".idpDB"));
                bool openSingleFile = xml_filepaths.Count() + idpDB_filepaths.Count() == 1;

                if (xml_filepaths.Count() + idpDB_filepaths.Count() == 0)
                {
                    if (Program.IsHeadless)
                    {
                        Console.Error.WriteLine("Headless mode must be passed some idpDB files to merge.");
                        Close();
                        return;
                    }
                    else
                        throw new Exception("no filepaths to open");
                }

                if (Program.IsHeadless && xml_filepaths.Any())
                    Program.HandleUserError(new Exception("headless mode only supports merging and filtering idpDB files"));

                // warn if idpDBs already exist
                bool warnOnce = false, skipReconvert = false;
                var skipFiles = new List<string>();
                foreach (string filepath in xml_filepaths)
                {
                    string idpDB_filepath = Path.ChangeExtension(filepath.Replace(".pep.xml", ".pepXML"), ".idpDB");
                    if (File.Exists(idpDB_filepath))
                    {
                        if (!warnOnce && MessageBox.Show("Some of these files have already been converted. Do you want to reconvert them?",
                                                         "Result already converted",
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Exclamation,
                                                         MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                            skipReconvert = true;
                        warnOnce = true;
                        if (skipReconvert)
                            skipFiles.Add(filepath);
                        else
                            File.Delete(idpDB_filepath);
                    }
                }
                xml_filepaths = xml_filepaths.Where(o => !skipFiles.Contains(o));
                idpDB_filepaths = idpDB_filepaths.Union(skipFiles.Select(o => Path.ChangeExtension(o.Replace(".pep.xml", ".pepXML"), ".idpDB")));


                // determine if merged filepath exists and that it's a valid idpDB
                var potentialPaths = filepaths.Select(item =>
                                                      Path.Combine(Path.GetDirectoryName(item) ?? string.Empty,
                                                                   Path.GetFileNameWithoutExtension(item) ??

                                                                   string.Empty) + ".idpDB").ToList();

                // for Mascot files (*.dat), use parseSource() to get the real filename, else save time by just using filename without extension
                var sourceNames = filepaths.Select(o => Path.Combine(Path.GetDirectoryName(o), o.ToLower().EndsWith(".dat") ? Parser.ParseSource(o) : Path.GetFileNameWithoutExtension(o.Replace(".pep.xml", ".pepXML")) + Path.GetExtension(o)));

                string commonFilepath = Util.GetCommonFilename(sourceNames);
                if (!openSingleFile && potentialPaths.Contains(commonFilepath))
                    commonFilepath = commonFilepath.Replace(".idpDB", " (merged).idpDB");
                string mergeTargetFilepath = defaultMergedOutputFilepath ?? commonFilepath;
                if (!openSingleFile && File.Exists(mergeTargetFilepath) && Program.IsHeadless)
                    File.Delete(mergeTargetFilepath);
                else
                {
                    // check that the single idpDB is writable; if not, it needs to be copied
                    if (openSingleFile)
                    {
                        // sanity check that file exists after the path manipulation above
                        if (idpDB_filepaths.Count() == 1 && !File.Exists(mergeTargetFilepath))
                            throw new Exception(String.Format("error in internal path manipulation for opening single idpDB: {0} transformed to {1} which does not exist", sourceNames.First(), mergeTargetFilepath));

                        string oldFilename = mergeTargetFilepath;

                        while (true)
                        {
                            if (canReadWriteInDirectory(Path.GetDirectoryName(mergeTargetFilepath)))
                                break;

                            MessageBox.Show("IDPicker files cannot be opened from a read-only location, pick a writable path to copy it to.");

                            if (!saveFileDialog(ref mergeTargetFilepath))
                                return;
                        }

                        // if location was changed, copy to the new location
                        if (oldFilename != mergeTargetFilepath)
                        {
                            toolStripStatusLabel.Text = "Copying idpDB...";
                            File.Copy(oldFilename, mergeTargetFilepath, true);
                        }
                    }
                    else
                    {
                        // if not headless and MergedOutputFilepath is unset,
                        // then give the user a chance to override the merge target location
                        if (!Program.IsHeadless &&
                            defaultMergedOutputFilepath == null &&
                            !saveFileDialog(ref mergeTargetFilepath, "Choose where to create the merged idpDB"))
                            return;

                        while (true)
                        {
                            if (!canReadWriteInDirectory(Path.GetDirectoryName(mergeTargetFilepath)))
                            {
                                MessageBox.Show("IDPicker files cannot be merged to a read-only location, pick a writable path.");

                                if (Program.IsHeadless || !saveFileDialog(ref mergeTargetFilepath, "Pick a writable path in which to create the merged idpDB"))
                                    return;

                                continue;
                            }

                            // the SaveFileDialog already asked the user to confirm overwriting an existing file
                            if (File.Exists(mergeTargetFilepath))
                                File.Delete(mergeTargetFilepath);

                            break;
                        }
                    }
                }

                // set main window title
                BeginInvoke(new MethodInvoker(() => Text = mergeTargetFilepath));

                //set up delayed messages so non-fatal errors that occur at the end arent lost
                var delayedMessages = new List<string[]>();
                if (xml_filepaths.Count() > 0)
                {
                    importCancelled = false;

                    // loop until the import settings don't result in any fatal errors, or user cancels
                    while (!importCancelled)
                    {
                        Parser parser = new Parser();
                        Invoke(new MethodInvoker(() => parser.ImportSettings += importSettingsHandler));

                        var ilr = new IterationListenerRegistry();

                        var progressForm = new ProgressForm(xml_filepaths, ilr)
                        {
                            Text = "Import Progress",
                            StartPosition = FormStartPosition.CenterParent,
                        };

                        Invoke(new MethodInvoker(() => progressForm.Show(this)));

                        try
                        {
                            parser.Parse(xml_filepaths, ilr);

                            // read log for non-fatal errors
                            //string log = Logger.Reader.ReadToEnd().Trim();
                            //if (log.Length > 0)
                            //    Invoke(new MethodInvoker(() => UserDialog.Show(this, "Log Messages", new TextBox {Multiline = true, Text = log.Replace("\n", "\r\n"), ReadOnly = true, Size = new Size(800, 600),  ScrollBars = ScrollBars.Both}, MessageBoxButtons.OK)));

                            break; // no fatal errors, break the loop
                        }
                        catch (Exception ex)
                        {
                            if (ex.Message.Contains("no peptides found mapping to a decoy protein") ||
                                ex.Message.Contains("peptides did not map to the database") ||
                                ex.Message.Contains("duplicate protein id"))
                                Program.HandleUserError(ex);
                            else
                                throw;
                        }
                        finally
                        {
                            importCancelled |= progressForm.Cancelled;
                            Invoke(new MethodInvoker(() => progressForm.Close()));
                        }
                    }

                    if (importCancelled)
                        return;

                    idpDB_filepaths = idpDB_filepaths.Union(xml_filepaths.Select(o => Path.ChangeExtension(o.Replace(".pep.xml", ".pepXML"), ".idpDB")));
                }

                if (idpDB_filepaths.Count() > 1)
                {
                    var merger = new MergerWrapper(mergeTargetFilepath, idpDB_filepaths);
                    toolStripStatusLabel.Text = "Merging results...";
                    merger.MergingProgress += progressMonitor.UpdateProgress;
                    merger.Start();

                    idpDB_filepaths = new List<string>() {mergeTargetFilepath};
                }

                // HACK: this needs to be handled more gracefully
                if (!IsHandleCreated)
                    return;

                if (Properties.GUI.Settings.Default.WarnAboutNonFixedDrive && !Util.IsPathOnFixedDrive(mergeTargetFilepath))
                {
                    string oldFilename = mergeTargetFilepath;
                    bool copyLocal = true;
                    Invoke(new MethodInvoker(() =>
                                                 {
                                                     var form = new NonFixedDriveWarningForm();
                                                     if (form.ShowDialog(this) == DialogResult.Ignore)
                                                         copyLocal = false;
                                                 }));

                    if (copyLocal)
                    {
                        string newFilename = Path.GetFileName(mergeTargetFilepath);
                        if (!saveFileDialog(ref newFilename, "Pick a local path to copy the idpDB to"))
                            return;

                        toolStripStatusLabel.Text = "Copying idpDB...";
                        File.Copy(oldFilename, newFilename, true);
                        mergeTargetFilepath = newFilename;

                        // set main window title
                        BeginInvoke(new MethodInvoker(() => Text = mergeTargetFilepath));
                    }
                }

                if (!IsHandleCreated)
                    return;

                Util.PrecacheFile(mergeTargetFilepath, progressMonitor.UpdateProgress);

                if (!IsHandleCreated)
                    return;

                BeginInvoke(new MethodInvoker(() =>
                {
                    clearProgress();
                    toolStripStatusLabel.Text = "Upgrading schema and creating session factory...";
                    statusStrip.Refresh();
                }));

                var sessionFactory = DataModel.SessionFactoryFactory.CreateSessionFactory(mergeTargetFilepath, new SessionFactoryConfig { WriteSqlToConsoleOut = true });
                if (logForm != null) logForm.SetSessionFactory(sessionFactory);

                BeginInvoke(new MethodInvoker(() =>
                {
                    // reload qonverter settings because the ids may change after merging
                    toolStripStatusLabel.Text = "Loading qonverter settings...";
                    statusStrip.Refresh();
                    session = sessionFactory.OpenSession();
                    session.DefaultReadOnly = true;

                    session.CreateSQLQuery("PRAGMA temp_store=MEMORY; PRAGMA mmap_size=70368744177664; -- 2^46").ExecuteUpdate();

                    toolStripStatusLabel.Text = "Refreshing group structure...";
                    statusStrip.Refresh();
                    var usedGroups = GroupingControlForm.SetInitialStructure(rootNode, session, defaultApplySourceGroupHierarchy);
                    if (usedGroups != null && usedGroups.Any())
                    {
                        var allGroupsByName = session.Query<SpectrumSourceGroup>().ToDictionary(o => o.Name);
                        var usedGroupsByName = usedGroups.ToDictionary(o => o.Name);

                        // if usedGroupsByName does not contain a key from allGroupsByName, delete the group
                        foreach (var unusedGroup in allGroupsByName.Where(o => !usedGroupsByName.ContainsKey(o.Key)))
                            session.Delete(unusedGroup);
                    }
                    session.Flush();

                    // check for embedded gene metadata;
                    // if it isn't there, ask the user if they want to embed it;
                    // if not, disable gene-related features
                    if (!Program.IsHeadless && !Embedder.HasGeneMetadata(mergeTargetFilepath) && Properties.GUI.Settings.Default.WarnAboutNoGeneMetadata)
                    {
                        bool embedGeneMetadata = true;
                        Invoke(new MethodInvoker(() =>
                                                     {
                                                         var form = new EmbedGeneMetadataWarningForm();
                                                         if (form.ShowDialog(this) == DialogResult.Ignore)
                                                             embedGeneMetadata = false;
                                                     }));

                        if (embedGeneMetadata)
                        {
                            loadRefSeqGeneMetadata(); // will call OpenFiles() after embedding, so return immediately
                            return;
                        }
                    }
                    else
                    {
                        // disable gene-related features
                    }


                    qonverterSettingsByAnalysis = session.Query<QonverterSettings>().ToDictionary(o => session.Get<Analysis>(o.Id));

                    _layoutManager.SetSession(session);

                    //set or save default layout
                    dockPanel.Visible = true;
                    _layoutManager.CurrentLayout = _layoutManager.GetCurrentDefault();

                    //breadCrumbControl.BreadCrumbs.Clear();

                    // pick a default RoundToNearest based on number of distinct modifications
                    decimal roundToNearest = 1m;
                    var distinctModificationFormat = new DistinctMatchFormat();
                    var modMasses = session.CreateQuery("SELECT DISTINCT mod.MonoMassDelta FROM Modification mod").List<double>();
                    for (int i = 4; i > 0; --i)
                    {
                        distinctModificationFormat.ModificationMassRoundToNearest = (decimal) (1.0 / Math.Pow(10, i));
                        if (modMasses.Select(o => distinctModificationFormat.Round(o)).Distinct().Count() < 30)
                        {
                            roundToNearest = distinctModificationFormat.ModificationMassRoundToNearest.Value;
                            break;
                        }
                    }
                    modificationTableForm.RoundToNearest = roundToNearest;

                    basicFilter = DataFilter.LoadFilter(session);

                    // if user has overridden filters from the command-line, make sure to reapply the filter
                    if (!defaultDataFilter.PersistentDataFilter.Equals(defaultDataFilter.OriginalPersistentDataFilter))
                        basicFilter = null;

                    if (basicFilter == null)
                    {
                        basicFilter = new DataFilter(defaultDataFilter);
                        basicFilterControl.DataFilter = basicFilter;

                        viewFilter = basicFilter;

                        ApplyBasicFilter();
                    }
                    else
                    {
                        basicFilterControl.DataFilter = basicFilter;

                        viewFilter = basicFilter;

                        try
                        {
                            // check that the unfiltered tables exist
                            session.CreateSQLQuery("SELECT COUNT(*) FROM UnfilteredProtein").UniqueResult();

                            setData();
                        }
                        catch
                        {
                            ApplyBasicFilter();
                        }
                    }

                    if (TestUILayout)
                    {
                        int i = 0;
                        foreach(var form in dockPanel.Contents)
                        {
                            ++i;
                            form.DockingHandler.DockAreas = (form.DockingHandler.DockAreas | DockAreas.Float);
                            var rect = dockPanel.ClientRectangle;
                            rect.Offset(i * 15, i * 15);
                            rect.Size = new System.Drawing.Size(960, 600);
                            form.DockingHandler.Show(dockPanel, rect);
                        }
                    }

                    toolStripStatusLabel.Text = "Ready";
                    Activate();
                }));

                //show list of delayed non-fatal errors
                if (delayedMessages.Any())
                {
                    var sb = new StringBuilder();
                    foreach (var message in delayedMessages)
                        sb.AppendLine(string.Format("{0}:{1}{2}{1}", message[0], Environment.NewLine, message[1]));
                    var messageString = sb.ToString();

                    ShowExpandedMessageBox(messageString);
                }
            }
            catch (Exception ex)
            {
                Program.HandleException(ex);
            }
        }
示例#39
0
 public LayoutAreaAdminService(ISession session, IDocumentService documentService)
 {
     _session = session;
     _documentService = documentService;
 }
示例#40
0
        public void ApplyQonverterSettings(IDictionary<Analysis, QonverterSettings> qonverterSettings)
        {
            clearData();
            setControlsWhenDatabaseLocked(true);

            var workerThread = new BackgroundWorker()
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            workerThread.DoWork += (s, e) =>
            {
                var qonverter = new Qonverter();
                qonverter.QonversionProgress += progressMonitor.UpdateProgress;
                foreach (var item in qonverterSettings)
                    qonverter.SettingsByAnalysis[(int) item.Key.Id] = item.Value.ToQonverterSettings();

                //qonverter.LogQonversionDetails = true;
                qonverter.Reset(Text);
                qonverter.Qonvert(Text);
            };

            workerThread.RunWorkerCompleted += (s, e) =>
            {
                if (e.Result is Exception)
                {
                    Program.HandleException(e.Result as Exception);
                    setControlsWhenDatabaseLocked(false);
                    return;
                }

                lock (session)
                {
                    var sessionFactory = DataModel.SessionFactoryFactory.CreateSessionFactory(Text, new SessionFactoryConfig { WriteSqlToConsoleOut = true });
                    session = sessionFactory.OpenSession();
                    //session.CreateSQLQuery("PRAGMA temp_store=MEMORY").ExecuteUpdate();
                    _layoutManager.SetSession(session);

                    // delete old filters since they are not valid with different qonverter settings
                    session.CreateSQLQuery("DELETE FROM FilterHistory").ExecuteUpdate();
                    session.Clear();

                    if (basicFilter == null)
                        basicFilter = new DataFilter()
                        {
                            MaximumQValue = 0.02,
                            MinimumDistinctPeptides = 2,
                            MinimumSpectra = 2,
                            MinimumAdditionalPeptides = 1,
                            GeneLevelFiltering = false,
                            DistinctMatchFormat = new DistinctMatchFormat
                            {
                                IsChargeDistinct = true,
                                IsAnalysisDistinct = false,
                                AreModificationsDistinct = true,
                                ModificationMassRoundToNearest = 1.0m
                            }
                        };

                    basicFilterControl.DataFilter = basicFilter;

                    viewFilter = basicFilter;

                    session.Close();
                    sessionFactory.Close();
                }

                progressMonitor = new ProgressMonitor();
                progressMonitor.ProgressUpdate += progressMonitor_ProgressUpdate;
                basicFilterControl = new BasicFilterControl();
                basicFilterControl.BasicFilterChanged += basicFilterControl_BasicFilterChanged;
                basicFilterControl.ShowQonverterSettings += ShowQonverterSettings;
                dataFilterPopup = new Popup(basicFilterControl) { FocusOnOpen = true };
                dataFilterPopup.Closed += dataFilterPopup_Closed;
                new Thread(() => OpenFiles(new List<string> { Text }, null)).Start();
            };

            workerThread.RunWorkerAsync();
        }
示例#41
0
        void clearSession()
        {
            setControlsWhenDatabaseLocked(true);

            proteinTableForm.ClearSession();
            peptideTableForm.ClearSession();
            spectrumTableForm.ClearSession();
            modificationTableForm.ClearSession();
            analysisTableForm.ClearSession();
            reassignPSMsForm.ClearSession();
            filterHistoryForm.ClearSession();

            fragmentationStatisticsForm.ClearSession();
            peakStatisticsForm.ClearSession();
            distributionStatisticsForm.ClearSession();

            dockPanel.Contents.OfType<SequenceCoverageForm>().ForEach(o => { o.ClearSession(); o.Close(); });

            if (session != null)
            {
                var factory = session.SessionFactory;
                if (session.IsOpen)
                    session.Dispose();
                session = null;
                if (!factory.IsClosed)
                    factory.Dispose();
            }
        }
 public void ClearSession()
 {
     ClearData(true);
     if (session != null && session.IsOpen)
     {
         session.Close();
         session.Dispose();
         session = null;
     }
 }
        public void SetData (NHibernate.ISession session, DataFilter dataFilter)
        {
            this.session = session;
            viewFilter = dataFilter;
            this.dataFilter = new DataFilter(dataFilter);

            ClearData();

            Controls.OfType<Control>().ForEach(o => o.Enabled = true);
        }