/// <summary> /// 缓存结果 /// </summary> /// <param name="info"></param> /// <param name="item"></param> private static void CacheResult(ApiGatewayUrl item, DataContext db, ReturnModel info = null, Dictionary <string, object> dic = null) { var model = new ApiGatewayCache(); model.Key = item.Key.ToLower(); model.TimeOut = DateTime.Now.AddDays(item.CacheTimeOut.ToStr().ToDouble(0)).AddHours(8); if (info != null) { model.result = BaseJson.ModelToJson(info.msg); } if (dic != null) { model.result = BaseJson.ModelToJson(dic); } if (FastRead.Query <ApiGatewayCache>(a => a.Key.ToUpper() == model.Key.ToUpper()).ToCount(db) <= 0) { FastWrite.Add(model); } else { FastWrite.Update <ApiGatewayCache>(model, a => a.Key.ToUpper() == model.Key.ToUpper(), a => new { a.result, a.TimeOut }, db); } }
public Task <Dictionary <string, object> > XmlDelAsyn(object name) { var result = new Dictionary <string, object>(); if (string.IsNullOrEmpty(name.ToStr().ToLower().Replace(".xml", ""))) { result.Add("msg", "xml文件名填写不正确"); } else { System.IO.File.Delete(name.ToStr()); var map = BaseConfig.GetValue <SqlMap>("SqlMap", "map.json", false); if (map.Path.Exists(a => a.ToLower() == string.Format("map/{0}", name.ToStr().ToLower()))) { var dic = new Dictionary <string, object>(); map.Path.Remove("map/" + name.ToStr()); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText("map.json", json); FastMap.InstanceMap(); } result.Add("msg", "操作成功"); } return(Task.FromResult(result)); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseExceptionHandler(error => { error.Use(async(context, next) => { var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { BaseLog.SaveLog(contextFeature.Error.Message, "error"); context.Response.ContentType = "application/json;charset=utf-8"; context.Response.StatusCode = 200; var result = new Dictionary <string, object>(); result.Add("success", false); result.Add("msg", contextFeature.Error.Message); await context.Response.WriteAsync(BaseJson.ModelToJson(result)); } }); }); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); }
/// <summary> /// 验证token /// </summary> /// <param name="item"></param> /// <param name="context"></param> private static bool CheckToken(ApiGatewayUrl item, HttpContext context, DataContext db, string urlParam) { var dic = new Dictionary <string, object>(); var token = GetUrlParamKey(urlParam, "token"); if (FastRead.Query <ApiGatewayUser>(a => a.AccessToken.ToUpper() == token.ToUpper()).ToCount(db) == 0) { context.Response.StatusCode = 200; dic.Add("success", false); dic.Add("result", "token不存在"); context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8); return(false); } else { var tokenInfo = FastRead.Query <ApiGatewayUser>(a => a.AccessToken.ToUpper() == token.ToUpper()).ToItem <ApiGatewayUser>(db); if (DateTime.Compare(tokenInfo.AccessExpires, DateTime.Now) < 0) { context.Response.StatusCode = 200; dic.Add("success", false); dic.Add("result", "token过期"); context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8); return(false); } if (tokenInfo.Ip != GetClientIp(context)) { context.Response.StatusCode = 200; dic.Add("success", false); dic.Add("result", "token授权ip地址异常"); context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8); return(false); } if (tokenInfo.Power.IndexOf(',') > 0) { foreach (var temp in tokenInfo.Power.Split(',')) { if (temp.ToLower() == item.Key.ToLower()) { return(true); } } context.Response.StatusCode = 200; dic.Add("success", false); dic.Add("result", string.Format("{0}没有权限访问", item.Key)); context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8); return(false); } else { context.Response.StatusCode = 200; dic.Add("success", false); dic.Add("result", string.Format("{0}没有权限访问", item.Key)); context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8); return(false); } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseExceptionHandler(error => { error.Use(async(context, next) => { var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { BaseLog.SaveLog(contextFeature.Error.Message, "error"); context.Response.ContentType = "application/json;charset=utf-8"; context.Response.StatusCode = 200; var result = new Dictionary <string, object>(); result.Add("success", false); result.Add("msg", contextFeature.Error.Message); await context.Response.WriteAsync(BaseJson.ModelToJson(result)); } }); }); app.UseStaticFiles(); app.UseMiddleware <FastApiHandler>(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{action=index}/{id?}"); }); }
public IActionResult Del(string name) { if (string.IsNullOrEmpty(name)) { return(Json(new { msg = "xml文件名不能为空" })); } else if (string.IsNullOrEmpty(name.ToLower().Replace(".xml", ""))) { return(Json(new { msg = "xml文件名填写不正确" })); } else { var xmlPath = string.Format("map/{0}", name); System.IO.File.Delete(xmlPath); var map = BaseConfig.GetValue <SqlMap>("SqlMap", "map.json"); if (map.Path.Exists(a => a.ToLower() == string.Format("map/{0}", name.ToLower()))) { var dic = new Dictionary <string, object>(); map.Path.Remove("map/" + name); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText("map.json", json); FastMap.InstanceMap(); } return(Json(new { msg = "操作成功" })); } }
public IActionResult Del(string name) { if (string.IsNullOrEmpty(name)) { return(Json(new { msg = "xml文件名不能为空" })); } else if (string.IsNullOrEmpty(name.ToLower().Replace(".xml", ""))) { return(Json(new { msg = "xml文件名填写不正确" })); } else { System.IO.File.Delete(name); var map = BaseConfig.GetValue <SqlMap>("SqlMap", FastApiExtension.config.mapFile); if (!map.Path.Exists(a => string.Compare(a, name) == 0)) { var dic = new Dictionary <string, object>(); map.Path.Remove(name); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText(FastApiExtension.config.mapFile, json); FastMap.InstanceMap(); } return(Json(new { msg = "操作成功" })); } }
public IActionResult OnPostDel(DelParam item) { var result = new Dictionary <string, object>(); if (string.IsNullOrEmpty(item.name.ToLower().Replace(".xml", ""))) { result.Add("msg", "xml文件名填写不正确"); } else { System.IO.File.Delete(item.name); var map = BaseConfig.GetValue <SqlMap>("SqlMap", FastApiExtension.config.mapFile, false); if (!map.Path.Exists(a => string.Compare(a, item.name) == 0)) { var dic = new Dictionary <string, object>(); map.Path.Remove(item.name); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText(FastApiExtension.config.mapFile, json); FastMap.InstanceMap(); } result.Add("msg", "操作成功"); } return(new JsonResult(result)); }
public Task <Dictionary <string, object> > XmlSaveAsyn(object name, object xml) { var IFast = ServiceContext.Engine.Resolve <IFastRepository>(); var result = new Dictionary <string, object>(); try { if (string.IsNullOrEmpty(name.ToStr().ToLower().Replace(".xml", ""))) { result.Add("msg", "xml文件名填写不正确"); result.Add("Issuccess", false); } else { using (var xmlWrite = System.IO.File.Create(name.ToStr())) { xmlWrite.Write(Encoding.Default.GetBytes(xml.ToStr())); } if (IFast.CheckMap(name.ToStr())) { var map = BaseConfig.GetValue <SqlMap>("SqlMap", "map.json", false); if (!map.Path.Exists(a => a.ToLower() == string.Format("map/{0}", name.ToStr().ToLower()))) { var dic = new Dictionary <string, object>(); map.Path.Add(string.Format("map/{0}", name.ToStr())); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText("map.json", json); } FastMap.InstanceMap(); result.Add("msg", "操作成功"); result.Add("Issuccess", true); } else { result.Add("msg", "操作失败"); result.Add("Issuccess", false); } } return(Task.FromResult(result)); } catch (Exception ex) { BaseLog.SaveLog(ex.StackTrace, "xml"); result.Add("msg", ex.Message); result.Add("Issuccess", false); return(Task.FromResult(result)); } }
public IActionResult OnPostXml(SaveParam item) { var result = new Dictionary <string, object>(); try { if (string.IsNullOrEmpty(item.name.ToLower().Replace(".xml", ""))) { result.Add("msg", "xml文件名填写不正确"); result.Add("Issuccess", false); } else { var xmlPath = string.Format("map/{0}", item.name); using (var xmlWrite = System.IO.File.Create(xmlPath)) { xmlWrite.Write(Encoding.Default.GetBytes(item.xml)); } if (IFast.CheckMap(xmlPath)) { var map = BaseConfig.GetValue <SqlMap>("SqlMap", "map.json"); if (!map.Path.Exists(a => a.ToLower() == string.Format("map/{0}", item.name.ToLower()))) { var dic = new Dictionary <string, object>(); map.Path.Add(string.Format("map/{0}", item.name)); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText("map.json", json); } FastMap.InstanceMap(); result.Add("msg", "操作成功"); result.Add("Issuccess", true); } else { result.Add("msg", "操作失败"); result.Add("Issuccess", false); } } return(new JsonResult(result)); } catch (Exception ex) { BaseLog.SaveLog(ex.StackTrace, "xml"); result.Add("msg", ex.Message); result.Add("Issuccess", false); return(new JsonResult(result)); } }
public IActionResult Xml(string xml, string name) { try { if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(name)) { return(Json(new { msg = "xml或文件名不能为空", Issuccess = false })); } else if (string.IsNullOrEmpty(name.ToLower().Replace(".xml", ""))) { return(Json(new { msg = "xml文件名填写不正确", Issuccess = false })); } else { var xmlPath = string.Format("map/{0}", name); using (var xmlWrite = System.IO.File.Create(xmlPath)) { xmlWrite.Write(Encoding.Default.GetBytes(xml)); } if (IFast.CheckMap(xmlPath)) { var map = BaseConfig.GetValue <SqlMap>("SqlMap", "map.json"); if (!map.Path.Exists(a => a.ToLower() == string.Format("map/{0}", name.ToLower()))) { var dic = new Dictionary <string, object>(); map.Path.Add(string.Format("map/{0}", name)); dic.Add("SqlMap", map); var json = BaseJson.ModelToJson(dic); System.IO.File.WriteAllText("map.json", json); } FastMap.InstanceMap(); return(Json(new { msg = "操作成功", Issuccess = true })); } else { return(Json(new { msg = "操作失败", Issuccess = false })); } } } catch (Exception ex) { BaseLog.SaveLog(ex.StackTrace, "xml"); return(Json(new { msg = ex.Message, Issuccess = false })); } }
/// <summary> /// 设置值 item /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="key">键</param> /// <param name="model">值</param> /// <param name="hours">存期限</param> /// <returns></returns> public static bool Set <T>(string key, T model, TimeSpan timeSpan, int db = 0) { try { db = db == 0 ? _db : db; if (!string.IsNullOrEmpty(key)) { return(Context.GetDatabase(db).StringSet(key, BaseJson.ModelToJson(model), timeSpan)); } else { return(false); } } catch (RedisException ex) { SaveLog <T>(ex, "Set<T>"); return(false); } }
/// <summary> /// 设置值 item asy /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="key">键</param> /// <param name="model">值</param> /// <param name="hours">存期限</param> /// <returns></returns> public static async Task <bool> SetAsy <T>(string key, T model, int hours = 24 * 30 * 12, int db = 0) { try { db = db == 0 ? _db : db; if (!string.IsNullOrEmpty(key)) { return(await Context.GetDatabase(db).StringSetAsync(key, BaseJson.ModelToJson(model), TimeSpan.FromHours(hours)).ConfigureAwait(false)); } else { return(false); } } catch (RedisException ex) { SaveLog <T>(ex, "Set<T>"); return(false); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseExceptionHandler(error => { error.Use(async(context, next) => { var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { BaseLog.SaveLog(contextFeature.Error.Message, "error"); context.Response.ContentType = "application/json;charset=utf-8"; context.Response.StatusCode = 200; var result = new Dictionary <string, object>(); result.Add("success", false); result.Add("msg", contextFeature.Error.Message); await context.Response.WriteAsync(BaseJson.ModelToJson(result)); } }); }); app.UseStaticFiles(); app.UseFastApiMiddleware(a => { a.IsResource = false; a.IsAlone = true; a.FilterUrl.Add("help"); a.FilterUrl.Add("xml"); a.FilterUrl.Add("del"); }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{action=Index}/{id?}"); }); }
/// <summary> /// 处理请求 /// </summary> /// <param name="downparam">下游</param> /// <param name="param">请求参数</param> /// <param name="content">请求参数body</param> /// <returns></returns> private static ReturnModel GetReuslt(ApiGatewayDownParam downparam, string param, string key, int isTextLog, int isDbLog, DataContext db, HttpContext context, string ActionId, int OrderBy, IHttpClientFactory client) { var info = FastRead.Query <ApiGatewayWait>(a => a.Key.ToLower() == key.ToLower() && a.Url.ToLower() == downparam.Url.ToLower()).ToItem <ApiGatewayWait>(db) ?? new ApiGatewayWait(); if (info.Key.ToStr().ToLower() == key.ToLower() && DateTime.Compare(info.NextAction, DateTime.Now) > 0) { //return time out var dic = new Dictionary <string, object>(); dic.Add("success", false); dic.Add("result", "等待恢复"); return(new ReturnModel { msg = BaseJson.ModelToJson(dic), status = 408 }); } else { var result = new ReturnModel(); var stopwatch = new Stopwatch(); stopwatch.Start(); if (downparam.Protocol.ToLower() == "soap") { result = BaseUrl.SoapUrl(downparam.Url, downparam.SoapParamName, downparam.SoapMethod, param, client, key, downparam.SoapNamespace); } else if (downparam.Protocol.ToLower() == "http") { //http if (downparam.Method.ToStr().ToLower() == "post") { if (downparam.IsBody == 1) { result = BaseUrl.PostContent(downparam.Url, param, key, client); } else { result = BaseUrl.PostUrl(downparam.Url, param, key, client); } } else if (downparam.Method.ToStr().ToLower() == "get") { result = BaseUrl.GetUrl(downparam.Url, param, key, client); } } //else if (downparam.Protocol.ToLower() == "mq") // //mq // result = BaseUrl.RabbitUrl(downparam.QueueName, param); else { result.status = 408; } if (result.status == 408) { //time out var wait = new ApiGatewayWait(); wait.Key = key; wait.Url = downparam.Url; wait.WaitHour = downparam.WaitHour.ToInt(0); wait.ErrorMsg = result.msg; wait.NextAction = DateTime.Now.AddHours(wait.WaitHour.ToStr().ToDouble(0)); FastWrite.Add(wait, db); } else if (info.Key.ToStr().ToLower() == key.ToLower()) { FastWrite.Delete <ApiGatewayWait>(a => a.Key.ToLower() == key.ToLower(), db); } stopwatch.Stop(); var logInfo = new ApiGatewayLog(); logInfo.ActionId = ActionId; logInfo.OrderBy = OrderBy; logInfo.Key = key; logInfo.ActionTime = DateTime.Now; logInfo.Url = downparam.Url; logInfo.Protocol = downparam.Protocol; logInfo.Success = result.status == 200 ? 1 : 0; logInfo.Result = result.msg; logInfo.Milliseconds = stopwatch.Elapsed.TotalMilliseconds; logInfo.ActionIp = GetClientIp(context); logInfo.ActionParam = param; if (isDbLog == 1) { FastWrite.Add(logInfo, null, DbApi); } if (isTextLog == 1) { BaseLog.SaveLog(BaseJson.ModelToJson(logInfo), logInfo.Key); } return(result); } }
void BeginRequest(object sender, EventArgs e) { var success = true; var dic = new Dictionary <string, object>(); var param = new List <DbParameter>(); var context = ((HttpApplication)sender); var key = context.Request.CurrentExecutionFilePath; key = string.IsNullOrEmpty(key) ? "" : key.Substring(1, key.Length - 1); if (FastMap.IsExists(key)) { context.Response.StatusCode = 200; context.Response.ContentType = "application/Json"; var data = new List <Dictionary <string, object> >(); var pageInfo = new PageResult(); var dbKey = FastMap.MapDb(key).ToStr(); var type = FastMap.MapType(key).ToStr(); var config = FastMap.DbConfig(dbKey); var url = context.Request.Form; if (url.Count == 0) { url = context.Request.QueryString; } var pageSize = url.GetValues("pageSize").ToStr().ToInt(10); var pageId = url.GetValues("pageId").ToStr().ToInt(1); foreach (var item in url) { var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter(); temp.ParameterName = item.ToStr(); temp.Value = url.Get(item.ToStr()); param.Add(temp); var existsKey = FastMap.MapExists(key, temp.ParameterName); var checkKey = FastMap.MapCheck(key, temp.ParameterName); //required if (!string.IsNullOrEmpty(FastMap.MapRequired(key, temp.ParameterName))) { dic.Add("success", false); dic.Add("error", string.Format("{0}不能为空", item)); param.Remove(temp); break; } //max length if (FastMap.MapMaxlength(key, temp.ParameterName).ToInt(0) != 0) { if (!(FastMap.MapMaxlength(key, temp.ParameterName).ToInt(0) >= temp.Value.ToStr().Length)) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1},最大长度{2}", item, temp.Value.ToStr(), FastMap.MapMaxlength(key, temp.ParameterName))); param.Remove(temp); break; } } //exists if (!string.IsNullOrEmpty(existsKey)) { var existsListParam = new List <DbParameter>(); var existsParam = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter(); existsParam.ParameterName = temp.ParameterName; existsParam.Value = temp.Value; existsListParam.Add(existsParam); var checkData = FastMap.Query(existsKey, existsListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) >= 1) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1}已存在", item, temp.Value)); param.Remove(temp); break; } } //check if (!string.IsNullOrEmpty(checkKey)) { var checkListParam = new List <DbParameter>(); var checkParam = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter(); checkParam.ParameterName = temp.ParameterName; checkParam.Value = temp.Value; checkListParam.Add(checkParam); var checkData = FastMap.Query(existsKey, checkListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) < 1) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1}不存在", item, temp.Value)); param.Remove(temp); break; } } //date if (string.Compare(FastMap.MapDate(key, temp.ParameterName).ToStr(), "true", true) == 0) { if (!BaseRegular.IsDate(temp.Value.ToStr())) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1},不是日期类型", item, temp.Value)); param.Remove(temp); break; } temp.Value = temp.Value.ToDate(); temp.DbType = System.Data.DbType.DateTime; } } if (dic.Count > 0) { context.Response.StatusCode = 200; context.Response.ContentType = "application/Json"; context.Response.Write(BaseJson.ModelToJson(dic)); context.Response.End(); } else { using (var db = new DataContext(dbKey)) { var tempParam = param.ToArray(); var sql = MapXml.GetMapSql(key, ref tempParam, db, dbKey); if (string.Compare(type, AppConfig.PageAll, true) == 0 || string.Compare(type, AppConfig.Page, true) == 0) { success = true; var page = new PageModel(); page.PageSize = pageSize == 0 ? 10 : pageSize; page.PageId = pageId == 0 ? 1 : pageId; pageInfo = db.GetPageSql(page, sql, tempParam).PageResult; dic.Add("data", pageInfo.list); dic.Add("page", pageInfo.pModel); } else if (string.Compare(type, AppConfig.All, true) == 0) { success = true; data = db.ExecuteSqlList(sql, tempParam, false).DicList; dic.Add("data", data); } else if (string.Compare(type, AppConfig.Write, true) == 0 && param.Count > 0) { var result = db.ExecuteSqlList(sql, tempParam, false).writeReturn; if (result.IsSuccess) { success = true; } else { success = false; dic.Add("error", result.Message); } } else { if (param.Count > 0) { success = true; data = db.ExecuteSqlList(sql, tempParam, false).DicList; dic.Add("data", data); } else { success = false; } } } } //if (FastMap.MapView(key).ToStr() != "") //{ // context.Response.ContentType = "text/html;charset=utf-8"; //} //else { dic.Add("success", success); context.Response.Write(BaseJson.ModelToJson(dic)); context.Response.End(); } } }
public static void InstanceMapResource(string dbKey = null, string dbFile = "db.json", string mapFile = "map.json") { var projectName = Assembly.GetCallingAssembly().GetName().Name; var config = DataConfig.Get(dbKey, projectName, dbFile); var db = new DataContext(dbKey); var assembly = Assembly.Load(projectName); var map = new MapConfigModel(); using (var resource = assembly.GetManifestResourceStream(string.Format("{0}.{1}", projectName, mapFile))) { if (resource != null) { using (var reader = new StreamReader(resource)) { var content = reader.ReadToEnd(); map.Path = BaseJson.JsonToModel <List <string> >(BaseJson.JsonToDic(BaseJson.ModelToJson(BaseJson.JsonToDic(content).GetValue(AppSettingKey.Map))).GetValue("Path").ToStr()); } } else { map = BaseConfig.GetValue <MapConfigModel>(AppSettingKey.Map, mapFile); } } if (map.Path == null) { return; } map.Path.ForEach(a => { using (var resource = assembly.GetManifestResourceStream(string.Format("{0}.{1}", projectName, a.Replace("/", ".")))) { var xml = ""; if (resource != null) { using (var reader = new StreamReader(resource)) { xml = reader.ReadToEnd(); } } var info = new FileInfo(a); var key = BaseSymmetric.Generate(info.FullName); if (!DbCache.Exists(config.CacheType, key)) { var temp = new MapXmlModel(); temp.LastWrite = info.LastWriteTime; temp.FileKey = MapXml.ReadXml(info.FullName, config, info.Name.ToLower().Replace(".xml", ""), xml); temp.FileName = info.FullName; if (MapXml.SaveXml(dbKey, key, info, config, db)) { DbCache.Set <MapXmlModel>(config.CacheType, key, temp); } } else if ((DbCache.Get <MapXmlModel>(config.CacheType, key).LastWrite - info.LastWriteTime).Milliseconds != 0) { DbCache.Get <MapXmlModel>(config.CacheType, key).FileKey.ForEach(f => { DbCache.Remove(config.CacheType, f); }); var model = new MapXmlModel(); model.LastWrite = info.LastWriteTime; model.FileKey = MapXml.ReadXml(info.FullName, config, info.Name.ToLower().Replace(".xml", ""), xml); model.FileName = info.FullName; if (MapXml.SaveXml(dbKey, key, info, config, db)) { DbCache.Set <MapXmlModel>(config.CacheType, key, model); } } } }); }
public async Task ContentAsync(HttpContext context, IFastRepository IFast, bool IsResource, string dbFile = "db.json") { var name = context.Request.Path.Value.ToStr().Substring(1, context.Request.Path.Value.ToStr().Length - 1).ToLower(); var urlParam = HttpUtility.UrlDecode(GetUrlParam(context)); var success = true; var dic = new Dictionary <string, object>(); var data = new List <Dictionary <string, object> >(); var dbKey = IFast.MapDb(name).ToStr(); var pageInfo = new PageResult(); context.Response.StatusCode = 200; context.Response.ContentType = "application/Json"; if (!IFast.IsExists(name)) { dic.Add("success", false); dic.Add("error", "接口不存在"); await context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8).ConfigureAwait(false); } else if (dbKey == "") { dic.Add("success", false); dic.Add("error", string.Format("map id {0}的db没有配置", name)); await context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8).ConfigureAwait(false); } else if (IFast.IsExists(name)) { var param = new List <DbParameter>(); foreach (var item in IFast.MapParam(name)) { var checkKey = IFast.MapCheck(name, item); var existsKey = IFast.MapExists(name, item); var tempParam = DbProviderFactories.GetFactory(IFast.MapDb(name), IsResource, dbFile).CreateParameter(); tempParam.ParameterName = item; tempParam.Value = GetUrlParam(urlParam, item); param.Add(tempParam); if (!string.IsNullOrEmpty(IFast.MapRequired(name, item))) { if (!(string.Compare(IFast.MapRequired(name, item), "true", true) == 0 && !string.IsNullOrEmpty(tempParam.Value.ToStr()))) { dic.Add("success", false); dic.Add("error", string.Format("{0}不能为空", item)); param.Remove(tempParam); break; } } if (IFast.MapMaxlength(name, item).ToInt(0) != 0) { if (!(IFast.MapMaxlength(name, item).ToInt(0) >= tempParam.Value.ToStr().Length)) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1},最大长度{2}", item, tempParam.Value.ToStr(), IFast.MapMaxlength(name, item))); param.Remove(tempParam); break; } } if (!string.IsNullOrEmpty(existsKey)) { var existsListParam = new List <DbParameter>(); var existsParam = DbProviderFactories.GetFactory(IFast.MapDb(existsKey), IsResource, dbFile).CreateParameter(); existsParam.ParameterName = item; existsParam.Value = tempParam.Value; existsListParam.Add(existsParam); var checkData = IFast.Query(existsKey, existsListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) >= 1) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1}已存在", item, tempParam.Value)); param.Remove(tempParam); break; } } if (!string.IsNullOrEmpty(checkKey)) { var checkListParam = new List <DbParameter>(); var checkParam = DbProviderFactories.GetFactory(IFast.MapDb(checkKey), IsResource, dbFile).CreateParameter(); checkParam.ParameterName = item; checkParam.Value = GetUrlParam(urlParam, item); checkListParam.Add(checkParam); var checkData = IFast.Query(existsKey, checkListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) < 1) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1}不存在", item, tempParam.Value)); param.Remove(tempParam); break; } } if (string.Compare(IFast.MapDate(name, item).ToStr(), "true", true) == 0) { if (!BaseRegular.IsDate(tempParam.Value.ToStr())) { dic.Add("success", false); dic.Add("error", string.Format("{0}:{1},不是日期类型", item, tempParam.Value)); param.Remove(tempParam); break; } tempParam.Value = tempParam.Value.ToDate(); tempParam.DbType = System.Data.DbType.DateTime; } if (tempParam.Value.ToStr() == "") { param.Remove(tempParam); } } using (var db = new DataContext(dbKey)) { var tempParam = param.ToArray(); var sql = MapXml.GetMapSql(name, ref tempParam, db, dbKey); if (dic.Count > 0) { await context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8).ConfigureAwait(false); } else if (string.Compare(IFast.MapType(name).ToStr(), AppConfig.PageAll, true) == 0 || string.Compare(IFast.MapType(name).ToStr(), AppConfig.Page, true) == 0) { success = true; var pageSize = GetUrlParam(urlParam, "PageSize"); var pageId = GetUrlParam(urlParam, "PageId"); var page = new PageModel(); page.PageSize = pageSize.ToInt(0) == 0 ? 10 : pageSize.ToInt(0); page.PageId = pageId.ToInt(0) == 0 ? 1 : pageId.ToInt(0); pageInfo = db.GetPageSql(page, sql, tempParam).PageResult; if (IFast.MapView(name).ToStr() == "") { dic.Add("data", pageInfo.list); dic.Add("page", pageInfo.pModel); } } else if (string.Compare(IFast.MapType(name).ToStr(), AppConfig.All, true) == 0) { success = true; data = db.ExecuteSqlList(sql, tempParam, false).DicList; dic.Add("data", data); } else if (string.Compare(IFast.MapType(name).ToStr(), AppConfig.Write, true) == 0 && param.Count > 0) { var result = db.ExecuteSqlList(sql, tempParam, false).writeReturn; if (result.IsSuccess) { success = true; } else { success = false; dic.Add("error", result.Message); } } else { if (param.Count > 0) { success = true; data = db.ExecuteSqlList(sql, tempParam, false).DicList; dic.Add("data", data); } else { success = false; } } } dic.Add("success", success); await context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8).ConfigureAwait(false); } }
/// <summary> /// 获取配置实体 /// </summary> /// <param name="key"></param> /// <returns></returns> public static ConfigModel Get(string key = null, string projectName = null, string dbFile = "db.json") { var list = new List <ConfigModel>(); var item = new ConfigModel(); var cacheKey = "FastData.Core.Config"; if (DbCache.Exists(CacheType.Web, cacheKey)) { list = DbCache.Get <List <ConfigModel> >(CacheType.Web, cacheKey); } else if (projectName != null) { var assembly = Assembly.Load(projectName); using (var resource = assembly.GetManifestResourceStream(string.Format("{0}.{1}", projectName, dbFile))) { if (resource != null) { using (var reader = new StreamReader(resource)) { var content = reader.ReadToEnd(); list = BaseJson.JsonToList <ConfigModel>(BaseJson.ModelToJson(BaseJson.JsonToDic(content).GetValue("DataConfig"))); list.ForEach(a => { a.IsUpdateCache = false; }); DbCache.Set <List <ConfigModel> >(CacheType.Web, cacheKey, list); } } else { list = BaseConfig.GetListValue <ConfigModel>(AppSettingKey.Config, dbFile); DbCache.Set <List <ConfigModel> >(CacheType.Web, cacheKey, list); } } } else { list = BaseConfig.GetListValue <ConfigModel>(AppSettingKey.Config, dbFile); DbCache.Set <List <ConfigModel> >(CacheType.Web, cacheKey, list); } if (string.IsNullOrEmpty(key)) { item = list[0]; } else { item = list.Find(a => a.Key.ToLower() == key.ToLower()); } if (item.DesignModel == "") { item.DesignModel = Config.DbFirst; } if (item.SqlErrorType == "") { item.SqlErrorType = SqlErrorType.File; } if (item.CacheType == "") { item.CacheType = CacheType.Web; } item.IsPropertyCache = true; item.DbType = item.DbType.ToLower(); if (projectName != null) { item.IsUpdateCache = false; } return(item); }
public async Task ContentAsync(HttpContext context, IFastRepository IFast) { var urlParam = HttpUtility.UrlDecode(GetUrlParam(context)); var isSuccess = true; var dic = new Dictionary <string, object>(); var stopwatch = new Stopwatch(); stopwatch.Start(); context.Response.ContentType = "application/Json"; var name = context.Request.Path.Value.ToStr().Substring(1, context.Request.Path.Value.ToStr().Length - 1).ToLower(); if (IFast.IsExists(name)) { var data = new List <Dictionary <string, object> >(); var param = new List <DbParameter>(); foreach (var item in IFast.MapParam(name)) { var checkKey = IFast.MapCheckMap(name, item); var existsKey = IFast.MapExistsMap(name, item); var tempParam = DbProviderFactories.GetFactory(IFast.MapDb(name)).CreateParameter(); tempParam.ParameterName = item; tempParam.Value = GetUrlParam(urlParam, item); param.Add(tempParam); if (!string.IsNullOrEmpty(IFast.MapRequired(name, item))) { if (!(IFast.MapRequired(name, item).ToLower() == "true" && !string.IsNullOrEmpty(tempParam.Value.ToStr()))) { dic.Add("error", string.Format("{0}不能为空", item)); param.Remove(tempParam); break; } } if (IFast.MapMaxlength(name, item).ToInt(0) != 0) { if (!(IFast.MapMaxlength(name, item).ToInt(0) >= tempParam.Value.ToStr().Length)) { dic.Add("error", string.Format("{0}:{1},最大长度{2}", item, tempParam.Value.ToStr(), IFast.MapMaxlength(name, item))); param.Remove(tempParam); break; } } if (!string.IsNullOrEmpty(existsKey)) { var existsListParam = new List <DbParameter>(); var existsParam = DbProviderFactories.GetFactory(IFast.MapDb(existsKey)).CreateParameter(); existsParam.ParameterName = item; existsParam.Value = tempParam.Value; existsListParam.Add(existsParam); var checkData = IFast.Query(existsKey, existsListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) >= 1) { dic.Add("error", string.Format("{0}:{1}已存在", item, tempParam.Value)); param.Remove(tempParam); break; } } if (!string.IsNullOrEmpty(checkKey)) { var checkListParam = new List <DbParameter>(); var checkParam = DbProviderFactories.GetFactory(IFast.MapDb(checkKey)).CreateParameter(); checkParam.ParameterName = item; checkParam.Value = GetUrlParam(urlParam, item); checkListParam.Add(checkParam); var checkData = IFast.Query(existsKey, checkListParam.ToArray())?.First() ?? new Dictionary <string, object>(); if (checkData.GetValue("count").ToStr().ToInt(0) < 1) { dic.Add("error", string.Format("{0}:{1}不存在", item, tempParam.Value)); param.Remove(tempParam); break; } } if (IFast.MapDate(name, item).ToLower() == "true") { if (!BaseRegular.IsDate(tempParam.Value.ToStr())) { dic.Add("error", string.Format("{0}:{1},不是日期类型", item, tempParam.Value)); param.Remove(tempParam); break; } tempParam.Value = tempParam.Value.ToDate(); tempParam.DbType = System.Data.DbType.DateTime; } if (tempParam.Value.ToStr() == "") { param.Remove(tempParam); } } if (IFast.MapType(name).ToLower() == AppConfig.PageAll && dic.Count == 0) { var pageSize = GetUrlParam(urlParam, "PageSize"); var pageId = GetUrlParam(urlParam, "PageId"); isSuccess = true; var page = new PageModel(); page.PageSize = pageSize.ToInt(0) == 0 ? 10 : pageSize.ToInt(0); page.PageId = pageId.ToInt(0) == 0 ? 1 : pageId.ToInt(0); var info = IFast.QueryPage(page, name, param.ToArray()); dic.Add("data", info.list); dic.Add("page", info.pModel); } else if (IFast.MapType(name).ToLower() == AppConfig.Page && param.Count > 0) { var pageSize = GetUrlParam(urlParam, "PageSize"); var pageId = GetUrlParam(urlParam, "PageId"); isSuccess = true; var page = new PageModel(); page.PageSize = pageSize.ToInt(0) == 0 ? 10 : pageSize.ToInt(0); page.PageId = pageId.ToInt(0) == 0 ? 1 : pageId.ToInt(0); var info = IFast.QueryPage(page, name, param.ToArray()); dic.Add("data", info.list); dic.Add("page", info.pModel); } else if (IFast.MapType(name).ToLower() == AppConfig.All && dic.Count == 0) { isSuccess = true; data = IFast.Query(name, param.ToArray()); dic.Add("data", data); } else if (IFast.MapType(name).ToLower() == AppConfig.Write && param.Count > 0) { var result = IFast.Write(name, param.ToArray()); if (result.IsSuccess) { isSuccess = true; } else { isSuccess = false; dic.Add("error", result.Message); } } else { if (param.Count > 0) { isSuccess = true; data = IFast.Query(name, param.ToArray()); dic.Add("data", data); } else { isSuccess = false; } } } else { isSuccess = false; dic.Add("error", "接口不存在"); } dic.Add("isSuccess", isSuccess); context.Response.StatusCode = 200; await context.Response.WriteAsync(BaseJson.ModelToJson(dic), Encoding.UTF8).ConfigureAwait(false); }