public ActionResult Index(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, _wxSetting.Token)) { return(Content("参数错误!")); } #region 打包 PostModel 信息 postModel.Token = _wxSetting.Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = _wxSetting.EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = _wxSetting.WeixinAppId; //根据自己后台的设置保持一致(必须提供) #endregion try { var messageHandler = new CustomMessageHandler(RequestHelper.Request().GetRequestMemoryStream(), postModel, 10); messageHandler.Execute(); //执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(Content(messageHandler.ResponseDocument.ToString())); } catch (Exception ex) { LogNHelper.Exception(ex); return(Content("")); } }
/// <summary> /// 参数转为对象T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> public T GetPostObject <T>(string name = "") { string json; try { if (string.IsNullOrEmpty(name)) { if (!_bodyJson.IsEmpty()) { return(_bodyJson.ToObject <T>()); } } else { json = GetPostString(name); return(json.ToObject <T>()); } } catch (Exception ex) { LogNHelper.Exception(ex); } return(default(T)); }
public string UpdatePwd(string uname, string oldPwd, string newPwd) { try { string encodePwd = CEncoder.Encode(oldPwd); using (var sql = SugarDbContext.GetInstance()) { var id = sql.Queryable <Opers>().Where(s => s.userName == uname && s.password == encodePwd) .Select(s => s.Id).First(); if (id == 0) { return("原始密码错误!!!"); } string newEncodePwd = CEncoder.Encode(newPwd); sql.Updateable <Opers>().UpdateColumns(s => new Opers() { password = newEncodePwd }) .Where(s => s.Id == id).ExecuteCommand(); } } catch (Exception ex) { LogNHelper.Exception(ex); return("密码修改失败!!!"); } return(string.Empty); }
/// <summary> /// 开始称重 /// </summary> /// <returns></returns> public string SaveBatchInfo(Batches dto) { dto.originalPlace = string.Empty; dto.istrace = false; dto.upload = false; dto.weighingBeginTime = DateTime.Now; dto.weighingFinishedTime = TimeHelper.GetMinDateTime(); try { var stime = new DateTime(dto.weighingBeginTime.Year, dto.weighingBeginTime.Month, dto.weighingBeginTime.Day); using (var sql = SugarDbContext.GetInstance()) { int sort = sql.Queryable <Batches>().Where(s => s.weighingBeginTime > stime) .OrderBy(s => s.sort, OrderByType.Desc).Select(s => s.sort).First(); sort += 1; dto.sort = sort; string sortNum = sort.ToString().PadLeft(2, '0'); dto.batchId = dto.yearNum + "-" + sortNum; sql.Insertable(dto).ExecuteCommand(); } return(dto.batchId); } catch (Exception e) { LogNHelper.Exception(e); } return(string.Empty); }
/// <summary> /// 窗口数据初始化 /// </summary> /// <returns></returns> public WeightInitDto GetInitData() { var model = new WeightInitDto(); try { var nowTime = DateTime.Now.AddDays(-1); using (var sql = SugarDbContext.GetInstance()) { model.BatchInfo = sql.Queryable <Batches>().Where(s => s.weighingBeginTime > nowTime && s.flag == false).First(); model.Products = sql.Queryable <AnimalTypes>().Where(s => s.price > 0).ToList(); var param = sql.Queryable <Params>().OrderBy(s => s.factoryId).First(); if (param != null) { model.HookCount = param.hookCount; model.HooksWeight = param.hooksWeight; } } } catch (Exception ex) { LogNHelper.Exception(ex); return(null); } return(model); }
/// <summary> /// 获取内网IP /// </summary> /// <returns></returns> public static string GetLanIp() { try { //foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName())) //{ // if (hostAddress.AddressFamily == AddressFamily.InterNetwork) // { // return hostAddress.ToString(); // } //} var nets = NetworkInterface.GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()).SelectMany(p => p.UnicastAddresses) .Where(p => p.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !System.Net.IPAddress.IsLoopback(p.Address)) .ToList(); if (nets.Count > 0) { string[] ip = nets.Where(s => s.IsDnsEligible).Select(s => s.Address.ToString()).ToArray(); return(string.Join(',', ip)); } } catch (Exception ex) { LogNHelper.Exception(ex); } return(string.Empty); }
private static string IncludeDirectory = "Template/include"; //包含文件 /// <summary> /// 模板生成 /// </summary> /// <param name="templateType">模板类型,1-首页,2-栏目,3-内容页,4-单页</param> /// <param name="templateName">模板文件名称</param> /// <param name="templateContent">模板内容</param> public static void Create(int templateType, string templateName, string templateContent) { try { switch (templateType) { case 1: CreateHome(templateName, templateContent); break; case 2: CreateChannel(templateName, templateContent); break; case 3: CreateContent(templateName, templateContent); break; case 4: // CreateContent(templateName, templateContent); break; case 5: CreateInclude(templateName, templateContent); break; default: break; } }catch (Exception ex) { LogNHelper.Exception(ex); } }
public static string CreateVideo(string html) { try { var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); // var htmlBody = htmlDoc.DocumentNode.SelectNodes("//body"); var videoNodes = htmlDoc.DocumentNode.SelectNodes("//img[@class='easycms-player']"); foreach (var node in videoNodes) { string videoUrl = node.Attributes["playurl"].Value; string videoPlayer = $"<embed src=\"/plugins/ckplayer/ckplayer.swf\" flashvars =\"video={videoUrl}\" quality=\"high\" width = \"400\" height =\"400\" align =\"middle\" allowScriptAccess =\"always\" allowFullscreen = \"true\" type = \"application/x-shockwave-flash\"></embed>"; HtmlNode newChild = HtmlNode.CreateNode(videoPlayer); node.ParentNode.InsertAfter(newChild, node); //node.ReplaceChild(newChild, node); node.Remove(); } return(htmlDoc.DocumentNode.InnerHtml);; } catch (Exception ex) { LogNHelper.Exception(ex); } return(html); }
/// <summary> /// 称重数据插入本地数据 /// </summary> /// <param name="dto"></param> /// <returns></returns> public WeightGridDto InsertWeightGrid(WeightGridDto dto) { var model = new WeightGridDto(); try { using (var sql = SqliteDbContext.GetInstance()) { //获取上一条未提交到服务器的数据 var localLastWeight = sql.Queryable <WeightGridDto>().Where(s => s.BatchId == dto.BatchId && s.Uploadflag == 0) .OrderBy(s => s.WeightTime, OrderByType.Desc).First(); //插入本条数据 sql.Insertable(dto).ExecuteCommand(); if (localLastWeight != null) { model = localLastWeight; } } return(model); } catch (Exception e) { LogNHelper.Exception(e); } return(null); }
public Loginer Login(string uname, string pwd) { Loginer userer = null; try { using (var sql = SugarDbContext.GetInstance()) { var user = sql.Queryable <Opers>().Where(s => s.userName == uname && s.password == pwd) .First(); if (user == null) { return(null); } userer = new Loginer(); //存储登录用户信息 userer.Account = user.userName; userer.AccountName = user.operName; userer.LoginTime = DateTime.Now; } } catch (Exception e) { LogNHelper.Exception(e); } return(userer); }
/// <summary> ///异常处理 /// </summary> /// <param name="context"></param> /// <param name="exception"></param> /// <returns></returns> private static async Task HandleExceptionAsync(HttpContext context, System.Exception exception) { if (exception == null) { return; } LogNHelper.Exception(exception); await WriteExceptionAsync(context, exception).ConfigureAwait(false); }
public static string CreateVideo(string html) { try { var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); var bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body"); var videoNodes = bodyNode.SelectNodes("//img[@class='easycms-player']"); Dictionary<string, string> playList = new Dictionary<string, string>(); byte needPlayer = 0; foreach (var node in videoNodes) { string videoUrl = node.Attributes["playurl"].Value; string videoId = node.Attributes["id"].Value; string player= node.Attributes["player"].Value; string videoPlayer = ""; if (player == "h5") { videoPlayer = H5Player(videoId); playList.Add(videoId, videoUrl); needPlayer = 1; } else { needPlayer = 1; videoPlayer = FlashPlayer(videoUrl); } HtmlNode newChild = HtmlNode.CreateNode(videoPlayer); node.ParentNode.InsertAfter(newChild, node); //node.ReplaceChild(newChild, node); node.Remove(); } //获取ckplayerjs引用 if (needPlayer == 1) { HtmlNode CkPlayerNode = HtmlNode.CreateNode(CkPlayerJs()); bodyNode.AppendChild(CkPlayerNode); //如果是h5播放器,需要添加额外控制脚本 if (playList.Count > 0) { var h5PlayerScript = H5PlayerJs(playList); HtmlNode h5PlayerJsNode = HtmlNode.CreateNode(h5PlayerScript); bodyNode.AppendChild(h5PlayerJsNode); } } return htmlDoc.DocumentNode.InnerHtml; ; } catch(Exception ex) { LogNHelper.Exception(ex); } return html; }
/// <summary> /// 返回渲染后的模板文件 /// </summary> /// <param name="content"></param> /// <param name="template"></param> /// <returns></returns> public void GenerateHomeHtml() { try { var templateModel = TemplateManagerCache.GetHomeTemplate(); if (templateModel.id == 0) { throw new Exception("找不到模板"); } //加载模板 //this.LoadTemplate(templateModel.template_content); string templateFile = Path.Combine(GlobalParamsDto.WebRoot, templateModel.template_file); this.Document = new TemplateDocument(templateModel.template_content, GlobalParamsDto.WebRoot, templateFile); this.Document.Variables.SetValue("this", this); //设置顶部导航条数据 var navigations = _generateContentApp.GetChannelTree(); this.Document.Variables.SetValue("navigations", navigations); //获取栏目文章模板 ElementCollection <Template> templates = this.Document.GetChildTemplatesByName("channels"); foreach (Template template in templates) { string total = template.Attributes.GetValue("total", "10"); //根据模板块里定义的type属性条件取得新闻数据 var data = _generateContentApp.GetContentSummary(template.Attributes.GetValue("type"), 1, int.Parse(total)); //设置变量newsdata的值 template.Variables.SetValue("contents", data); //取得模板块下Id为newslist的标签(也即是在cnblogs_newsdata.html文件中定义的foreach标签) //Tag tag = template.GetChildTagById("newslist"); //if (tag is ForEachTag) //{ // //如果标签为foreach标签则设置其BeforeRender事件用于设置变量表达式{$:#.news.url}的值 // tag.BeforeRender += new System.ComponentModel.CancelEventHandler(Tag_BeforeRender); //} } string contentFilePath = Path.Combine(GlobalParamsDto.WebRoot, "index.html"); using (var filestream = new FileStream(contentFilePath, FileMode.Create, FileAccess.ReadWrite)) { string renderHtml = this.Document.GetRenderText(); using (StreamWriter writer = new StreamWriter(filestream, Encoding.UTF8)) { writer.WriteLine(renderHtml); writer.Flush(); } } } catch (Exception ex) { LogNHelper.Exception(ex); } }
/// <summary> /// 错误处理函数 /// </summary> void comPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { if (Error != null) { Error(sender, e); } else { LogNHelper.Exception(e.ToString()); } }
public void ConfigureContainer(ContainerBuilder builder) { try { builder.RegisterModule(new AtlassAutofacDI()); } catch (Exception e) { LogNHelper.Exception(e); } }
public void ConfigureContainer(ContainerBuilder builder) { try { //builder.RegisterModule(new AutofacModule()); builder.RegisterModule(new AutofacExt()); } catch (Exception e) { LogNHelper.Exception(e); } }
/// <summary> /// 未处理异常处理 /// </summary> /// <param name="filterContext"></param> protected override void OnException(ExceptionContext filterContext) { //if (!filterContext.ExceptionHandled && filterContext.Exception is ArgumentOutOfRangeException) if (!filterContext.ExceptionHandled) { //filterContext.Result = new RedirectResult("~/Error.htm"); LogNHelper.Exception(filterContext.Exception); filterContext.ExceptionHandled = true; } //base.OnException(filterContext); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); //nlog日志配置文件 env.ConfigureNLog("configs/nlog.config"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller=DeviceData}/{action=Index}/{id?}"); }); #region 解决Ubuntu Nginx 代理不能获取IP问题 //app.UseForwardedHeaders(new ForwardedHeadersOptions //{ // ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto //}); #endregion //扩展HttpContext app.UseStaticHttpContext(); //应用程序启动后 appLifetime.ApplicationStarted.Register(() => { try { GlobalParamsDto.WebRoot = env.WebRootPath; SugarDbConn.DbConnectStr = this.Configuration.GetSection("DbConn:mysqlConn").Value; //为数据库连接字符串赋值 GlobalParamsDto.RpcUname = this.Configuration.GetSection("RpcUser:Username").Value; GlobalParamsDto.RpcPwd = this.Configuration.GetSection("RpcUser:Password").Value; } catch (Exception e) { LogNHelper.Exception(e); } }); }
public JsonResult GetData() { var data = new DataGridEx(); try { data.list = _menuApp.GetMenuList(); } catch (Exception ex) { LogNHelper.Exception(ex); } return(JsonEx(data)); }
public ActionResult Loginon(LoginDto loginModel) { if (string.IsNullOrEmpty(loginModel.uname)) { ModelState.AddModelError("err", "用户名不能为空"); } if (string.IsNullOrEmpty(loginModel.pwd)) { ModelState.AddModelError("err", "密码不能为空"); } try { var user = _userApp.LoginValidate(loginModel.uname.Trim(), loginModel.pwd.Trim()); var loginUserDto = new LoginUserDto(); if (user != null) { loginUserDto.Id = user.id; loginUserDto.AccountName = user.account_name; loginUserDto.RealName = user.real_name; loginUserDto.IsSuper = user.is_super; loginUserDto.City = user.city; loginUserDto.County = user.county; loginUserDto.UserLevel = user.user_level; //if (user.account_name.ToLower() == "admin") //{ // loginUserDto.IsSuper = true; //user.IsSuper; //} //else //{ // loginUserDto.IsSuper = user.is_super; //user.IsSuper; //} loginUserDto.SysRoleId = user.sys_role_id; //设置cookie // FormsAuthentication.SetAuthCookie(loginUserDto.AccountName, false); string claimstr = loginUserDto.ToJson(); CookieHelper.WriteLoginCookie(claimstr); return(Redirect("/Home")); } ModelState.AddModelError("err", "用户名或密码错误"); } catch (Exception e) { LogNHelper.Exception(e); ModelState.AddModelError("err", "登录异常"); } return(View("Index", loginModel)); }
/// <summary> /// 返回渲染后的模板文件 /// </summary> /// <param name="content"></param> /// <param name="template"></param> /// <returns></returns> public (bool genStatus, string contentHtml) GenerateContentHtml(ContentModel content, cms_template template) { try { this.LoadTemplate(template.template_content); this.InitPageTemplate(content); return(true, this.Document.GetRenderText()); } catch (Exception ex) { LogNHelper.Exception(ex); } return(false, ""); }
public JsonResult GetData(DataGridEx param) { var data = new DataGridEx(); try { data = _roleApp.GetRoleList(param); } catch (Exception ex) { LogNHelper.Exception(ex); } return(JsonEx(data)); }
/// <summary> /// cpu使用率 /// </summary> /// <returns></returns> public string GetCPURate() { //string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage"); //string cpuRate = output.Replace("LoadPercentage", string.Empty).Trim(); try { //ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor"); //var cpuTimes = searcher.Get() // .Cast<ManagementObject>() // .Select(mo => new // { // Name = mo["Name"], // Usage = mo["PercentProcessorTime"] // }).ToList(); //var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage); //var cpuUsage = query.SingleOrDefault(); //if (cpuUsage == null) //{ // return "0"; //} //return cpuUsage.ToString() + "%"; var startTime = DateTime.UtcNow; var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var stopWatch = new Stopwatch(); // Start watching CPU stopWatch.Start(); // Meansure something else, such as .Net Core Middleware Thread.Sleep(100); // Stop watching to meansure stopWatch.Stop(); var endTime = DateTime.UtcNow; var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime; var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds; var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); var cpuUsagePercentage = cpuUsageTotal * 100; return(cpuUsagePercentage.ToString()); } catch (Exception ex) { LogNHelper.Exception(ex); } return(""); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //依赖注入 try { AutofacConfig.ConfigureContainer(); } catch (Exception ex) { LogNHelper.Exception("IOC依赖注入失败" + ex.Message); } }
public override void OnException(ExceptionContext context) { var ex = context.Exception; LogNHelper.Exception(ex); var result = new { statusCode = 300, msg = "服务内部异常,请联系管理员" }; context.Result = new ContentResult { Content = result.ToJson(), StatusCode = StatusCodes.Status200OK, ContentType = "text/html;charset=utf-8" }; context.ExceptionHandled = true; }
public void OnException(ExceptionContext context) { if (context.ExceptionHandled == false) { LogNHelper.Exception(context.Exception); var result = new { statusCode = 300, msg = "服务内部异常,请联系管理员" }; context.Result = new ContentResult { Content = result.ToJson(), StatusCode = StatusCodes.Status200OK, ContentType = "text/html;charset=utf-8" }; } context.ExceptionHandled = true; }
public void OnException(ExceptionContext context) { if (context.ExceptionHandled == false) { LogNHelper.Exception(context.Exception); var result = new { status = false, msg = "System error!", Exception = context.Exception }; context.Result = new ContentResult { Content = JsonConvert.SerializeObject(result), StatusCode = StatusCodes.Status500InternalServerError, ContentType = "text/html;charset=utf-8" }; } context.ExceptionHandled = true; //异常已处理了 }
/// <summary> /// 加载模板文件,生成模板内容 /// </summary> /// <param name="contentId"></param> public void CreateHtml(int contentId) { try { var sqlDb = FreesqlDbInstance.GetInstance(); var content = sqlDb.Select <cms_content>().Where(s => s.id == contentId).First(); if (content == null) { return; } string contentFolder = $@"static/content/{content.channel_id}"; string contentFile = $@"static/content/{content.channel_id}/{ content.id}.html"; string contentFolderPath = Path.Combine(GlobalParamsDto.WebRoot, contentFolder); string contentFilePath = Path.Combine(GlobalParamsDto.WebRoot, contentFile); string templatePath = Path.Combine(GlobalParamsDto.WebRoot, "Template/article.html"); if (!File.Exists(templatePath)) { LogNHelper.Exception("模板数据不存在"); return; } if (!Directory.Exists(contentFolderPath)) { Directory.CreateDirectory(contentFolderPath); } //加载模板 //this.LoadTemplateFile(templatePath); //this.InitPageTemplate(content); //this.Document = new TemplateDocument(templatePath, fileName); using (var filestream = new FileStream(contentFilePath, FileMode.Create, FileAccess.ReadWrite)) { string renderHtml = this.Document.GetRenderText(); using (StreamWriter writer = new StreamWriter(filestream, Encoding.UTF8)) { writer.WriteLine(renderHtml); writer.Flush(); } } } catch (Exception ex) { LogNHelper.Exception(ex); } }
public string GetOSRunTime() { string runTime = string.Empty; try { string output = ShellHelper.Bash("uptime -s"); output = output.Trim(); runTime = TimeHelper.FormatTime((DateTime.Now - output.ToDate()).TotalMilliseconds.ToString().Split('.')[0].ToInt64()); } catch (Exception ex) { LogNHelper.Exception(ex); } return(runTime); }
/// <summary> /// 撤销最新一条未提交的数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public bool DelLocalWeightById(string id) { try { using (var sql = SqliteDbContext.GetInstance()) { sql.Deleteable <WeightGridDto>().Where(s => s.Id == id).ExecuteCommand(); } return(true); } catch (Exception e) { LogNHelper.Exception(e); } return(false); }