[ValidateInput(false)] //因为要传递带html标签的art.Text,所以此处不能验证输入 public ActionResult Edit(Base_Article art, int caId = 0) { art.EditorId = CommOp.ToInt(CurrentUserId); art.State = ArticleState.Published; Base_CatalogArticle ca; if (caId == 0) { ca = new Base_CatalogArticle { CatalogId = CatalogId }; } else { ca = _article.GetById(caId); _innerCatalogId = ca.CatalogId; } ca.Article = art; if (art.Id > 0 && caId == 0) { var oldCaId = _article.GetByArticleId(art.Id, CatalogId).Id; ca.Id = oldCaId; } if (BeforeSaving(ca)) { _article.Save(ca); } return(AfterSaved(ca)); }
/// <summary> /// 数据分页查询 异步版本 /// </summary> /// <param name="pager"></param> /// <param name="sp"></param> /// <returns></returns> public async Task <IDataReader> ExecPageReaderAsync(IPager p, params IDataParameter[] sp) { if (p is DBPagerInfo) { DBPagerInfo pager = p as DBPagerInfo; var tp = GetSortFieldFromOrderBy(pager.OrderBy, pager.KeyId); string orderby = tp[0]; string sql = "SELECT COUNT(1) FROM (" + pager.Query + ")c"; pager.RecordCount = CommOp.ToInt(await Helper.ExecGetObjectAsync(sql, sp)); sql = $@"WITH PAGED AS ( SELECT ROW_NUMBER() OVER(ORDER BY {pager.OrderBy}) AS rowNum, * FROM ({pager.Query})a) SELECT TT.* FROM PAGED P INNER JOIN ({pager.Query})TT ON P.{pager.KeyId} = TT.{pager.KeyId} WHERE ROWNUM BETWEEN {pager.StartIndex + 1} AND {pager.StartIndex + pager.PageSize} ORDER BY {pager.OrderBy}"; //pager.OrderBy, pager.Query, pager.KeyId, pager.StartIndex + 1, pager.StartIndex + pager.PageSize); return(await Helper.ExecReaderAsync(sql, sp)); } else if (p is MasterDetailPagerInfo) { return(await ExecMasterDetailPageReaderAsync((MasterDetailPagerInfo)p, sp)); } else { throw new ArgumentException($"请传入{nameof(DBPagerInfo)}或{nameof(MasterDetailPagerInfo)}"); } }
/// <summary> /// 根据唯一ID获取对象,返回实体,如果有多个则报错 /// </summary> /// <param name="id">ID</param> /// <returns>返回实体类</returns> public async Task <T> GetModelByIdAsync <T, TId>(TId id) where T : IId <TId>, new() { if (CommOp.IsDefault(id)) { return(default(T)); } var pid = CreateParameter("ID", id); Type type = typeof(T); string sql = $"SELECT COUNT(1) FROM {AddFix(type.Name)} where ID=@ID"; int cnt = CommOp.ToInt(await this.ExecGetObjectAsync(sql, pid)); if (cnt == 0) { return(default(T)); } if (cnt > 1) { throw new Exception("根据唯一的ID查到不止一条记录"); } sql = $"SELECT * FROM {AddFix(type.Name)} where ID=@ID"; List <IDataParameter> list = new List <IDataParameter>(); DataTable dt = await this.ExecDataTableAsync(sql, pid); if (dt.Rows.Count == 1) { return(RowToModel <T>(dt.Rows[0])); } return(default(T)); }
/// <summary> /// 如果有Sql语句,直接根据Sql生成分页 /// </summary> /// <param name="gkey"></param> /// <param name="parameters"></param> /// <returns></returns> private IPager BuildSqlPager(DataGateKey gkey, IDictionary <string, object> parameters) { var mainModel = GetMainTable(gkey); string filter = FormatFilter(gkey.Filter, mainModel); if (!filter.IsEmpty()) { filter = " where " + filter; } string sql = $"{gkey.Sql}{filter}"; int pageSize = CommOp.ToInt(GetValueRemoveKey(parameters, "pageSize")); if (pageSize <= 0) { pageSize = Consts.DefaultPageSize; } DBPagerInfo pager = new DBPagerInfo { Query = sql, KeyId = mainModel.PrimaryKey.FixDbName, PageIndex = Math.Max(1, CommOp.ToInt(GetValueRemoveKey(parameters, "pageIndex"))) - 1, PageSize = pageSize, OrderBy = gkey.OrderBy, }; return(pager); }
/// <summary> /// 获取所有用户的分页json数据 /// </summary> /// <param name="page">查询分页信息,包括当前页、页大小、关键词等</param> /// <returns></returns> public JsonResult GetAll(PageModel page) { //mini-ui的分页是从0开始的 page.PageIndex++; //因userMgr.GetAll()不是IQueryable对象,所以不能直接用在分页API中 //需要一个转换 var users = mUserMgr.GetAll().AsQueryable(); if (!page.Key.IsEmpty()) { page.Key = page.Key.ToLower(); users = users.Where(u => u.Name.ToLower().Contains(page.Key) || u.Id.Equals(page.Key) || (u.Email != null && u.Email.Contains(page.Key)) || (u.PhoneNumber != null && u.PhoneNumber.Contains(page.Key)) || u.RoleNames.ToLower().Contains(page.Key)); } var pager = new Pager <AppUser>(users.OrderByDescending(u => CommOp.ToInt(u.Id)), page.PageIndex, page.PageSize); //多重排序: //ViewBag.Pager = Pager.GetPagedList(ref users, us => // us.OrderByDescending(u => u.IsOnline) // .ThenByDescending(u => u.Id), page); // var vre = this.ViewEngineCollection[1].FindView(this.ControllerContext., "Index_Spc", "_AdminPartial", false); //MVC3不支持 return(Json(new { data = pager, total = pager.RecordCount }, JsonRequestBehavior.AllowGet)); }
//保存扩展属性 private void SaveExts(Base_Catalog cat, NameValueCollection form) { cat.Exts.Clear(); var ids = form["ExtId"].Split(','); var names = form["ExtName"].Split(','); var defaultValues = form["DefaultValue"].Split(','); var dataTypes = form["DataType"].Split(','); var maxLengths = form["MaxLength"].Split(','); //var allownulls = form["AllowNull"].Split(','); var states = form["ExtState"].Split(','); var dataSourceTypes = form["DataSourceType"].Split(','); var dataSources = form["DataSource"].Split(','); for (int i = 1; i < names.Length; i++) { if (!string.IsNullOrEmpty(names[i])) { Base_CatalogExt ext = new Base_CatalogExt { Id = CommOp.ToInt(ids[i]), CatalogId = cat.Id, Name = names[i], DefaultValue = defaultValues[i], DataType = CommOp.ToEnum <ExtDataType>(dataTypes[i]), State = states[i] == "" ? ArticleState.Published : CommOp.ToInt(states[i]), Ord = i, //AllowNull = CommOp.ToBool(allownulls[i] == "on" ? true : false), MaxLength = CommOp.ToInt(maxLengths[i]), DataSourceType = CommOp.ToEnum <ExtDataSourceType>(dataSourceTypes[i]), DataSource = dataSources[i] }; cat.Exts.Add(ext); } } }
// --查询条件也有子表 //select u.*, r.*, ur.* from app_user u left join app_user_role ur on u.id = ur.user_id //left join app_role r on r.id = ur.role_id where u.id in //(select id from //(select id, failed_try, rownum r from ( //select distinct(u.id), u.failed_try from app_user u left join app_user_role ur on u.id = ur.user_id //left join app_role r on r.id = ur.role_id // where u.name like '测试用户%' and r.name like '%管理员%' // order by u.failed_try)g //)h where r between 1 and 3) // order by u.failed_try; async Task <IDataReader> ExecMasterDetailPageReaderAsync(MasterDetailPagerInfo pager, params IDataParameter[] sp) { var tp = GetSortFieldFromOrderBy(pager.OrderBy, pager.KeyId); string sortFields = tp[1]; string innerSorts = tp[2]; string orderby = tp[0]; string innerId = pager.KeyId.Split('.').Last(); string filter = pager.Filter.IsEmpty() ? "" : " where " + pager.Filter; string sql = $"select COUNT(distinct({pager.KeyId})) from " + $"{pager.TablesAndJoins}{filter}"; if (!innerSorts.IsEmpty()) { innerSorts = "," + innerSorts; } if (!sortFields.IsEmpty()) { sortFields = "," + sortFields; } pager.RecordCount = CommOp.ToInt(await Helper.ExecGetObjectAsync(sql, sp)); sql = $"select {pager.Fields} from {pager.TablesAndJoins} where{Environment.NewLine}" + $" {pager.KeyId} in{Environment.NewLine}" + $"(select {innerId} from" + $"(select {innerId}{innerSorts},rownum r from({Environment.NewLine}" + $"select distinct({pager.KeyId}){sortFields} from {pager.TablesAndJoins}{filter}{Environment.NewLine}" + $"order by {orderby})g__{Environment.NewLine}" + $")h__ where r between {pager.StartIndex + 1} and {pager.StartIndex + pager.PageSize}){Environment.NewLine}" + $"order by {orderby}"; return(await Helper.ExecReaderAsync(sql, sp)); }
//单表的分页 private IPager BuildPager(DataGateKey gkey, IDictionary <string, object> parameters) { var tableMeta = gkey.MainTable; string filter = FormatFilter(gkey.Filter, tableMeta); if (!filter.IsEmpty()) { filter = " where " + filter; } string sql = gkey.Sql; if (sql.IsEmpty()) { sql = $"select {gkey.QueryFieldsTerm} from {tableMeta.FixDbName}{filter}"; } int pageSize = CommOp.ToInt(GetValueRemoveKey(parameters, "pageSize")); if (pageSize <= 0) { pageSize = Consts.DefaultPageSize; } DBPagerInfo pager = new DBPagerInfo { Query = sql, KeyId = $"{gkey.TableJoins[0].Alias ?? tableMeta.FixDbName}.{tableMeta.PrimaryKey.FixDbName}", PageIndex = Math.Max(1, CommOp.ToInt(GetValueRemoveKey(parameters, "pageIndex"))) - 1, PageSize = pageSize, OrderBy = gkey.OrderBy, }; return(pager); }
[ValidateInput(false)] //因为要传递带html标签的art.Text,所以此处不能验证输入 public ActionResult Edit(Base_Article art, int caId = 0) { art.EditorId = CommOp.ToInt(CurrentUserId); art.State = ArticleState.Published; Base_CatalogArticle ca; if (caId == 0) { ca = new Base_CatalogArticle { CatalogId = CatalogId }; } else { ca = _resourceFileService.Article.GetById(caId); _innerCatalogId = ca.CatalogId; } ca.Article = art; if (art.Id > 0 && caId == 0) { var oldCaId = _resourceFileService.Article.GetByArticleId(art.Id, CatalogId).Id; ca.Id = oldCaId; } if (true) { _resourceFileService.Article.Save(ca); } return(JsonTips("success", "", JStr.SuccessSaved0, (object)null, ca.Article.Title)); }
//构造分页主从表查询分页对象 private IPager BuildMasterDetailPager(DataGateKey gkey, IDictionary <string, object> parameters) { var mainModel = gkey.TableJoins[0].Table; var tableMetas = gkey.TableJoins.Select(m => { return(m.Table); }); int pageSize = CommOp.ToInt(GetValueRemoveKey(parameters, "pageSize")); if (pageSize <= 0) { pageSize = Consts.DefaultPageSize; } return(new MasterDetailPagerInfo { TablesAndJoins = gkey.JoinSubTerm, Fields = gkey.QueryFieldsTerm, OrderBy = gkey.OrderBy, Filter = FormatFilter(gkey.Filter, tableMetas.ToArray()), KeyId = $"{gkey.TableJoins[0].Alias ?? mainModel.FixDbName}.{mainModel.PrimaryKey.FixDbName}", PageIndex = Math.Max(1, CommOp.ToInt(GetValueRemoveKey(parameters, "pageIndex"))) - 1, PageSize = pageSize, }); }
public JsonResult Delete(string ids) { var idArr = ids.Split(',') .Where(id => !id.IsEmpty()) .Select(id => CommOp.ToInt(id)) .ToList(); return(JsonTips("success", JStr.SuccessDeleted, SiteManager.Catalog.Delete(idArr.ToArray()))); }
private IQueryable <Base_CatalogArticle> GetUserQueryArticle(string modelName) { int userId = CommOp.ToInt(AppManager.Instance.GetCurrentUserId()); int modelNameId = SiteManager.Catalog.GetExtByName(AdvQuery.Query.Id, AdvQuery.Query.ModelName).Id; var arts = _article.GetAllAtCatalog(AdvQuery.Query.Id) .Where(ca => ca.Article.EditorId == userId && ca.Article.Exts.Any(ext => ext.CatlogExtId == modelNameId && ext.Value == modelName)); return(arts); }
public void TestGetDataSetReadXls1() { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestData", "2014年长庆油流向表油.xls"); ExcelHelper helper = new ExcelHelper(path); DataSet ds = helper.ExcelToDataSet(true); Assert.AreEqual(5, CommOp.ToInt(ds.Tables["区块数"].Rows[4]["序号"])); }
/// <summary> /// 根据指定主键获取对应的业务模型对象 /// </summary> /// <param name="key"></param> /// <returns></returns> public virtual TModel GetByKey(object key) { int id = CommOp.ToInt(key); var t = GetQuery().FirstOrDefault(e => e.Id == id); GetAttachmentsCollection(t); GetCollections(t); return(t); }
public IDataReader ExecPageReader(DBPagerInfo pager, params IDataParameter[] sp) { string sql = "SELECT COUNT(*) FROM (" + pager.Query + ")c"; pager.RecordCount = CommOp.ToInt(Helper.ExecGetObject(sql, sp)); sql = String.Format(@"SELECT * FROM(SELECT A.*, rownum r FROM({0} ORDER BY {1})A WHERE rownum <= {2})B WHERE r>{3}", pager.Query, pager.OrderBy, pager.StartIndex + pager.PageSize, pager.StartIndex); return(Helper.ExecReader(sql, sp)); }
/// <summary> /// 根据用户设置的提醒分钟数,设定事件的提醒时间 /// </summary> /// <param name="ca"></param> public static void AdjustAlertTime(Base_CatalogArticle ca) { var startTime = ca.GetExtDateTime(ScheduleEvent.Root.StartTime); var alertBefore = ca.GetExtStr(ScheduleEvent.Root.AlertBefore); if (!alertBefore.IsEmpty()) { ca.SetExt(ScheduleEvent.Root.AlertTime, startTime.AddMinutes(-CommOp.ToInt(alertBefore))); } }
public JsonResult Move(string ids, int pId) { var idArr = ids.Split(',') .Where(id => !id.IsEmpty()) .Select(id => CommOp.ToInt(id)) .ToList(); SiteManager.Catalog.Move(idArr, pId); return(JsonTips("success", JStr.SuccessMoved)); }
/// <summary> /// 根据查询名称获取高级查询对象 /// </summary> /// <param name="queryName">查询对象的名称</param> /// <param name="modelName">要查询的实体类型全名</param> /// <returns></returns> public AdvQueryItem GetQueryItemByName(string queryName, string modelName) { int userId = CommOp.ToInt(AppManager.Instance.GetCurrentUserId()); var ca = GetUserQueryArticle(modelName).FirstOrDefault(ca1 => ca1.Article.Title.Equals(queryName, StringComparison.OrdinalIgnoreCase)); _article.MatchTexts(ca.Article); return(new AdvQueryItem() { Id = ca.Id, Name = ca.Article.Title, Nodes = JsonHelper.FromJson <List <AdvQueryNode> >(ca.Article.Text), }); }
public override Base_CatalogArticle GetByKey(object oid) { int id = CommOp.ToInt(oid); Base_CatalogArticle catArt = GetQuery() .Include(ca => ca.Article.ArticleText) .FirstOrDefault(c => c.Id == id); if (catArt != null) { Detach(catArt); } return(catArt); }
public IDataReader ExecPageReader(DBPagerInfo pager, params IDataParameter[] sp) { if (pager.OrderBy.IsEmpty()) { throw new ArgumentException("pager.OrderBy"); } string sql = "SELECT COUNT(*) FROM (" + pager.Query + ")c"; pager.RecordCount = CommOp.ToInt(Helper.ExecGetObject(sql, sp)); sql = String.Format(@"{0} ORDER BY {1} LIMIT {2} OFFSET {3}", pager.Query, pager.OrderBy, pager.PageSize, pager.StartIndex); return(Helper.ExecReader(sql, sp)); }
[ValidateInput(false)] //因为要传递带html标签的art.Text,所以此处不能验证输入 public ActionResult Edit(T t) { ICUDEntity cud = t as ICUDEntity; if (cud != null) { cud.UpdaterId = CommOp.ToInt(CurrentUserId); } if (BeforeSaving(t)) { _dataProvider.Add(t); } return(AfterSaved(t)); }
public void SQLiteTestImportFromDataTable() { DataTable dt = TestObjects.MakeCustomerTable(); //先清除表的原数据,这不是必需的 helper.ExecNonQuery("DELETE FROM Biz_Order;DELETE FROM Biz_Customer"); //将前面生成的DataTable导入到表中 helper.Import(dt, null, true, 10, null); //count一下验证是否导入成功 object cnt = helper.ExecGetObject("SELECT COUNT(*) FROM Biz_Customer"); Assert.AreEqual(dt.Rows.Count, CommOp.ToInt(cnt)); }
/// <summary> /// 根据一串ID在数据库中删除对应的全部数据对象 /// </summary> /// <param name="keys"></param> /// <returns></returns> public virtual int DeleteByKeys(IEnumerable keys) { if (typeof(ICanLogicalDeleteEntity).IsAssignableFrom(typeof(TEntity))) { var ids = keys.Each(key => CommOp.ToInt(key)).ToArray(); var logicalDeletedList = _innerDataProvider.GetQuery().Where(t => ids.Contains(t.Id)) .ToArray() .Each(t => { (t as ICanLogicalDeleteEntity).IsDeleted = true; }); return(_innerDataProvider.Change(logicalDeletedList)); } else { return(_innerDataProvider.DeleteByKeys(keys)); } }
/// <summary> /// 保存查询对象,根据是否是新对象决定是插入还是改写 /// </summary> /// <param name="item">查询对象</param> public void Save(AdvQueryItem item) { var ca = GetUserQueryArticle(item.ModelName).FirstOrDefault(ca1 => ca1.Article.Title.Equals(item.Name, StringComparison.OrdinalIgnoreCase)); if (ca == null) { ca = _article.CreateByCatalog(AdvQuery.Query.Id); ca.Article.State = ArticleState.Published; } ca.Article.Title = item.Name; ca.Article.Text = JsonHelper.ToJson(item.Nodes); ca.Article.EditorId = CommOp.ToInt(AppManager.Instance.GetCurrentUserId()); ca.SetExt(AdvQuery.Query.ModelName, item.ModelName); _article.Save(ca); item.Id = ca.Id; }
public void OnResultExecuting(ResultExecutingContext filterContext) { _filterContext = filterContext; var jsonResult = filterContext.Result as JsonResult; _pageModel = new PageModel { AdvQuery = filterContext.HttpContext.Request["AdvQuery"], Key = CommOp.ToStr(filterContext.HttpContext.Request["Key"]), SortOrder = filterContext.HttpContext.Request["SortOrder"], SortField = filterContext.HttpContext.Request["SortField"], PageSize = CommOp.ToInt(filterContext.HttpContext.Request["PageSize"]), PageIndex = CommOp.ToInt(filterContext.HttpContext.Request["PageIndex"]), }; WrapData(jsonResult); }
/// <summary> /// 获取数据库中所有的表信息(转化为实体对象的形式) /// </summary> /// <returns>表集合</returns> public List <DBTable> GetSchema() { tables = new List <DBTable>(); string sqlstr = String.Format(@" SELECT id=d.id,name = d.name, description = case when a.colorder = 1 then isnull(f.value, '') else '' end FROM syscolumns a inner join sysobjects d on a.id = d.id and d.xtype = 'U' and d.name <> 'sysdiagrams' left join sys.extended_properties f on a.id = f.major_id and f.minor_id = 0 Where (case when a.colorder = 1 then d.name else '' end) <>''"); //查找所有的用户表(获取到表的id以及name) var tb = _helper.ExecDataTable(sqlstr); for (int i = 0; i < tb.Rows.Count; i++) { DBTable table = new DBTable { Id = CommOp.ToInt(tb.Rows[i]["id"]), Name = CommOp.ToStr(tb.Rows[i]["name"]), Description = CommOp.ToStr(tb.Rows[i]["description"]), Field = new List <DBField>(), Reletion = new List <DBRelation>() }; //获取用户表的所有字段 var attrs = GetAllFields(); foreach (DBField t in attrs.Where(t => t.DBTableId == table.Id)) { table.Field.Add(t); } //获取用户表的关系 var relas = GetTableRelation(); foreach (DBRelation t in relas.Where(t => t.PrimaryTable == table.Name || t.ForeignTable == table.Name)) { table.Reletion.Add(t); } tables.Add(table); } AddDescription(tables); return(tables); }
private IEnumerable <T> AfterGetData(IEnumerable <AppUser> userList) { foreach (var user in userList) { var cacheUser = usersList.FirstOrDefault(u => u.Id == user.Id) ?? SiteManager.Get <T>(); if (CommOp.ToInt(cacheUser.Id) == 0) { cacheUser.IsDefaultRole = true; } cacheUser.Id = user.Id; cacheUser.Name = user.Name; cacheUser.Email = user.Email; cacheUser.PhoneNumber = user.PhoneNumber; cacheUser.RoleIds = user.RoleIds; cacheUser.TrueName = user.TrueName; yield return(cacheUser); } }
/// <summary> /// 目录管理的主界面 /// </summary> /// <param name="root">管理的目录树的根结点ID或名称</param> /// <returns>主界面视图</returns> public ActionResult Index(string root = "") { InitMenuBar(); Base_Catalog rootCat = null; if (CommOp.IsNumeric(root)) { rootCat = SiteManager.Catalog.GetById(CommOp.ToInt(root)); } if (rootCat == null && !root.IsEmpty()) { rootCat = SiteManager.Catalog.GetByName(root); } if (rootCat == null) { rootCat = SiteManager.Get <Base_Catalog>(); } return(View(rootCat)); }
public virtual void SQLiteTestTransNonQuery() { int customerId = 0; while (true) { customerId = CommOp.ToInt(helper.ExecGetObject("SELECT Id FROM Biz_Customer LIMIT 1")); if (customerId > 0) { break; } SQLiteTestImportFromDataTable(); } helper.BeginTrans(); int r = helper.TransNonQuery(@"INSERT INTO [Biz_Order] ([Name] ,[ProductName] ,[Amount] ,[DelierDate] ,[CustomerId] ,[ManagerId]) VALUES (@Name ,@ProductName ,@Amount ,@DelierDate ,@CustomerId ,@ManagerId )", helper.CreateParameter("Name", "Computer") , helper.CreateParameter("ProductName", "Dell") , helper.CreateParameter("Amount", 101) , helper.CreateParameter("DelierDate", DateTime.Today) , helper.CreateParameter("CustomerId", customerId) , helper.CreateParameter("ManagerId", 1) ); helper.EndTrans(); Assert.AreEqual(r, 1); }
public virtual void AccessTestExecNonQuery() { DBHelper helper = new DBHelper("AccessConnection"); int customerId = 0; while (true) { customerId = CommOp.ToInt(helper.ExecGetObject("SELECT TOP 1 Id FROM Biz_Customer")); if (customerId > 0) { break; } AccessTestImportFromDataTable(); } //注意Access也可以用?号代替@参数名。access的参数顺序不能乱而且不能重复使用 int r = helper.ExecNonQuery(@"INSERT INTO [Biz_Order] ([Name] ,[ProductName] ,[Amount] ,[DelierDate] ,[CustomerId] ,[ManagerId]) VALUES (@Name ,@ProductName ,@Amount ,@DelierDate ,@CustomerId ,@ManagerId )", helper.CreateParameter("Name", "Computer" + DateTime.Now.Second) , helper.CreateParameter("ProductName", "Dell" + DateTime.Now.Millisecond) , helper.CreateParameter("Amount", 101) , helper.CreateParameter("DelierDate", DateTime.Today) , helper.CreateParameter("CustomerId", customerId) , helper.CreateParameter("ManagerId", 1) ); Assert.AreEqual(r, 1); }