//--------------------------------------------- // 公有方法 //--------------------------------------------- /// <summary> /// 初始化表单。访问权限验证;生成工具栏按钮;请在OnInit事件中调用。 /// </summary> /// <param name="form">页面中的表单</param> /// <param name="viewPower">查看权限</param> /// <param name="editPower">编辑权限</param> /// <param name="newPower">新建权限</param> /// <param name="toolbar">工具栏。按钮将在该工具栏中生成。若为空,则尝试在表单第一个工具栏中插入按钮。</param> /// <param name="relayoutToolbar">是否重新布局工具栏。为true的话将工具栏上的原控件移到右侧。</param> public void InitForm(FormBase form, PowerType viewPower, PowerType editPower, PowerType newPower, Toolbar toolbar = null, bool relayoutToolbar = true) { // 检测页面访问权限 switch (this.Mode) { case PageMode.View: Common.CheckPagePower(viewPower); break; case PageMode.New: Common.CheckPagePower(newPower); break; case PageMode.Edit: Common.CheckPagePower(editPower); break; } // 工具栏 this.frm = form; if (toolbar == null) { if (form.Toolbars.Count > 0) { toolbar = form.Toolbars[0]; } else { toolbar = new Toolbar(); form.Toolbars.Add(toolbar); } } // 工具栏控件 InitToolbar(toolbar, relayoutToolbar); this.ShowBtnClose = Asp.GetQueryBoolValue("showBtnClose") ?? false; }
public object Clone() { var av = new AttVal(); if (Next != null) { av.Next = (AttVal)Next.Clone(); } if (Attribute != null) { av.Attribute = Attribute; } if (Val != null) { av.Val = Val; } av.Delim = Delim; if (Asp != null) { av.Asp = (Node)Asp.Clone(); } if (Php != null) { av.Php = (Node)Php.Clone(); } av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(this); return(av); }
/// <summary>移动端登录(openId存在库中,默认登录)</summary> /// <param name="userToken">微信平台校验码</param> public static bool LoginMobileByOpenId(string openId) { try { var user = User.GetDetail(null, null, null, openId); if (user != null) { OAuthUserInfo userInfo = Asp.GetSession("OAuthUserInfo") as OAuthUserInfo; if (user.NickName.IsNullOrEmpty()) { user.NickName = userInfo.nickname; user.Save(); } if (user.Photo.IsNullOrEmpty()) { user.Photo = userInfo.headimgurl; user.Save(); } Logout();//有没有 注销 再登录 LoginSuccess(user); return(true); } } catch (Exception ex) { Logger.LogToDb(ex.Message); } return(false); }
public void Configure( IApplicationBuilder app, IWebHostEnvironment env, WebAppAndElmAppConfig webAppAndElmAppConfig, Func <DateTimeOffset> getDateTimeOffset, IHostApplicationLifetime appLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var state = new PublicAppState(webAppAndElmAppConfig: webAppAndElmAppConfig, getDateTimeOffset: getDateTimeOffset); appLifetime.ApplicationStopping.Register(() => { state.applicationStoppingCancellationTokenSource.Cancel(); _logger?.LogInformation("Public app noticed ApplicationStopping."); }); if (webAppAndElmAppConfig.WebAppConfiguration?.letsEncryptOptions != null) { app.UseFluffySpoonLetsEncryptChallengeApprovalMiddleware(); } state.ProcessEventTimeHasArrived(); app .Use(async(context, next) => await Asp.MiddlewareFromWebAppConfig(webAppAndElmAppConfig.WebAppConfiguration, context, next)) .Run(state.Run); }
public APIResult Up(string folder, string fileName) { var exts = new List <string> { ".jpg", ".png", ".gif", ".mp3", ".mp4", ".txt", ".md" }; var ext = fileName.GetFileExtension(); if (!exts.Contains(ext)) { return(new APIResult(false, "File deny", 13)); } // 构造存储路径 var url = GetUploadPath(folder, fileName); var path = Asp.MapPath(url); var fi = new FileInfo(path); if (!fi.Directory.Exists) { Directory.CreateDirectory(fi.Directory.FullName); } // 存储第一个文件 var files = Asp.Request.Form.Files; if (files.Count == 0) { return(new APIResult(false, "File doesn't exist", 11)); } using (var stream = File.Create(path)) files[0].CopyToAsync(stream); return(new APIResult(true, url)); }
public async Task Invoke(HttpContext context) { var path = context.Request.Path.Value; // 无 host 和 querystring。如:/res/icon/add.png var ext = path.GetFileExtension(); if (!Extensions.Contains(ext)) { await _next.Invoke(context); return; } // 原图路径校验 var rawPath = Asp.MapPath(path); if (!File.Exists(rawPath)) { //Asp.Error(404, "Not found"); // 因为 wwwroot 的原因,MapPath 出来的路径可能不对,就不做处理了 await _next.Invoke(context); return; } // 原图输出 var pathAndQuery = path + context.Request.QueryString; var mimeType = path.GetMimeType(); var w = Asp.GetQueryInt("w"); if (w == null) { Asp.WriteFile(rawPath, mimeType: mimeType); return; } // 缩略图参数 var h = Asp.GetQueryInt("h"); if (w > 1000) { w = 1000; } if (h != null && h > 1000) { h = 1000; } var key = pathAndQuery.ToLower().MD5(); // 缩略图缓存策略 var cachePath = Asp.MapPath(string.Format("/Caches/{0}.cache", key)); if (!File.Exists(cachePath)) { IO.PrepareDirectory(cachePath); var img = Painter.Thumbnail(rawPath, w.Value, h); img.Save(cachePath); img.Dispose(); } Asp.WriteFile(cachePath, mimeType: mimeType); }
// 保存并关闭 protected void btnSaveClose_Click(object sender, EventArgs e) { int id = Asp.GetQueryIntValue("id").Value; User item = DAL.User.Get(id); DAL.User.SetPassword(item, tbxPassword.Text.Trim()); PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference()); }
/// <summary>获取上传文件要保存的路径名</summary> public static string GetUploadFilePath(string folderName, string fileName) { string folder = string.Format("~/Files/{0}", folderName); fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_"); fileName = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmssfffffff"), fileName); return(Asp.ResolveUrl(string.Format("{0}/{1}", folder, fileName))); }
// 初始化 protected void Page_Load(object sender, EventArgs e) { string typeName = Request.QueryString["type"]; this.SimpleForm1.EntityTypeName = Asp.GetQueryString("type"); this.SimpleForm1.EntityID = Asp.GetQueryIntValue("id").Value; this.SimpleForm1.Mode = this.Mode; this.SimpleForm1.InitForm(); }
// 初始化 protected void Page_Load(object sender, EventArgs e) { string typeName = "App.DAL.Log"; // Request.QueryString["type"]; this.SimpleForm1.EntityTypeName = typeName; this.SimpleForm1.EntityID = Asp.GetQueryIntValue("id").Value; this.SimpleForm1.Mode = PageMode.View; this.SimpleForm1.InitForm(); }
// 清空数据 public override void NewData() { this.lblId.Text = "-1"; this.tbName.Text = ""; this.tbSeq.Text = "0"; this.tbRemark.Text = ""; int?parentId = Asp.GetQueryIntValue("parentid"); BindDDL(parentId, parentId); }
/// <summary>获取在线人数(15分钟内活动的用户),加了缓存</summary> public static int GetOnlineCount() { return((int)Asp.GetCacheData( "OnlineCount", DateTime.Now.AddMinutes(5), () => { DateTime lastDt = DateTime.Now.AddMinutes(-15); return Set.Where(o => o.UpdateDt > lastDt).Count(); })); }
/// <summary>获取公众号调用微信JS接口的临时票据(有效期7200秒,开发者必须在自己的服务全局缓存jsapi_ticket)(未测试)</summary> static string GetJsSdkTicket(string accessToken) { var dt = DateTime.Now.AddMinutes(60); return(Asp.GetCacheData <string>("WechatJSAPITicket", dt, () => { var url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", accessToken); var txt = HttpHelper.Get(url); return txt.ParseJObject()["ticket"].ToString(); })); }
public void FillKnowledge(CandidateViewModel candidate) { _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); Ionic.EnterText(candidate.Ionic.ToString()); Android.EnterText(candidate.Android.ToString()); Angular.EnterText(candidate.Angular.ToString()); Asp.EnterText(candidate.Asp.ToString()); Others.EnterText(candidate.Others); Photoshop.EnterText(candidate.Photoshop.ToString()); Illustrator.EnterText(candidate.Illustrator.ToString()); Html.EnterText(candidate.Html.ToString()); Jquery.EnterText(candidate.Jquery.ToString()); }
/// <summary>获取微信网页授权登录AccessToken</summary> /// <remarks> /// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 /// 网页授权流程分为四步: /// 1、引导用户进入授权页面同意授权,获取code /// 2、通过code换取网页授权access_token(与基础支持中的access_token不同) /// 3、如果需要,开发者可以刷新网页授权access_token,避免过期 /// 4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制) /// </remarks> public static OAuthGetTokenReply OAuthGetAccessToken(string code) { var key = "WechatWebAccessToken"; var dt = DateTime.Now.AddMinutes(60); return(Asp.GetCacheData <OAuthGetTokenReply>(key, dt, () => { var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", WechatConfig.OpenAppId, WechatConfig.OpenAppSecret, code ); var reply = HttpHelper.Get(url); return reply.ParseJson <OAuthGetTokenReply>(); })); }
// 注册在线用户(由于日志过于频繁且低价值,不记录到日志中去了) public static void RegisterOnlineUser(int userId) { var now = DateTime.Now; Online online = Set.Where(o => o.User.ID == userId).FirstOrDefault(); online = online ?? new Online(); online.UserID = userId; online.IP = Asp.GetClientIP(); online.LoginDt = now; online.UpdateDt = now; online.Save(false); // 记录本次更新时间 HttpContext.Current.Session[Common.SESSION_ONLINE_UPDATE_TIME] = now; }
// 新建数据 public override void NewData() { tbName.Text = ""; tbUrl.Text = ""; tbSeq.Text = "0"; tbIcon.Text = ""; tbRemark.Text = ""; chkOpen.Checked = false; // 图标列表, 上级菜单,权限下拉框 int?parentId = Asp.GetQueryIntValue("parentid"); BindDDLMenu(parentId, null); BindDDLPower(null); BindIcons(""); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int id = Asp.GetQueryIntValue("id").Value; var item = DAL.Article.Get(id); item.VisitCnt += 1; item.Save(); this.lblTitle.Text = item.Title; this.lblAuthor.Text = item.Author; this.lblPostDt.Text = item.PostDt.ToString("yyyy-MM-dd"); this.lblVisitCnt.Text = item.VisitCnt.ToText(); this.lblContent.Text = item.Body; this.rptImage.DataSource = item.Images; this.rptImage.DataBind(); } }
// 读取用户信息 private void LoadData() { int id = Asp.GetQueryIntValue("id").Value; User user = DAL.User.Get(id); if (user == null) { Alert.Show("参数错误!", String.Empty, ActiveWindow.GetHideReference()); return; } if (user.Name == "admin" && AuthHelper.GetIdentityName() != "admin") { Alert.Show("你无权编辑超级管理员!", String.Empty, ActiveWindow.GetHideReference()); return; } labUserName.Text = user.Name; labUserRealName.Text = user.RealName; }
/// <summary> /// 显示表单,请在页面首次初始化代码中调用 /// </summary> public void ShowForm() { // 新建 var mode = this.Mode; if (mode == PageMode.New) { NewData(); ShowButtons(true, true, true); return; } // 尝试获取实体 var id = Asp.GetQueryIntValue("id"); if (id == null) { return; } T item = GetData(id.Value); if (item == null) { Alert.Show("参数错误!", String.Empty, ActiveWindow.GetHideReference()); return; } // 显示表单数据 ShowData(item); // 查看或编辑 if (mode == PageMode.View) { ShowButtons(true, false, false); FormHelper.SetFormEditable(this.frm, false); } if (mode == PageMode.Edit) { ShowButtons(true, true, false); } }
public static DataResult LoginMobile(string mobile, string password, string verifyCode, string OS) { var result = new DataResult("false", "账户或密码错误", null, null); if (Asp.GetSession(Common.SESSION_VERIFYCODE) == null || verifyCode.ToLower() != Asp.GetSession(Common.SESSION_VERIFYCODE).ToString().ToLower()) { return(new DataResult("false", "验证码错误", null, null)); } else { // 校验账户和密码 var user = User.GetDetail(null, null, mobile, null); var userInfo = Asp.GetSession("OAuthUserInfo") as OAuthUserInfo; if (user == null) { result = new DataResult("false", "手机号码未在平台绑定", null, null); } else if (user != null && user.InUsed && PasswordHelper.ComparePasswords(user.Password, password)) { if (user.NickName.IsNullOrEmpty()) { user.NickName = userInfo.nickname; } if (user.Photo.IsNullOrEmpty()) { user.Photo = userInfo.headimgurl; } user.WechatOpenId = userInfo.openid; LoginSuccess(user); Logger.LogToDb("登录成功", LogLevel.Info, mobile, OS); result = new DataResult("true", "登录成功", null, null); } else { Logger.LogToDb("登录失败", LogLevel.Warn, mobile, OS); } } return(result); }
public static DataResult LoginByMsgCode(string mobile, string msgCode) { var result = new DataResult("false", "验证码错误", null, null); var vCode = VerifyCode.GetDetail(mobile); if (vCode == null || vCode.ExpireDt < DateTime.Now || vCode.Code != msgCode) { result = new DataResult("false", "验证码错误或过期", null, null); } else { var user = User.GetDetail(null, null, mobile, null); var userInfo = Asp.GetSession("OAuthUserInfo") as OAuthUserInfo; if (user == null) { result = new DataResult("false", "手机号码未在平台绑定", null, null); } else { if (user.NickName.IsNullOrEmpty()) { user.NickName = userInfo.nickname; } if (user.Photo.IsNullOrEmpty()) { user.Photo = userInfo.headimgurl; } if (user.WechatOpenId.IsNullOrEmpty()) { user.WechatOpenId = userInfo.openid; } LoginSuccess(user); Logger.LogToDb("登录成功", LogLevel.Info, mobile); result = new DataResult("true", "登录成功", null, null); } } return(result); }
public void ConfigureServices(IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); var config = serviceProvider.GetService <IConfiguration>(); var getDateTimeOffset = serviceProvider.GetService <Func <DateTimeOffset> >(); if (getDateTimeOffset == null) { getDateTimeOffset = () => DateTimeOffset.UtcNow; services.AddSingleton(getDateTimeOffset); } var webAppAndElmAppConfig = serviceProvider.GetService <WebAppAndElmAppConfig>(); if (webAppAndElmAppConfig == null) { throw new Exception("Missing reference to the web app config."); } { var letsEncryptOptions = webAppAndElmAppConfig.WebAppConfiguration?.letsEncryptOptions; if (letsEncryptOptions == null) { _logger.LogInformation("I did not find 'letsEncryptOptions' in the configuration. I continue without Let's Encrypt."); } else { _logger.LogInformation("I found 'letsEncryptOptions' in the configuration."); services.AddFluffySpoonLetsEncryptRenewalService(letsEncryptOptions); services.AddFluffySpoonLetsEncryptFileCertificatePersistence(); services.AddFluffySpoonLetsEncryptMemoryChallengePersistence(); } } Asp.ConfigureServices(services); }
/// <summary>处理文件资源</summary> public void HandleFileRes(string url) { // 文件扩展名及推断属性 this.FileExtension = url.GetFileExtension(); this.MimeType = IO.GetMimeType(this.FileExtension); this.Type = this.MimeType.Contains("image") ? ResType.Image : ResType.File; // 物理文件属性 if (url.IsSiteFile()) { try { var physicalPath = Asp.MapPath(url); var fi = new FileInfo(physicalPath); this.FileSize = fi.Length; this.FileMD5 = IO.GetFileMD5(physicalPath); } catch (Exception e) { UtilConfig.Log("GetFileInfoFail", e.Message); }; } }
public DataResult Login(string userName, string password, string verifyCode) { // 验证验证码 if (Asp.GetSession(Common.SESSION_VERIFYCODE) == null || verifyCode.ToLower() != Asp.GetSession(Common.SESSION_VERIFYCODE).ToString().ToLower()) { return(new DataResult("false", "验证码错误", null, null)); } // 校验账户和密码 var user = User.Get(name: userName); if (user != null && user.InUsed && PasswordHelper.ComparePasswords(user.Password, password)) { LoginSuccess(user); Logger.LogToDb("登录成功", LogLevel.Info, userName); return(new DataResult("true", "登录成功", null, null)); } else { Logger.LogToDb("登录失败", LogLevel.Warn, userName); return(new DataResult("false", "账户或密码错误", null, null)); } }
public DataResult LoginDefault(string code) { try { var userInfo = Asp.GetSession("OAuthUserInfo") as OAuthUserInfo; if (userInfo == null) { if (!code.IsNullOrEmpty()) { var oauthResult = OAuthApi.GetAccessToken(WechatHelper.AppID, WechatHelper.AppSecret, code); userInfo = OAuthApi.GetUserInfo(oauthResult.access_token, oauthResult.openid); Asp.SetSession("OAuthUserInfo", userInfo);//userToken只能使用一次 获取用户信息记录到session if (LoginMobileByOpenId(userInfo.openid)) { return(new DataResult("true", "登录成功", "WeChatScan.aspx", null)); } } else { return(new DataResult("false", "未绑定微信号", "Login.aspx", null)); } } else { if (LoginMobileByOpenId(userInfo.openid)) { return(new DataResult("true", "登录成功", "WeChatScan.aspx", null)); } } } catch (Exception e) { Logger.LogToDb(e.Message); } return(new DataResult("false", "未绑定微信号", "Login.aspx", null)); }
/// <summary>输出页面信息</summary> public static void WritePageInfo(string url) { Asp.Write(url); //Asp.Write(WebHelper.BuildBootstrapCss()); //Asp.Write(BuildPageInfo(url)); }
public DataResult BindTel(string mobile, string password, string msgCode, string inviterId) { var result = new DataResult("true", "绑定成功", null, null); var vCode = VerifyCode.GetDetail(mobile); if (vCode == null || vCode.ExpireDt < DateTime.Now) { result = new DataResult("false", "验证码已过期", null, null); } else if (vCode.Code != msgCode) { result = new DataResult("false", "验证码错误", null, null); } else { var user = App.DAL.User.Get(mobile: mobile); if (user != null) { result = new DataResult("false", "当前手机号码已被其他人使用", null, null); } else { //OAuthAccessTokenResult oauthResult = OAuthApi.GetAccessToken(WeChatHelper.AppID, WeChatHelper.AppSecret, userToken); //OAuthUserInfo userInfo = OAuthApi.GetUserInfo(oauthResult.access_token, oauthResult.openid); OAuthUserInfo userInfo = Asp.GetSession("OAuthUserInfo") as OAuthUserInfo; user = new User(); user.Name = mobile; user.Password = PasswordHelper.CreateDbPassword(password); user.NickName = userInfo.nickname; user.WechatOpenId = userInfo.openid; user.Photo = userInfo.headimgurl; user.Mobile = mobile; user.Phone = mobile; user.CreateDt = DateTime.Now; user.InUsed = true; user.Gender = userInfo.sex == 1 ? "男" : "女"; user.Roles = new List <RoleType>() { RoleType.Customer }; user.Save(); LoginSuccess(user); if (inviterId != "-1" && DESEncrypt.DecryptDES(inviterId) != inviterId)//这个解密失败,会返回传入的值 { inviterId = DESEncrypt.DecryptDES(inviterId); User inviter = User.Get(inviterId.ToInt32()); if (inviter != null) { //注册成功,才记录邀请记录 Invite invite = new Invite(); invite.InviterID = inviter.ID; invite.InviteeID = user.ID; invite.InviteeMobile = mobile; invite.Sts = InviteStatus.New; invite.Source = InviteSource.WeiXin; invite.CreateDt = DateTime.Now; invite.RegistDt = user.CreateDt; invite.Save(); result = new DataResult("true", "受邀,绑定成功", null, null); } } } } return(result); }
/// <summary>保存(含新增或修改逻辑)</summary> public virtual bool Save() { try { T item = (this.Mode == PageMode.New) ? AppContext.Current.Set <T>().Create() : GetData(Asp.GetQueryIntValue("id").Value); CollectData(ref item); var error = CheckData(item); if (!error.IsNullOrEmpty()) { UI.ShowAlert(error); return(false); } else { SaveData(item); return(true); } } catch (Exception ex) { UI.ShowAlert("保存失败。{0}", ex.Message); return(false); } }
public Fish GetFishByStr() { Fish fish = null; var regex = new Regex(@".*(?=:)"); var fishName = regex.Match(LoadStr); var name = fishName.Value; regex = new Regex(@"\d+"); var matches = regex.Matches(LoadStr); var sizeCf = Convert.ToSingle(matches[0].Value) / 100; var minDeep = Convert.ToInt32(matches[1].Value); var maxDeep = Convert.ToInt32(matches[2].Value); regex = new Regex(@"(?<=\[).*(?=\])"); var match = regex.Match(LoadStr); var luresList = match.Value; var lures = luresList.Split(','); HashSet <FishBait> baits = new HashSet <FishBait>(); foreach (var s in lures) { baits.Add(FishBait.GetFishBaitByName(s)); } switch (name) { case "Щука": fish = new Pike(minDeep, maxDeep, sizeCf, baits); break; case "Арктич. Голец": fish = new ArcticChar(minDeep, maxDeep, sizeCf, baits); break; case "Жерех": fish = new Asp(minDeep, maxDeep, sizeCf, baits); break; case "Лещ": fish = new Bream(minDeep, maxDeep, sizeCf, baits); break; case "Налим": fish = new Burbot(minDeep, maxDeep, sizeCf, baits); break; case "Голавль": fish = new Chub(minDeep, maxDeep, sizeCf, baits); break; case "Карась Зол": fish = new GoldCarp(minDeep, maxDeep, sizeCf, baits); break; case "Карась Сер": fish = new SilverCarp(minDeep, maxDeep, sizeCf, baits); break; case "Хариус": fish = new Grayling(minDeep, maxDeep, sizeCf, baits); break; case "Окунь": fish = new Perch(minDeep, maxDeep, sizeCf, baits); break; case "Горбуша": fish = new PinkSalmon(minDeep, maxDeep, sizeCf, baits); break; case "Плотва": fish = new Roach(minDeep, maxDeep, sizeCf, baits); break; case "Рыбец": fish = new Rybets(minDeep, maxDeep, sizeCf, baits); break; case "Сёмга": fish = new Salmon(minDeep, maxDeep, sizeCf, baits); break; case "Подлещик": fish = new Scavenger(minDeep, maxDeep, sizeCf, baits); break; case "Змееголов": fish = new SnakeHead(minDeep, maxDeep, sizeCf, baits); break; case "Линь": fish = new Tench(minDeep, maxDeep, sizeCf, baits); break; } return(fish); }