Exemplo n.º 1
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(Domain.Socioboard.Domain.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
 }
        /// <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.Socioboard.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.Socioboard.Domain.DiscoverySearch> lst = session.CreateQuery("from DiscoverySearch where SearchKeyword = :keyword")
                                                                              .SetParameter("keyword", keyword)
                                                                              .List <Domain.Socioboard.Domain.DiscoverySearch>()
                                                                              .ToList <Domain.Socioboard.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
        }
Exemplo n.º 3
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);
                }
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
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"));
                }
            }
        }
Exemplo n.º 6
0
        public int  UpdateCreatDateByUserId(User user)
        {
            int i = 0;

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            i = session.CreateQuery("Update User set CreateDate =:createDate, AccountType =: accountType , PaymentStatus=:paymentStatus where Id = :id")
                                .SetParameter("createDate", user.CreateDate)
                                .SetParameter("accountType", user.AccountType)
                                .SetParameter("paymentStatus", user.PaymentStatus)
                                .SetParameter("id", user.Id)
                                .ExecuteUpdate();
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            return(i);
        }
Exemplo n.º 7
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);
 }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
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
 }
Exemplo n.º 10
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
 }
Exemplo n.º 11
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
        }
Exemplo n.º 12
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
 }
Exemplo n.º 13
0
        //public ArrayList getAllTasksOfUser(Guid UserId)
        //{
        //    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");
        //                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;
        //}


        public ArrayList getAllTasksOfUser(Guid UserId)
        {
            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 ");
                        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);
        }
Exemplo n.º 14
0
        public int UpdateReferenceUserByUserId(User user)
        {
            int i = 0;

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            i = session.CreateQuery("Update User set ReferenceStatus =:referenceStatus where Id = :id")
                                .SetParameter("referenceStatus", user.ReferenceStatus)
                                .SetParameter("id", user.Id)

                                .ExecuteUpdate();
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            return(i);
        }
Exemplo n.º 15
0
 public bool IsUserExist(string Emailid)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 NHibernate.IQuery query = session.CreateQuery("from  User u where u.EmailId = : email");
                 query.SetParameter("email", Emailid);
                 var result = query.UniqueResult();
                 if (result == null)
                 {
                     return(false);
                 }
                 else
                 {
                     return(true);
                 }
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return(true);
             }
         }
     }
 }
Exemplo n.º 16
0
        //public int ResetPassword(Guid id, string password)
        //{
        //    using (NHibernate.ISession session = SessionFactory.GetNewSession())
        //    {
        //        using (NHibernate.ITransaction transaction = session.BeginTransaction())
        //        {
        //            try
        //            {
        //                int i = session.CreateQuery("Update User set Password =:pass where Id = :userid")
        //                          .SetParameter("userid", id)
        //                          .SetParameter("pass", password)
        //                          .ExecuteUpdate();
        //                transaction.Commit();
        //                return i;

        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine(ex.StackTrace);
        //                return 0;
        //            }


        //        }
        //    }

        //}



        public List <User> GetAllUsersByCreateDate(string date)
        {
            List <User> alstUser = new List <User>();

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            alstUser = session.CreateQuery("from User where CreateDate < '2014-02-10' order by CreateDate desc").List <User>().ToList <User>();
                            //.SetParameter("date", date).List<User>().ToList<User>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.StackTrace);
            }

            return(alstUser);
        }
Exemplo n.º 17
0
        /********************/

        public List <User> testing()
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        List <User> s = session.CreateQuery("from User").List <User>().ToList <User>();
                        return(s);
                        //List<User> alstUser = new List<User>();
                        //foreach (User item in query.Enumerable())
                        //{
                        //    alstUser.Add(item);
                        //}

                        //return alstUser;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return(null);
                    }
                }
            }
        }
Exemplo n.º 18
0
        public User getUserInfoByEmail(string emailId)
        {
            List <User> lstUser = new List <User>();
            User        user    = new User();

            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        lstUser = session.CreateQuery("from  User u where u.EmailId = : email")
                                  .SetParameter("email", emailId).List <User>().ToList <User>();
                        user = lstUser[0];
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        user = null;
                    }
                }
            }

            return(user);
        }
Exemplo n.º 19
0
 public static void UpdateAccountType(User user)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 int i = session.CreateQuery("Update User set ProfileUrl =:profileurl, UserName =: username , EmailId=:emailid,AccountType=:accounttype,UserStatus=:userstatus,ExpiryDate=:expirydate,TimeZone=:timezone where Id = :twtuserid")
                         .SetParameter("twtuserid", user.Id)
                         .SetParameter("profileurl", user.ProfileUrl)
                         .SetParameter("username", user.UserName)
                         .SetParameter("emailid", user.EmailId)
                         .SetParameter("accounttype", user.AccountType)
                         .SetParameter("userstatus", user.UserStatus)
                         .SetParameter("expirydate", user.ExpiryDate)
                         .SetParameter("timezone", user.TimeZone)
                         .ExecuteUpdate();
                 transaction.Commit();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
             }
         }
     }
 }
Exemplo n.º 20
0
        public int UpdatePaymentStatusByUserId(User user)
        {
            int i = 0;

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            i = session.CreateQuery("Update User set PaymentStatus=:paymentStatus  where Id = :userid")
                                .SetParameter("userid", user.Id)
                                .SetParameter("paymentStatus", user.PaymentStatus)
                                .ExecuteUpdate();
                            transaction.Commit();
                        }
                        catch { }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.StackTrace);
            }

            return(i);
        }
Exemplo n.º 21
0
 public void SetUserByUserId(string emailid, string password, Guid id, string username, string accounttype, string couponcode)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 int i = session.CreateQuery("Update User set EmailId=:email, UserName =: username, Password =:pass, AccountType= :acctype,CouponCode=:couponCode where Id = :twtuserid")
                         .SetParameter("twtuserid", id)
                         .SetParameter("email", emailid)
                         .SetParameter("pass", password)
                         .SetParameter("acctype", accounttype)
                         .SetParameter("username", username)
                         .SetParameter("couponCode", couponcode)
                         .ExecuteUpdate();
                 transaction.Commit();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
             }
         }
     }
 }
Exemplo n.º 22
0
        public List <User> getAllUsers()
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        NHibernate.IQuery query    = session.CreateQuery("from User where Id !=null");
                        List <User>       alstUser = new List <User>();
                        foreach (User item in query.Enumerable())
                        {
                            alstUser.Add(item);
                        }

                        return(alstUser);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return(null);
                    }
                }
            }
        }
Exemplo n.º 23
0
        public int UpdateUserExpiryDateById(User user)
        {
            int i = 0;

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            i = session.CreateQuery("Update User set ExpiryDate=:expirydate, AccountType=:accounttype where Id = :id")
                                .SetParameter("id", user.Id)
                                .SetParameter("accounttype", user.AccountType)
                                .SetParameter("expirydate", user.ExpiryDate)
                                .ExecuteUpdate();
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            return(i);
        }
Exemplo n.º 24
0
        public int ChangePassword(string newpassword, string oldpassword, string Emailid)
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //NHibernate.IQuery query = session.CreateQuery("Update User set Password=:password where EmailId = :email and Password = :oldpass");
                        //query.SetParameter("email", Emailid);
                        //query.SetParameter("oldpass",oldpassword);
                        //query.SetParameter("password",newpassword);
                        //query.ExecuteUpdate();

                        int i = session.CreateQuery("Update User set Password=:password where EmailId = :email and Password = :oldpass")
                                .SetParameter("email", Emailid)
                                .SetParameter("oldpass", oldpassword)
                                .SetParameter("password", newpassword)
                                .ExecuteUpdate();
                        transaction.Commit();
                        return(i);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        return(0);
                    }
                }
            }
        }
Exemplo n.º 25
0
        public List <User> GetUserByCouponCode(User user)
        {
            List <User> alstUser = new List <User>();

            try
            {
                using (NHibernate.ISession session = SessionFactory.GetNewSession())
                {
                    using (NHibernate.ITransaction transaction = session.BeginTransaction())
                    {
                        try
                        {
                            alstUser = session.CreateQuery("from User where CouponCode=:couponCode")
                                       .SetParameter("couponCode", user.CouponCode)
                                       .List <User>().ToList <User>();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.StackTrace);
            }

            return(alstUser);
        }
Exemplo n.º 26
0
        public IList FindByMainId(string id)
        {
            NHibernate.ISession session = HibernateTemplate.SessionFactory.OpenSession();
            NHibernate.IQuery   query   = session.CreateQuery("from MasterInfo m where m.InfoCode=:infoCode");
            query.SetParameter("infoCode", id);

            return(query.List());
        }
Exemplo n.º 27
0
        public object Execute(NHibernate.ISession session)
        {
            IQuery q = session.CreateQuery(string.Format("select count(*) {0}", this._hql));

            if (this._parameters != null)
            {
                for (int i = 0; i < this._parameters.Length; i++)
                {
                    q.SetParameter(i, this._parameters[i]);
                }
            }
            return(q.UniqueResult());
        }
Exemplo n.º 28
0
        public object Execute(NHibernate.ISession session)
        {
            IQuery query = session.CreateQuery(_hql);

            if (_paras != null)
            {
                for (int i = 0; i < _paras.Length; i++)
                {
                    query.SetParameter(i, _paras[i]);
                }
            }
            return(query.List());
        }
Exemplo n.º 29
0
 /// <getTaskById>
 /// Get Task By Id
 /// </summary>
 /// <param name="Taskid">Task id.(string)</param>
 /// <param name="userId">User id.(Guid)</param>
 /// <returns>Return object of Tasks Class with  all Tasks info.(List<Tasks>)</returns>
 public Domain.Socioboard.Domain.Tasks getTaskById(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())
         {
             //Proceed action, to get Account details by Fb user id and user id.
             NHibernate.IQuery query = session.CreateQuery("from FacebookAccount where FbUserId = :Fbuserid and UserId=:userId");
             query.SetParameter("Fbuserid", Taskid);
             query.SetParameter("userId", userId);
             Domain.Socioboard.Domain.Tasks result = (Domain.Socioboard.Domain.Tasks)query.UniqueResult();
             return(result);
         } //End Transaction
     }     //End Session
 }
Exemplo n.º 30
0
 public int DeleteTaskOfGroup(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 delete task of user by groupId.
             NHibernate.IQuery query = session.CreateQuery("delete from Tasks where GroupId = :GroupId")
                                       .SetParameter("GroupId", groupId);
             int isUpdated = query.ExecuteUpdate();
             transaction.Commit();
             return(isUpdated);
         }
     }
 }
Exemplo n.º 31
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);
            }
        }