private async void button1_Click(object sender, EventArgs e) //Login button { if (checkBox3.Checked) //Saves username & password to local variables { Settings.Default.remember = true; Settings.Default.username = textBox3.Text; Settings.Default.password = textBox2.Text; Settings.Default.Save(); Settings.Default.Reload(); } sess = new DBSession(textBox3.Text, textBox2.Text); //Login with credentials await sess.LoginAsync(); if (sess.Status == DBStatus.LoggedIn) { sess.ReceiveShouts = true; sess.OnShoutReceived += getShouts; MessageBox.Show($"Logged in as: " + textBox3.Text, "Succes"); pictureBox1.Visible = false; groupBox1.Visible = true; groupBox2.Visible = false; groupBox4.Visible = true; groupBox5.Visible = true; this.Text = "Darkboy - " + textBox3.Text; label7.Visible = false; label8.Visible = false; timer1.Stop(); } else MessageBox.Show("Something went wrong, try again!", "Oops!"); //Error when logging in }
/// <summary> /// 读取Oracle /// </summary> /// <returns></returns> private static List <TableInfo> ReaderOracle() { #region sql string sql = @" select x.*,(case when y.COLUMN_NAME is null then 0 else 1 end)IsPrimaryKey from ( select A.COLUMN_NAME,a.data_type,a.data_length,a.data_precision,a.data_scale,B.COMMENTS from user_tab_cols a left join user_col_comments b on a.COLUMN_NAME=B.COLUMN_NAME where a.TABLE_NAME='{0}' and b.TABLE_NAME='{0}' )x left join ( select COLUMN_NAME from user_constraints a left join user_cons_columns b on A.CONSTRAINT_NAME=B.CONSTRAINT_NAME where a.CONSTRAINT_TYPE = 'P' and a.table_name='{0}' )y on x.COLUMN_NAME=y.COLUMN_NAME"; #endregion using (DBSession db = DBSession.TryGet()) { //获取所有table dynamic dytables = db.GetDynamicList("select TABLE_NAME,COMMENTS from user_tab_comments"); List <TableInfo> tables = new List <TableInfo>(); foreach (dynamic item in dytables) { TableInfo table = new TableInfo(); table.Name = item.TABLE_NAME; table.Desc = TBFieldHelper.FormatDesc(item.COMMENTS); table.Fields = new List <TBField>(); //获取字段 dynamic fields = db.GetDynamicList(string.Format(sql, table.Name.ToUpper())); foreach (dynamic dyF in fields) { TBField field = new TBField(); field.Name = dyF.COLUMN_NAME; field.Desc = TBFieldHelper.FormatDesc(dyF.COMMENTS); field.IsPrimaryKey = dyF.ISPRIMARYKEY == 1 ? true : false; string typestr = dyF.DATA_TYPE; //获取数据类型 field.FieldType = TBFieldHelper.GetFieldType(field.Name, typestr, DataBaseType.Oracle, () => { return(Getdynamic <int>(dyF.DATA_PRECISION)); }, () => { return(Getdynamic <int>(dyF.DATA_SCALE)); }); table.Fields.Add(field); } tables.Add(table); } return(tables); } }
//设置权限角色 public bool SetActionRoleInfo(int actionId, List <int> roleIdlist) { //获取要设置角色的权限信息 ActionInfo actionInfo = DBSession.ActionInfoDal.GetEntities(a => a.ID == actionId).FirstOrDefault(); if (actionInfo != null) { actionInfo.RoleInfo.Clear();//清除该权限的所有角色 foreach (int roleId in roleIdlist) { RoleInfo roleInfo = DBSession.RoleInfoDal.GetEntities(r => r.ID == roleId).FirstOrDefault(); actionInfo.RoleInfo.Add(roleInfo); } return(DBSession.SaveChanges() > 0); } return(false); }
/// <summary> /// 根据数据Id获取缓存对象,如果在缓存中没有获取到,则自动从数据库中加载 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> public static T GetCacheObject<T>(object id) { T t = Instanse.GetCache<T>(id); DBTable table = MapHelper.GetDBTable(typeof(T)); if (table == null) throw new Exception("非映射类,不能获取缓存!"); if (table.CacheType != CacheType.Object) throw new Exception("该映射类,没有设置缓存!"); //如果为nul,则从数据库获取 if (t == null) { using (DBSession session = DBSession.TryGet()) { t = session.GetById<T>(id); } } return t; }
/// <summary> /// 得到编码 /// </summary> /// <param name="depCode">父级或同级编码</param> /// <param name="strLevel">父级(same),下级(son)</param> /// <returns></returns> public string GetCode(string depCode, string strLevel) { string strNewCode = ""; string strWhere = ""; if (strLevel == "same") //新增同级 { if (depCode.Length <= 3) //根目录或为空 { strWhere = " len(Department_Code)=3"; } else { string strPcode = depCode.Substring(0, depCode.Length - 3); strWhere = " Department_ParentCode='" + strPcode + "'"; } } else { strWhere = " Department_ParentCode='" + depCode + "'"; } List <Sys_Department> listDep = DBSession.ExecuteQuery <Sys_Department>("Select * from " + typeof(Sys_Department).Name + " where " + strWhere);//FindWhere(strWhere); int count = listDep.Count + 1; while (count <= 999) { if (count < 10) { strNewCode = depCode + "00" + count; } else if (count < 99) { strNewCode = depCode + "0" + count; } else { strNewCode = depCode + count.ToString(); } count++; if (!IsExitsCode(strNewCode)) { break; } } return(strNewCode); }
public bool UpdateTeaAddCount(Teacher tea) { DBSession db = new DBSession(); if (tea.Tea_ChoseCount == tea.Tea_StuCount) { return(false); } tea.Tea_ChoseCount++; if (teaDal.UpdateEntity(tea) != null) { db.SaveChanges(); return(true); } ; return(false); }
//如果现在有需求 原来是IUserInfoDal dal=new EFUserInfoDal()现在要求把EFUserInfoDal换成NHUserInfoDal //因为有可能很多地方都用到了EFUserInfoDal所以这样改起来将会很麻烦 //自然想到简单工厂设计 public UserInfo Add(UserInfo userinfo) { //如果使用new关键字实际 BaseService<UserInfo> s = new UserInfoService();那么这样调用的就是baseservice的add方法这里默认是使用new // UserInfo u=userdal.Add(userinfo); // BaseDal<UserInfo> based = new BaseDal<UserInfo>(); // UserInfo u=based.Add(userinfo); DBSession db = new DBSession(); UserInfo u2 = db.UserInfoDal.Add(userinfo); db.SaveChanges(); //数据提交的权利从数据库访问层提到了业务逻辑层 //如果没有提到业务逻辑层 那么每次在dal层调用一次crud方法都会执行一次commit方法 //如歌一个业务有多个crud方法 ,那么每次调用提交 调用提交 这样肯定会降低效率, //所以把提交的方法提到业务逻辑层 可以实现多次操作一次 提交从而增加效率. return(u2); }
/// <summary> /// 设置用户角色 /// </summary> /// <param name="userID"></param> /// <param name="RoleIdList"></param> /// <returns></returns> public bool SetUserRoleInfo(int userID, List <int> RoleIdList) { UserInfo userInfo = DBSession.UserInfoDal.GetEntities(u => u.ID == userID).FirstOrDefault(); if (userInfo != null) { userInfo.RoleInfo.Clear();//清除用户的所有角色 foreach (int RoleId in RoleIdList) { RoleInfo RoleInfo = DBSession.RoleInfoDal.GetEntities(r => r.ID == RoleId).FirstOrDefault(); userInfo.RoleInfo.Add(RoleInfo);//循环为用户添加角色 } return(DBSession.SaveChanges() > 0); } else { return(false); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() // TODO : Newtonsoft.Json not working in .netcoreapp3.1 .. specifically ReferenceLoopHandling //.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); //.AddNewtonsoftJson(options => { }); ; // NHibernate session registration // Note that we are registring SessionFactory as a Singleton // but session is registered per request var nHibernateConfiguration = new DBSession().GetConfiguration(); var nHibernateSessionFactory = new DBSession().GetSessionFactory(nHibernateConfiguration); services.AddSingleton(nHibernateConfiguration); services.AddSingleton(nHibernateSessionFactory); services.AddScoped(factory => nHibernateSessionFactory.OpenSession()); }
public ActionResult AddCustomer(Customer_reltab newobj) { using (var db = new DBSession("default")) { ISession session = db.Session; try { session.Save(newobj); } catch (Exception eX) { db.Rollback = true; return ErrorContent(eX.Message); } return Json(newobj); } }
public ActionResult GetTreeData() { IList<ACMenu> menus = new List<ACMenu>(); using (var db = new DBSession("default")) { var session = db.Session; try { menus = session.CreateQuery("from ACMenu").List<ACMenu>(); } catch (Exception eX) { return ErrorContent(eX.Message); } } return Json(menus); }
public bool PassThe(int theid) { DBSession db = new DBSession(); IQueryable <Theme> iq = themedal.GetEntities(u => u.Theme_Id == theid); Theme t = new Theme(); foreach (var item in iq) { t = item; } t.Examine = 1; t.ExamineTime = DateTime.Now; if (themedal.UpdateEntity(t) != null) { db.SaveChanges(); return(true); } ; return(false); }
public virtual void QueryValues(string columnID, string startTime, string endTime) { DBSession session = LTCingFWSet.GetThreadContext().DBSession; ValueInfoOrmModel model = null; if (session.ProviderName == DBSession.MySql_ProviderName) { model = new ValueInfoOrmModel(); } if (model != null) { model.COLUMN_ID = columnID; OrmBaseModel m = (OrmBaseModel)model; m.Where = " UPDATE_TIME > '" + startTime + "' AND UPDATE_TIME < '" + endTime + "' "; udDao.Select(session, m); } }
/// <summary> /// 为特殊用户分配权限 /// </summary> /// <param name="actionId">权限ID</param> /// <param name="userId">用户ID</param> /// <param name="HasPermission">是否允许</param> /// <returns></returns> public bool SetUserActionInfo(int actionId, int userId, bool HasPermission) { short Normal = (short)DelFlagEnum.Normal; //为特殊用户分配权限 R_UserInfo_ActionInfo r_UserInfo_ActionInfo = DBSession.R_UserInfo_ActionInfoDal.GetEntities(r => r.ActionInfoID == actionId && r.UserInfoID == userId && r.DelFlag == Normal).FirstOrDefault(); if (r_UserInfo_ActionInfo != null) { r_UserInfo_ActionInfo.HasPermission = HasPermission;//修改是否允许标识 } else { R_UserInfo_ActionInfo R_UserInfo_Act = new R_UserInfo_ActionInfo(); R_UserInfo_Act.UserInfoID = userId; R_UserInfo_Act.ActionInfoID = actionId; R_UserInfo_Act.DelFlag = Normal; R_UserInfo_Act.HasPermission = HasPermission; DBSession.R_UserInfo_ActionInfoDal.Add(R_UserInfo_Act); } return(DBSession.SaveChanges() > 0); }
/// <summary> /// 获取缓存的List集合 /// </summary> /// <typeparam name="T">获取的数据类型</typeparam> /// <returns>该类型的所有缓存数据</returns> internal List <T> TryGetList <T>() { Type type = typeof(T); DBTable table = MapHelper.GetDBTable(type); if (table.CacheType != CacheType.List) { throw new Exception("该类型不是list缓存模式"); } List <T> list = GetCache <List <T> >(type.FullName); if (list == null)//加载该集合 { using (DBSession session = DBSession.TryGet()) { list = session.GetList <T>("", ""); } SetCache(typeof(List <>).MakeGenericType(type), type.FullName, list, table.CacheSeconds); } return(list); }
public Article AddArticle(Article model, string categories) { model.CreateTime = model.EditeTime = DateTime.Now; using (TransactionScope ts = new TransactionScope()) { model = dal.AddEntity(model); var cats = categories.Split(','); if (cats != null && cats.Count() > 0) { cats.ToList().ForEach(p => { art_catDal.AddEntity(new Article_Category { CategoryId = p, ArticleId = model.Id }); }); } DBSession.SaveChanges(); ts.Complete(); return(model); } }
private void AddRoleRight(string roleId, string moduleId) { SysRight right = m_Rep.GetList(r => r.RoleId == roleId && r.ModuleId == moduleId).FirstOrDefault(); if (right == null) { right = new SysRight() { RoleId = roleId, ModuleId = moduleId, Id = ResultHelper.NewId, Rightflag = true }; m_Rep.Create(right); DBSession.SaveChanges(); SysModule module = DBSession.SysModule.GetById(moduleId); if (module.ParentId != "000") { AddRoleRight(roleId, module.ParentId); } } }
/// <summary> /// 查询条数 /// 使用model作为查询条件; /// 查询该条件下的所有条目 /// </summary> /// <param name="query_model"></param> /// <returns></returns> public virtual int GetItemCount(OrmBaseModel query_model) { DBSession session = LTCingFWSet.GetThreadContext().DBSession; return(dao.GetItemCount(session, query_model)); }
public ActionResult All(int startRow, int rows, string orderby, string order, string filters) { using (var db = new DBSession("default")) { List<QueryFilter> qFilters = null == filters ? new List<QueryFilter>() : DecodeUrlJson<List<QueryFilter>>(filters); ISession session = db.Session; try { PagingRecord retRecord = new PagingRecord(); retRecord.FilterInfo.Order = order; retRecord.FilterInfo.Orderby = orderby; retRecord.PageInfo.Rows = rows; //DetachedCriteria c = DetachedCriteria.For<Customer_reltab>() // .SetProjection(Projections.Property("custNo")); ICriteria cmain = session.CreateCriteria<Customer_reltab>(); IClassMetadata metadata = db.Session.SessionFactory.GetClassMetadata(typeof(Customer_reltab)); // .Add(Subqueries.PropertyNotIn("Vie_ieid", c)); BuildCriterionFromJsonQuery(cmain, qFilters, metadata, (f) => { return f.Substring(0, 1).ToUpper() + f.Substring(1, f.Length - 1); }); switch (order.ToUpper()) { case "ASC": cmain.AddOrder(Order.Asc(orderby.ToFirstUpper())); break; case "DESC": cmain.AddOrder(Order.Desc(orderby.ToFirstUpper())); break; default: cmain.AddOrder(Order.Asc(orderby.ToFirstUpper())); break; } ICriteria countc = cmain.Clone() as ICriteria; countc.SetProjection(Projections.CountDistinct("CustNo")); retRecord.PageInfo.TotalRows = countc.UniqueResult<int>(); if (0 != rows) { cmain.SetFirstResult(startRow - 1).SetMaxResults(rows); } IList<Customer_reltab> retValues = cmain.List<Customer_reltab>(); retRecord.Records = retValues; return DefaultJson(retRecord); } catch (Exception eX) { return ErrorContent(eX.Message); } } }
public T Add(T entity) { CurrentDal.Create(entity); DBSession.SaveChanges(); return(entity); }
public ActionResult Delete(List<string> delobjs) { using (var db = new DBSession("default")) { ISession session = db.Session; try { foreach (string key in delobjs) { session.Delete(session.Get<Customer_reltab>(int.Parse(key))); } return Content("删除成功"); } catch (Exception eX) { db.Rollback = true; return ErrorContent(eX.Message); } } }
/// <summary> /// 删除实体对象数据.不要随意调用。 /// </summary> /// <param name="entity">实体对象</param> /// <returns>返回bool类型</returns> public bool Delete(T entity) { Dal.Delete(entity); return(DBSession.SaveChanges()); }
/// <summary> /// 插入实体对象列表到数据库 /// </summary> /// <param name="entityList">实体对象列表</param> /// <returns>返回bool类型</returns> public bool Add(List <T> entityList) { Dal.Add(entityList); DBSession.SaveChanges(); return(true); }
static void Main(string[] args) { DBSession session = new DBSession("database.db"); Console.ReadLine(); }
public ActionResult UpdateCustomer(Customer_reltab updobj) { using (var db = new DBSession("default")) { ISession session = db.Session; Customer_reltab old = session.Get<Customer_reltab>(updobj.CustNo); if (null != old) { try { session.Evict(old); session.Update(updobj); } catch (Exception eX) { db.Rollback = true; return ErrorContent(eX.Message); } return Content("更新成功"); } else { return ErrorContent("要更新的客户信息不存在"); } } }
public bool Add(Sys_Role model, List <Sys_RolePurview> list) { this.DBSession.Sys_RoleDal.Add(model); this.DBSession.Sys_RolePurviewDal.Add(list); return(DBSession.SaveChanges()); }
/// <summary> /// 特殊情况Sql语句查询数据 /// </summary> /// <param name="SqlWhere">查询条件</param> /// <returns></returns> public List <Sys_Department> FindWhere(string SqlWhere) { return(DBSession.ExecuteQuery <Sys_Department>("Select * from " + typeof(Sys_Department).Name + " where " + SqlWhere)); }
public bool Delete(T entity) { CurrentDal.Delete(entity); return(DBSession.SaveChanges() > 0); }
/// <summary> /// 插入实体对象到数据库 /// </summary> /// <param name="entity">实体对象</param> /// <returns>返回bool类型</returns> public bool Add(T entity) { Dal.Add(entity); return(DBSession.SaveChanges()); }
public IActionResult Login([FromBody] DTOs.LoginRequestDTO dto) { using (var transaction = DBSession.BeginTransaction()) { try { var person = DBSession.QueryOver <Person>().Where(x => x.Username == dto.Username).SingleOrDefault(); if (person == null) { return(Unauthorized()); } if (!PasswordHash.ValidatePassword(dto.Password, person.PasswordHash)) { if (person.EmailAddresses.Any()) { var model = new Email.Models.FailedAccountLoginEmailModel { FriendlyName = person.ToString() }; //Ok, so we have an email we can use to contact the person! Email.EmailInterface.CCEmailMessage .CreateDefault() .To(person.EmailAddresses.Select(x => new System.Net.Mail.MailAddress(x.Address, person.ToString()))) .Subject("Security Alert : Failed Login") .HTMLAlternateViewUsingTemplateFromEmbedded("CommandCentral.Email.Templates.FailedAccountLogin_HTML.html", model) .SendWithRetryAndFailure(TimeSpan.FromSeconds(1)); //Now we also need to add the event to client's account history. person.AccountHistory.Add(new AccountHistoryEvent { AccountHistoryEventType = ReferenceListHelper <AccountHistoryType> .Find("Failed Login"), EventTime = this.CallTime }); DBSession.Update(person); } transaction.Commit(); return(Unauthorized()); } //The client is who they claim to be so let's make them an authentication session. AuthenticationSession ses = new AuthenticationSession { Id = Guid.NewGuid(), IsActive = true, LastUsedTime = CallTime, LoginTime = CallTime, Person = person }; //Now insert it DBSession.Save(ses); //Also put the account history on the client. person.AccountHistory.Add(new AccountHistoryEvent { AccountHistoryEventType = ReferenceListHelper <AccountHistoryType> .Find("Login"), EventTime = CallTime }); Response.Headers.Add("sessionId", new Microsoft.Extensions.Primitives.StringValues(ses.Id.ToString())); transaction.Commit(); return(Ok()); } catch (Exception e) { LogException(e); transaction.Rollback(); return(StatusCode(500)); } } }
/// <summary> /// 插入实体对象到数据库 /// </summary> /// <param name="entity">实体对象</param> /// <returns>返回当前更新过的实体对象</returns> public T AddEntity(T entity) { Dal.AddEntity(entity); DBSession.SaveChanges(); return(entity); }
public virtual T Add(T item) { DAL.Add(item); DBSession.SaveChanges(); return(item); }
/// <summary> /// 更新实体对象 /// </summary> /// <param name="entity">实体对象</param> /// <returns>返回bool类型</returns> public bool Update(T entity) { Dal.Update(entity); return(DBSession.SaveChanges()); }
public virtual bool Delete(T item) { DAL.Delete(item); DBSession.SaveChanges(); return(true); }
/// <summary> /// 删除符合表达式条件数据 /// </summary> /// <param name="where">条件表达式</param> /// <returns>返回bool类型</returns> public bool Delete(Expression <Func <T, bool> > where) { Dal.Delete(where); return(DBSession.SaveChanges()); }
public virtual bool Edit(T item) { DAL.Edit(item); DBSession.SaveChanges(); return(true); }
public ActionResult Single(int id) { using (var db = new DBSession("default")) { ISession session = db.Session; try { Customer_reltab retValue = session.Get<Customer_reltab>(id); return DefaultJson(retValue); } catch (Exception eX) { return ErrorContent(eX.Message); } } }
/// <summary> /// Создать копию /// </summary> /// <returns></returns> public DBSession Clone() { var rslt = new DBSession(this.ConnectionString); rslt.BeforeDBConnectEvent += this.BeforeDBConnectEvent; rslt.AfterDBConnectEvent += this.AfterDBConnectEvent; return rslt; }