/// <summary> /// 合并所有来自其他程序集的资源到主资源,前提是资源文件在对应项目的App_Data文件夹下 /// </summary> /// <param name="resNamespaces">资源所在的命名空间名称列表</param> /// <param name="overwriteExists">是否覆盖已经定义的资源</param> public static void CombinAssemblyResx(IEnumerable <Assembly> assemblys, bool overwriteExists = false) { foreach (var ns in assemblys) { foreach (string cultureName in GetUsedCultureNames()) { string resName = "app_data/customstrings." + cultureName.ToLower() + ".resx"; Stream stream = GetGResources(ns, resName) as Stream; if (stream == null) { continue; } ResXResourceReader reader = new ResXResourceReader(stream); var coll = GetCollection(cultureName); foreach (DictionaryEntry d in reader) { if ((coll[CommOp.ToStr(d.Key)].IsEmpty() || overwriteExists) && !CommOp.ToStr(d.Value).IsEmpty()) { coll[CommOp.ToStr(d.Key)] = CommOp.ToStr(d.Value); } } reader.Close(); } } }
private void SetCellValue(ICell cell, object obj) { if (obj == null) { cell.SetCellValue(""); return; } Type type = obj.GetType(); if (type == typeof(bool) || type == typeof(bool?)) { cell.SetCellValue(CommOp.ToBool(obj)); } else if (CommOp.ToDecimal(obj).ToString() == obj.ToString()) { cell.SetCellValue(CommOp.ToDouble(obj)); } else if (type == typeof(DateTime)) { cell.SetCellValue(CommOp.ToDateTime(obj)); } else { cell.SetCellValue(CommOp.ToStr(obj)); } }
/// <summary> /// 根据指定的类型名称和属性名称获取对应的属性配置项 /// </summary> /// <param name="className">类型名称</param> /// <param name="propName">属性名称</param> /// <param name="attr">标签属性</param> /// <returns>属性配置项</returns> public static AdvDataConfigItem GetPropertyConfig(CatalogExtAttribute attr, string className, string propName) { AdvDataConfigItem foundItem = null; var classConfig = _configCache.FirstOrDefault(cfg => cfg.ClassName.Equals(className)); if (classConfig == null) { classConfig = new AdvDataConfig() { ClassName = className }; _configCache.Add(classConfig); _modified = true; } foundItem = classConfig.Items.FirstOrDefault(c => c.PropertyName == propName); if (foundItem == null) { foundItem = new AdvDataConfigItem { OverWrite = true, FormOrder = 1, PropertyName = propName, GridOrder = 1, AllowNull = attr.AllowNull, DataSource = attr.DataSource.ToStr(), DataSourceType = CommOp.ToStr(attr.DataSourceType), DataType = attr.DataType.ToString(), MaxLength = attr.MaxLength, MinLength = attr.MinLength, MaxValue = CommOp.ToStr(attr.MaxValue), MinValue = CommOp.ToStr(attr.MinValue), RegExpr = attr.RegExpr, DefaultValue = attr.DefaultValue, InputFormat = attr.InputFormat, DisplayFormat = attr.DisplayFormat, Browsable = attr.Browsable, }; classConfig.Items.Add(foundItem); _modified = true; } else if (foundItem.OverWrite) { attr.DefaultValue = foundItem.DefaultValue; attr.DataType = CommOp.ToEnum <ExtDataType>(foundItem.DataType); attr.AllowNull = foundItem.AllowNull; attr.DataSource = foundItem.DataSource; attr.DataSourceType = CommOp.ToEnum <ExtDataSourceType>(foundItem.DataSourceType); attr.MaxLength = foundItem.MaxLength; attr.MinLength = foundItem.MinLength; attr.MaxValue = foundItem.MaxValue; attr.MinValue = foundItem.MinValue; attr.RegExpr = foundItem.RegExpr; attr.InputFormat = foundItem.InputFormat; attr.DisplayFormat = foundItem.DisplayFormat; attr.Browsable = foundItem.Browsable; } return(foundItem); }
/// <summary> /// 根据表名获取与表相关的约束(主外键关系) /// </summary> /// <param name="tableName"></param> /// <returns></returns> private IEnumerable <DBRelation> GetTableRelation() { List <DBRelation> tableRelas = new List <DBRelation>(); const string sqlstr = @"SELECT ConstrName=OBJECT_NAME(b.constid) ,ForeignTableId=b.fkeyid ,ForeignTableName=object_name(b.fkeyid) ,ForeignKey=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid) ,PrimaryTableId=b.rkeyid ,PrimaryTableName=object_name(b.rkeyid) ,PrimaryKey=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid) ,IsUpdateCascade=ObjectProperty(a.id,'CnstIsUpdateCascade') ,IsDeleteCascade=ObjectProperty(a.id,'CnstIsDeleteCascade') FROM sysobjects a join sysforeignkeys b on a.id=b.constid join sysobjects c on a.parent_obj=c.id where a.xtype='f' AND c.xtype='U'" ; var tb = _helper.ExecDataTable(sqlstr); for (int i = 0; i < tb.Rows.Count; i++) { DBRelation tableRela = new DBRelation { Id = i + 1, ConstrName = CommOp.ToStr(tb.Rows[i]["ConstrName"]),//约束名 PrimaryTable = CommOp.ToStr(tb.Rows[i]["PrimaryTableName"]), ForeignTable = CommOp.ToStr(tb.Rows[i]["ForeignTableName"]), PrimaryKey = CommOp.ToStr(tb.Rows[i]["PrimaryKey"]), ForeignKey = CommOp.ToStr(tb.Rows[i]["ForeignKey"]), IsUpdateCascade = CommOp.ToStr(tb.Rows[i]["IsUpdateCascade"]) == "1", IsDeleteCascade = CommOp.ToStr(tb.Rows[i]["IsDeleteCascade"]) == "1", }; tableRelas.Add(tableRela); } return(tableRelas); }
/// <summary> /// 通过RouteValues或QueryString获取指定的值 /// </summary> /// <param name="context"></param> /// <param name="name"></param> /// <returns></returns> public static string GetParamsValue(this RequestContext context, string name) { string r = CommOp.ToStr(context.RouteData.Values[name]); if (r.IsEmpty()) { r = CommOp.ToStr(context.HttpContext.Request[name]); } return(r); }
/// <summary> /// 去掉不必要的首尾空格 /// </summary> /// <param name="item">高级查询对象</param> public void ClearQueryItem(AdvQueryItem item) { item.Nodes.ForEach(node => { node.Expression = CommOp.ToStr(node.Expression); node.ExpressionText = CommOp.ToStr(node.ExpressionText); node.Value = CommOp.ToStr(node.Value); node.ValueText = CommOp.ToStr(node.ValueText); }); }
/// <summary> /// 将Reqesut.Form中没有在UploadRequest中定义的属性放到Metadata属性中。 /// </summary> /// <param name="request"></param> private void BuildMetadata(UploadRequest request) { foreach (string key in this.Request.Form.Keys) { if (!requestConstProps.Contains(key, StringComparer.OrdinalIgnoreCase)) { request.Metadata[key] = CommOp.ToStr(Request.Form[key]); } } }
public void OnAdd(DataGateKey gkey, IDictionary <string, object> ps) { foreach (string key in new string[] { "account", "email", "tel" }) { string accountKey = GetLUKey(ps, key); if (!accountKey.IsEmpty()) { ps[accountKey] = CommOp.ToStr(ps[accountKey]).ToLower(); } } }
static IEnumerable <SelectListItem> GetSelectList(DataTable dt) { int valIndex = dt.Columns.Count > 0 ? 1 : 0; var items = dt.Rows.Cast <DataRow>() .Select(dr => new SelectListItem { Text = CommOp.ToStr(dr[0]), Value = CommOp.ToStr(dr[valIndex]) }); return(items); }
//从参数表中获取值并移除参数中中该项,通常用于分页查询中获取分页参数 string GetValueRemoveKey(IDictionary <string, object> parameters, string key) { string dictKey = parameters.Keys.FirstOrDefault(k => k.Equals(key, StringComparison.OrdinalIgnoreCase)); if (dictKey != null) { var value = CommOp.ToStr(parameters[dictKey]); parameters.Remove(dictKey); return(value); } return(null); }
private string GetUrl(Base_CatalogArticle ca) { string processUrl = CommOp.ToStr(ca.GetExt(ScheduleEvent.Root.ProcessUrl)); if (processUrl.IsEmpty()) { return(null); } else { return(Url.Content(processUrl)); } }
/// <summary> /// 应用程序启动时的初始化操作,在基类中用于从URL判断当前语种 /// 如果在子类重写时没有调用基类方法,则会丢失此特性 /// </summary> protected virtual void Application_BeginRequest() { HttpContextBase contextWrapper = new HttpContextWrapper(HttpContext.Current); object culture = null; string cultureName = null; RouteData routeData = RouteTable.Routes.GetRouteData(contextWrapper); //判断URL中有无语言参数 if (routeData != null && routeData.Values.TryGetValue("culture", out culture)) { cultureName = CommOp.ToStr(culture); } //没有则从Cookie中取 else { cultureName = WebHelper.GetCookie("culture"); } //如果还没有,则从用户浏览器传过来的语言信息判断 if (cultureName.IsEmpty()) { if (!HttpContext.Current.Request.UserLanguages.IsEmpty()) { cultureName = HttpContext.Current.Request.UserLanguages.First(); } } //如果有明确的语言参数,则切换语言,并保存到Cookie if (!cultureName.IsEmpty()) { try { ResHelper.CurrentCultureName = cultureName; WebHelper.SetCookie("culture", cultureName, 14); } catch { } } string baseUrl = HttpContext.Current.Request.Url.LocalPath; //在浏览没有语言参数的首页URL时,当用户的语言的首选语言不是中文时,自动导向英文 //if (!cultureName.StartsWith("zh") && baseUrl == "/") //{ // HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri + "en-us"); //} }
public virtual ActionResult ForgotPassword(string userName, string email, string Email1) { var state = AppManager.Instance.StateProvider.SendPasswordResetMessage(userName, email, new Uri(Request.Url, Url.Action("ResetPassword")).ToString()); if (state == LoginState.OK) { //修改默认的初始密码跳转到登录页 return(JsonTips("success", null, FStr.ResetPasswordEmailSent, new { Url = Url.Action("Logout", "Account") })); //return JsonTipsLang("success", null, "Reset_Password_Email_Sent"); } else { return(JsonTips("error", state.ToString(), CommOp.ToStr(Session["ResetPasswordEmailBody"]))); } }
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> /// <param name="gkey"></param> /// <param name="param"></param> /// <returns></returns> private async Task <string> InsertOneAsync(DataGateKey gkey, JToken jToken) { var tableMeta = gkey.MainTable; IDictionary <string, object> psin = jToken.ToDictionary(); CheckPrimaryKey(tableMeta, psin, out string id, out string getMaxIdSql); gkey.DataGate.OnAdd(gkey, psin); List <string> fields = tableMeta.Fields.Where(f => !f.IsArray && f.ForeignField.IsEmpty()) .Select(f => f.Name).Intersect(psin.Select(kv => kv.Key), StringComparer.OrdinalIgnoreCase).ToList(); var ps = fields.Select(f => { //集合字段不进入Insert语句 var ff = tableMeta.Fields.FirstOrDefault(fd => fd.Name.Equals(f, StringComparison.OrdinalIgnoreCase)); if (ff != null && ff.IsArray) { return(null); } //外键字段pass掉 if (ff != null && !ff.ForeignField.IsEmpty()) { return(null); } var psKey = psin.Keys.First(key => key.Equals(f, StringComparison.OrdinalIgnoreCase)); return(new { f = ff.FixDbName, p = DB.CreateParameter(ff.DbName, psin[psKey]), }); }).Where(p => p.f != null); string strFields = String.Join(",", ps.Select(p => p.f)); string strValues = String.Join(",", ps.Select(p => '@' + p.p.ParameterName)); string sql = $"insert into {tableMeta.FixDbName} ({strFields}) values({strValues})"; await DB.ExecNonQueryAsync(sql, ps.Select(p => p.p).ToArray()); if (!getMaxIdSql.IsEmpty()) { id = CommOp.ToStr(await DB.ExecGetObjectAsync(getMaxIdSql)); psin["id"] = id; } gkey.DataGate.OnAdded(gkey, psin); return(id); }
/// <summary> /// 保存DataTable中的数据到所有语言的资源文件 /// </summary> /// <param name="dt">存有资源的DataTable</param> public static void SaveDataTable(DataTable dt) { foreach (DataColumn dc in dt.Columns) { if (dc.Ordinal == 0) { continue; } var coll = GetCollection(dc.ColumnName); coll.Clear(); foreach (DataRow dr in dt.Rows) { coll[(string)dr[0]] = CommOp.ToStr(dr[dc]); } } SaveAllRes(); }
/// <summary> /// 一次性加载所有语言的资源 /// </summary> static void LoadAllRes() { foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) { string resxFile = GetResxFileName(culture.Name); if (File.Exists(resxFile)) { ResXResourceReader reader = new ResXResourceReader(resxFile); var coll = new NameValueCollection(); foreach (DictionaryEntry d in reader) { coll[CommOp.ToStr(d.Key)] = CommOp.ToStr(d.Value); } mCultureDict[culture.Name] = coll; } } }
/// <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); }
/// <summary> /// 将Form表单中的数据导入实体对象中的同名属性 /// </summary> /// <param name="form">表单数据</param> /// <param name="model">实体对象</param> public static void AssignFormValues(this NameValueCollection form, object model) { //添加其他程序子类中的特殊属性 foreach (string key in form.Keys) { var prop = model.GetType().GetProperty(key); if (prop != null) { if (prop.PropertyType == typeof(bool)) { //在复选框时,勾选会传回两个值: true,false; 所以要分辨 RefHelper.SetValue(model, key, CommOp.ToStr(form[key]).Split(',').First()); } else { RefHelper.SetValue(model, key, CommOp.ToStr(form[key])); } } } }
//在新增记录时,对于单一主键的记录,检查主键字段是否自增或是guid,是否值为空, //如果是自增,则去掉传过来的值,由库自动生成,如果是guid并且为空,则生成一个guid private void CheckPrimaryKey(TableMeta tableMeta, IDictionary <string, object> psin, out string id, out string getMaxIdSql) { id = null; getMaxIdSql = null; var pKeyField = tableMeta.PrimaryKey; if (pKeyField == null) { return; } if (pKeyField.DataType == "Number") { getMaxIdSql = $"select max({pKeyField.FixDbName}) from {tableMeta.FixDbName}"; } var pkey = psin.Keys.FirstOrDefault(k => k.Equals(pKeyField.Name, StringComparison.OrdinalIgnoreCase)); //没有传主键字段过来 if (pkey == null) { pkey = pKeyField.Name; psin.Add(pkey, null); } //当主键为Number型时,认为是自增字段,为空时从参数中去掉,让数据库自动生成 if (pKeyField.DataType == "Number") { psin.Remove(pkey); } //非number型,并且为空,则认为是32位的guid字符串,为它自动生成 else if (CommOp.IsEmpty(psin[pkey])) { id = CommOp.NewId(); psin[pkey] = id; } else { id = CommOp.ToStr(psin[pkey]); } }
/// <summary> /// 根据sql语句返回下拉列表所需数据 /// </summary> /// <param name="catExt"></param> /// <returns></returns> public static IEnumerable <SelectListItem> GetSqlList(this Base_CatalogExt catExt) { string sql = catExt.DataSource; var dbHelper = SiteManager.Get <DBHelper>(); List <IDataParameter> ps = new List <IDataParameter>(); if (sql.Contains("@UserId")) { ps.Add(dbHelper.CreateParameter("@UserId", AppManager.Instance.GetCurrentUserId())); } DataTable dt = dbHelper.ExecDataTable(sql, ps.ToArray()); int valIndex = dt.Columns.Count > 0 ? 1 : 0; var items = dt.Rows.Cast <DataRow>() .Select(dr => new SelectListItem { Text = CommOp.ToStr(dr[0]), Value = CommOp.ToStr(dr[valIndex]) }); return(items); }
/// <summary> /// 获取表的所有字段 /// </summary> /// <returns>字段集合</returns> private IEnumerable <DBField> GetAllFields() { List <DBField> tableAttrs = new List <DBField>(); string sqlstr = String.Format(@"select tb1.*,tb2.isPrimaryKey from (select c.Id as tableId ,object_name(c.id) as tableName,c.colid as fieldid,c.name as filedName, t.name as type,c.isnullable as isNullable,c.prec as length ,m.text as deaulftValue,ex.value as description, (select COLUMNPROPERTY( c.id,c.name,'IsIdentity')) as isIdentifyField from syscolumns c inner join systypes t on c.xusertype=t.xusertype left join syscomments m on c.cdefault=m.id left join sys.extended_properties ex ON ex.major_id = c.id AND ex.minor_id = c.colid AND ex.name = 'MS_Description' WHERE OBJECTPROPERTY(c.id, 'IsMsShipped')=0 and c.id in(select id from sysobjects where type='U' and name!='sysdiagrams'))tb1 left join (SELECT TABLE_NAME,COLUMN_NAME,1 as isPrimaryKey FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME like 'PK_%')tb2 on tb1.tableName=tb2.TABLE_NAME and tb1.filedName=tb2.COLUMN_NAME"); var tb = _helper.ExecDataTable(sqlstr); for (int i = 0; i < tb.Rows.Count; i++) { DBField tableAttr = new DBField { Id = i + 1, DBTableId = CommOp.ToInt(tb.Rows[i]["tableId"]), //所在表ID DBTableName = CommOp.ToStr(tb.Rows[i]["tableName"]), FieldName = CommOp.ToStr(tb.Rows[i]["filedName"]), //属性的名称 //DataType = SqlTypeStrToCsharpType(tb.Rows[i]["type"].ToString()), DataType = tb.Rows[i]["type"].ToString(), AllowNull = CommOp.ToInt(tb.Rows[i]["isNullable"]) != 0, MaxLength = CommOp.ToInt(tb.Rows[i]["length"]), DefaultValue = CommOp.ToStr(tb.Rows[i]["deaulftValue"]), Description = CommOp.ToStr(tb.Rows[i]["description"]), IsPrimaryKey = CommOp.ToInt(tb.Rows[i]["isPrimaryKey"]) != 0, IsIdentifyField = CommOp.ToInt(tb.Rows[i]["isIdentifyField"]) != 0, }; tableAttrs.Add(tableAttr); } return(tableAttrs); }
//生成排序子句,排序子句的传入规则是 field1 a/d field2 a/d ... private void CreateOrderStr(DataGateKey gkey, TableMeta tableMeta, IDictionary <string, object> ps) { if (!ps.ContainsKey(Consts.SortKey)) { return; } var sortStr = CommOp.ToStr(ps[Consts.SortKey]); ps.Remove(Consts.SortKey); var sortArr = sortStr.Split(' '); List <string> sorts = new List <string>(); for (var i = 0; i < sortArr.Length - 1; i += 2) { string f = sortArr[i]; string field = GetSortField(f, gkey); if (field.IsEmpty()) { continue; } string ad = sortArr[i + 1]; if (ad.StartsWith("d")) { sorts.Add(field + " desc"); } else { sorts.Add(field.ToStr()); } } string orderby = String.Join(",", sorts); if (!orderby.IsEmpty()) { gkey.OrderBy = orderby; } }
/// <summary> /// 获取文章扩展展性的显示值(来自键值对的下拉列表中的显示内容) /// </summary> /// <param name="ca"></param> /// <param name="name"></param> /// <returns></returns> public static object GetExtDisplay(this Base_CatalogArticle ca, Base_CatalogExt catExt) { if (catExt.DataSource.IsEmpty()) { return(GetExt(ca, catExt)); } else { var obj = GetExt(ca, catExt); string str = CommOp.ToStr(obj); StringSpliter ss = new StringSpliter(catExt.DataSource, ";", "="); foreach (var key in ss.Keys) { if (ss[key] == str) { return(key); } } } return(GetExt(ca, catExt)); }
/// <summary> /// 将object参数序列化到url的查询字符串中 /// </summary> /// <param name="o"></param> /// <returns></returns> public string SerialzeToUrl(object o) { if (o == null) { return(null); } return("?" + string.Join("&", o.GetType().GetProperties() .Select(pi => $"{pi.Name}={HttpUtility.UrlEncode(CommOp.ToStr(pi.GetValue(o, null)))}"))); }
/// <summary> /// 分析页面传过来的修改过的子表对象数组,并更新原有子表对象集合 /// 此方法被自动反射调用 /// </summary> /// <typeparam name="TItemModel">子表对象类型</typeparam> /// <param name="t">主表对象</param> /// <param name="propName">子表集合在主表对象中的属性名称</param> protected void SaveDetails <TItemModel>(TModel t, string propName) where TItemModel : IId <TKey> { String json = Request["DetailChanges_" + propName]; var prop = typeof(TModel).GetProperty(propName); var itemEnum = prop.GetValue(t, null) as IEnumerable <TItemModel>; if (itemEnum == null) { itemEnum = new List <TItemModel>(); prop.SetValue(t, itemEnum, null); } var itemList = itemEnum as IList <TItemModel>; if (itemList == null) { itemList = new List <TItemModel>(itemEnum); prop.SetValue(t, itemList, null); } //string listTypeName = "System.Collections.Generic.List`1[[" + itemType.AssemblyQualifiedName + "]],mscorlib"; //Type listType = RefHelper.LoadType(listTypeName); var rows = (ArrayList)JsonHelper.FormJson(json); var itemModels = JsonHelper.FromJson <List <TItemModel> >(json); foreach (var itemModel in itemModels) { if (itemModel.Id.IsDefault()) { itemList.Add(itemModel); } } foreach (Hashtable row in rows) { string id = CommOp.ToStr(row["Id"]); //根据记录状态,进行不同的增加、删除、修改操作 String state = row["_state"] != null ? row["_state"].ToString() : ""; if (state == "removed" || state == "deleted") { var oldObj = itemList.FirstOrDefault(item => CommOp.ToStr(item.Id).Equals(id)); if (oldObj != null) { itemList.Remove(oldObj); } } else if (state == "modified" || state == "") //更新:_state为空或modified { var oldObj = itemList.FirstOrDefault(item => CommOp.ToStr(item.Id).Equals(id)); var newObj = itemModels.First(item => CommOp.ToStr(item.Id).Equals(id)); if (oldObj != null) { int idx = itemList.IndexOf(oldObj); itemList[idx] = newObj; } } else if (state == "added") { var oldObj = itemList.FirstOrDefault(item => CommOp.ToStr(item.Id).Equals(id)); var newObj = itemModels.FirstOrDefault(item => CommOp.ToStr(item.Id).Equals(id) && !item.Id.IsDefault()); if (oldObj == null && newObj != null) { itemList.Add(newObj); } } } }
public static object SetExt(this Base_Article article, Base_CatalogExt catExt, object value) { if (catExt == null) { return(null); } var artExt = article.Exts.FirstOrDefault(ext => ext.CatlogExtId == catExt.Id); if (artExt == null) { artExt = new Base_ArticleExt { CatlogExtId = catExt.Id, }; article.Exts.Add(artExt); } ; string strValue = null; switch ((ExtDataType)catExt.DataType) { case ExtDataType.Currency: Decimal?dec = CommOp.ToDecimalNull(value); if (dec != null) { strValue = dec.Value.ToString(); } break; case ExtDataType.FloatNumber: double?flt = CommOp.ToDoubleNull(value); if (flt != null) { strValue = flt.Value.ToString(); } break; case ExtDataType.DateAndTime: case ExtDataType.Date: DateTime?dt = CommOp.ToDateTimeNull(value); if (dt != null) { strValue = dt.Value.ToString("yyyy-MM-dd HH:mm:ss"); } break; case ExtDataType.SingleNumber: long?lng = CommOp.ToLongNull(value); if (lng != null) { strValue = lng.Value.ToString(); } break; case ExtDataType.Bool: value = CommOp.ToBool(value); strValue = value.ToString(); break; default: strValue = CommOp.ToStr(value); if (strValue.IsEmpty()) { strValue = null; } break; } artExt.Value = strValue; return(value); }
/// <summary> /// 获取字符串扩展属性 /// </summary> /// <param name="ca"></param> /// <param name="name"></param> /// <returns></returns> public static string GetExtStr(this Base_CatalogArticle ca, string name) { return(CommOp.ToStr(ca.GetExt(name))); }
/// <summary> /// 根据传过来的地址栏filter参数来获取查询条件 /// 与服务端配置的filter合并 /// </summary> /// <param name="tableMeta"></param> /// <param name="ps"></param> /// <returns></returns> private void CreateFilterStr(DataGateKey gkey, TableMeta tableMeta, IDictionary <string, object> ps) { if (!ps.ContainsKey(Consts.FilterKey)) { return; } var filterStr = CommOp.ToStr(ps[Consts.FilterKey]); var requests = JsonConvert.DeserializeObject <FilterRequest[]>(filterStr); ps.Remove(Consts.FilterKey); filterStr = string.Join(" and ", requests.Select(r => { var field = tableMeta.Fields.FirstOrDefault(f => f.Name.Equals(r.Name, StringComparison.OrdinalIgnoreCase)); if (field == null) { return(null); } string left = field.ForeignField.IsEmpty() ? (gkey.TableJoins[0].Alias ?? tableMeta.Name) + "." + field.Name : field.ForeignField; //当有sql语句并且有模型定义时 if (!gkey.Sql.IsEmpty() && gkey.TableJoins.Count > 0) { left = field.Name; } string pName = r.Name + "_f"; //加后缀以免和未知的key冲突 ps[pName] = r.Value; switch (r.Operator) { case "e": return($"{left}=@{pName}"); //判断日期相等,日期相等比较特殊,很难精确相等, //因此转成只判断是否在当天 case "de": var date = CommOp.ToDateTime(r.Value).Date; var date1 = date.AddDays(1).AddTicks(-1); ps[pName] = date; ps[pName + 1] = date1; return($"{left} between @{pName} and @{pName}1"); case "ne": return($"{left}!=@{pName}"); case "in": ps[pName] = CommOp.ToStr(ps[pName]).Split(','); return($"{left} in (@{pName})"); case "nin": ps[pName] = CommOp.ToStr(ps[pName]).Split(','); return($"{left} not in (@{pName})"); case "i": ps[pName] = "%" + r.Value + '%'; return($"{left} like @{pName}"); case "ni": ps[pName] = "%" + r.Value + '%'; return($"{left} not like @{pName}"); case "lte": return($"{left} <= @{pName}"); case "gte": return($"{left} >= @{pName}"); case "bt": if (r.Value1.IsDefault()) { return($"{left} >= @{pName}"); } if (field.DataType == "Date" || field.DataType == "DateTime") { r.Value1 = CommOp.ToDateTime(r.Value1).Date.AddDays(1).AddTicks(-1); } ps[pName + 1] = r.Value1; return($"{left} between @{pName} and @{pName}1"); case "n": return($"{left} is null"); case "nn": return($"{left} is not null"); default: return(null); //throw new ArgumentException("非法的查询请求:" + r.Operator); } }).Where(r => r != null)); //与原有的gkey.Filter合并得到一个and条件 if (!filterStr.IsEmpty()) { gkey.Filter = gkey.Filter.IsEmpty() ? filterStr : $"({gkey.Filter}) and {filterStr}"; } }
public virtual T GetByKey(object key) { string keyName = ModelHelper.GetKeyField(typeof(T)); return(this.DBHelper.GetModelById <T>(keyName, CommOp.ToStr(key))); }