public void AddTest() { var bll = new BaseBLL<t_JobNews>(); var r1 = bll.Query(u => true).FirstOrDefault().Content; var bll2 = new BaseBLL<t_JobNews>(); var r2 = bll2.Query(u => true).FirstOrDefault().Content; Assert.AreEqual(true, r1 != r2); }
private void UC_JobNews_Load(object sender, EventArgs e) { //获取news BaseBLL<t_JobNews> newsBll = new BaseBLL<t_JobNews>(); var source = newsBll.Query(u => 1 == 1).OrderByDescending(u => u.Date).ToList(); this.dataGridView1.DataSource = source; Date.DataPropertyName = "Date"; Title.DataPropertyName = "Title"; ID.DataPropertyName = "ID"; }
private void btnLogin_Click(object sender, EventArgs e) { var bll = new BaseBLL<t_User>(); var user = bll.Query(u => u.User == this.tbxName.Text && u.Pwd == this.tbxPwd.Text).FirstOrDefault(); if (user != null) { Program.loginUserID = user.ID; this.Hide(); Form1 fm = new Form1(); fm.Show(); } }
public FormReg() { InitializeComponent(); var bll = new BaseBLL<t_Role>(); var source = bll.Query(u => true).ToList(); this.cmbRole.DataSource = source; this.cmbRole.DisplayMember = "RoleName"; this.cmbRole.ValueMember = "ID"; this.tbxPwd.PasswordChar = '*'; this.tbxRePwd.PasswordChar = '*'; this.StartPosition = FormStartPosition.CenterScreen; }
private void button1_Click(object sender, EventArgs e) { var con = Tools.CheckIllegalControls(this.tbxRePwd, this.tbxPwd, this.tbxName, this.cmbRole); if (con != null) { MessageBox.Show("该项不能为空"); con.Focus(); return; } if (this.tbxPwd.Text != this.tbxRePwd.Text) { MessageBox.Show("输入的密码不一样"); this.tbxRePwd.Focus(); return; } var bll = new BaseBLL<t_User>(); var urBll = new BaseBLL<t_UserRole>(); var user = new t_User() { ID = Guid.NewGuid(), Pwd = this.tbxPwd.Text, RoleID = new Guid(this.cmbRole.SelectedValue.ToString()), User = this.tbxName.Text }; var ur = new t_UserRole() { RoleID = user.RoleID, UserID = user.ID }; if (bll.Query(u => u.User == user.User).Any()) { MessageBox.Show("该用户名已被注册"); return; } if (bll.Add(user) && urBll.Add(ur)) { if (MessageBox.Show("注册成功", "", MessageBoxButtons.OK) == DialogResult.OK) { this.Close(); } } }
public string getCahe() { //BLL.Common.CacheData.GetAllUserInfo(true); //BLL.Common.CacheData.GetAllType(true); //BLL.Common.GetDataHelper.GetAllTag(); BLL.BaseBLL <BlogUser> user = new BaseBLL <BlogUser>(); //if (false) //{ // var list = user.GetList(t => true).ToList(); // for (int i = 0; i < list.Count(); i++) // { // var str = list[i].UserPass; // list[i].UserPass = str.MD5().MD5(); // user.Up(list[i], "UserPass"); // } // user.save(false); //} return("ok"); }
/// <summary> /// 获取现在是属于初赛还是半决赛还是决赛 /// </summary> /// <returns></returns> public ApiResult GetGetCompetition() { ApiResult apiResult = new ApiResult(); BaseBLL <competition_notice> competition_season_bll = new BaseBLL <competition_notice>(); var competition_season = competition_season_bll.Find(o => o.is_delete == 0 && o.is_open == 1); if (competition_season?.competition_season_id > 0) { DateTime now = DateTime.Now.Date; if (now <= competition_season.preliminaries_end_date) { apiResult.data = "初赛"; } else if (now >= competition_season.semifinals_start_date && now <= competition_season.semifinals_end_date) { apiResult.data = "半决赛"; } else if (now >= competition_season.final_start_date) { apiResult.data = "决赛"; } else { apiResult.data = "初赛"; } } else { return(new ApiResult() { success = false, message = "当前没有赛季" }); } apiResult.success = true; apiResult.message = "获取现在是属于初赛还是半决赛还是决赛"; return(apiResult); }
/// <summary> /// 生成公众号带参数的二维码 /// </summary> /// <param name="appid"></param> /// <param name="secret"></param> /// <param name="path"></param> /// <returns></returns> public static string CreateWeixinCode(string appid, string secret, string path) { BaseBLL <weixin> weixin_bll = new BaseBLL <weixin>(); var weixin = weixin_bll.Find(o => o.appid == appid && o.appsecret == secret); if (weixin == null) { return(null); } string access_token_time = Util.isNotNull(weixin.access_token_time) ? weixin.access_token_time.ToString() : ""; WeixinAPI api = new WeixinAPI(weixin.appid, weixin.appsecret, weixin.access_token, access_token_time); string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + api.AccessToken; string post_data = Newtonsoft.Json.JsonConvert.SerializeObject(new { expire_seconds = 604800, action_name = "QR_STR_SCENE", action_info = new { scene = new { scene_str = path } } }); string result = HttpHelper.HttpPost(url, post_data); JObject obj = JObject.Parse(result); if (Util.isNotNull(obj["url"]) && Util.isNotNull(obj["ticket"])) { string ticket = obj["ticket"].ToString(); return(api.GetWeixinCode(ticket)); } return(null); }
/// <summary> /// 删除 文章 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult Del(int?id) { var userinfo = BLLSession.UserInfoSessioin; List <BlogsDTO> blogs = new List <BlogsDTO>(); int isdelok = -1; if (null != id) { BLL.BaseBLL <BlogInfo> blogbll = new BaseBLL <BlogInfo>(); blogbll.Delete(new BlogInfo() { Id = (int)id }, true); isdelok = blogbll.save(false); List <SearchResult> list = new List <SearchResult>(); list.Add(new SearchResult() { id = (int)id }); SafetyWriteHelper <SearchResult> .logWrite(list, PanGuLuceneHelper.instance.Delete); } return(Content((isdelok > 0).ToString())); }
public void TestMethod_BatchInsert_T() { List <UserTestEntity> userEntities = new List <UserTestEntity>(); for (int i = 0; i < 100; i++) { UserTestEntity user = new UserTestEntity { Name = "小师弟", Age = 18, Sex = 1, Description = "测试实体插入", Mobile = "15890909090" }; user.Create(); userEntities.Add(user); } BaseBLL <UserTestEntity> bll = new BaseBLL <UserTestEntity>(); int res = bll.AddList(userEntities); Console.WriteLine("执行结果:{0}", res); }
public ApiResult AdviserLoginIn() { string user_name = HttpContext.Current.Request.Form["user_name"]; string password = HttpContext.Current.Request.Form["password"]; ApiResult apiResult = new ApiResult(); var checkResult = Util.CheckParameters( new Parameter { Value = user_name, Msg = "user_name 不能为空值" }, new Parameter { Value = password, Msg = "password 不能为空值" } ); if (!checkResult.OK) { apiResult.success = false; apiResult.status = ApiStatusCode.InvalidParam; apiResult.message = checkResult.Msg; return(apiResult); } BaseBLL <adviser> bll = new BaseBLL <adviser>(); var adviser = bll.Find(o => o.user_name == user_name && o.password == password); if (adviser?.adviser_id > 0) { apiResult.success = true; apiResult.message = "登陆成功"; apiResult.data = adviser; } else { apiResult.success = false; apiResult.message = "登陆失败"; } return(apiResult); }
public ApiPageResult GetAllNotices(DateTime?start = null, DateTime?end = null, int is_show = 1, int pageIndex = GloabManager.PAGEINDEX, int pageSize = GloabManager.PAGESIZE) { ApiPageResult apiPageResult = new ApiPageResult(); apiPageResult.pageIndex = pageIndex; apiPageResult.pageSize = pageSize; BaseBLL <user_notice> bll = new BaseBLL <user_notice>(); var list = bll.FindList <int>(notice => true); if (is_show == 0) { list = list.Where(o => o.publish_time <= DateTime.Now); } if (start.HasValue) { list = list.Where(notice => notice.update_time > start.Value && notice.update_time < (end ?? DateTime.Now)); } int count = list.Count(); var top_notice = list.Where(o => o.is_top == 1); list = list.OrderByDescending(notice => notice.update_time).Skip((pageIndex - 1) * pageSize).Take(pageSize); var result = list.Select(notice => new { notice.notice_id, notice.title, notice.content, notice.is_top, notice.publish_time, }); apiPageResult.success = true; apiPageResult.message = "获取所有通知"; apiPageResult.data = new { result, top_notice }; apiPageResult.totalCount = count; return(apiPageResult); }
public object SendYzmEmail(string email) { if (!ValidatorClass.Validator(email, CheckType.Email, null, false)) { return(new { Rcode = -1, Rmsg = "参数错误" }); } Random rand = new Random(); string errmsg = null; base_identifycode info = new base_identifycode { code = rand.Next(100000, 999999).ToString(), sendtime = DateTime.Now, endtime = DateTime.Now.AddMinutes(5), email = email }; bool success = BaseBLL.PutIdentifyCode(info, out errmsg); if (!success || !string.IsNullOrEmpty(errmsg)) { return new { Rcode = -1, Rmsg = "写入验证码出错" + errmsg } } ; string subject = Models.GlobalParameters.SmtpSignTitle + "验证邮件"; string content = string.Format("您的验证码为 {0} ,请勿轻易告诉他人!", info.code); NetClass.SmtpServer = Models.GlobalParameters.SmtpServer; NetClass.Account = Models.GlobalParameters.SmtpUser; NetClass.Passwd = Models.GlobalParameters.SmtpPass; NetClass.MailFrom = Models.GlobalParameters.SmtpMail; if (!NetClass.SendMail(email, subject, content, Models.GlobalParameters.SmtpMail, ref errmsg)) { return(new { Rcode = -1, Rmsg = "发送邮件出错:" + errmsg }); } return(new { Rcode = 1, Rmsg = "邮件已发送,请注意查收" }); } }
/// <summary> /// 五分彩数据同步 /// </summary> public void FiveMinuteLotteryDataSync() { try { var dataStr = DateTime.Now.ToString("yyyyMMdd"); var FiveMinuteLotteryList = new BaseBLL <FiveMinuteLottery>().LoadEntities(x => x.ID.Contains(dataStr)).ToList(); string date = $"action=GetLotteryOpen20List&lottery_code=1004&data_count=20&session_id={session_id}"; var reult = HttpMethods.HttpPost(ShengDaUrl.LotteryQuery, date); var baseObj = JsonConvert.DeserializeObject <BaseRes <string> >(reult); var fmlObj = JsonConvert.DeserializeObject <List <ReqFiveMinuteLottery> >(baseObj.data); var reqfmlResultList = new List <FiveMinuteLottery>(); foreach (var item in fmlObj) { var reqfmlResult = new FiveMinuteLottery() { ID = item.issue_no, OpenTime = item.open_time }; var list2 = new List <string>(item.lotteryopen_no.Split(new[] { "," }, StringSplitOptions.None)); reqfmlResult.One = int.Parse(list2[0]); reqfmlResult.Two = int.Parse(list2[1]); reqfmlResult.Three = int.Parse(list2[2]); reqfmlResult.Four = int.Parse(list2[3]); reqfmlResult.Five = int.Parse(list2[4]); reqfmlResultList.Add(reqfmlResult); } if (FiveMinuteLotteryList != null & FiveMinuteLotteryList.Count > 0) { reqfmlResultList = reqfmlResultList.Where(x => FiveMinuteLotteryList.FirstOrDefault(y => y.ID == x.ID) == null).ToList(); } new BaseBLL <FiveMinuteLottery>().BulkInsert2(reqfmlResultList); } catch (Exception e) { Console.WriteLine($"报错了,消息为{e.Message}"); } }
private int GetTypeId(string typename, string userName) { BLL.BaseBLL <BlogType> blogtype = new BaseBLL <BlogType>(); var blogtagmode = blogtype.GetList(t => t.TypeName == typename); if (blogtagmode.Count() >= 1) { return(blogtagmode.FirstOrDefault().Id); } else { var tmepUserid = GetUserId(userName); var user = new BLL.BaseBLL <BlogUser>().GetList(t => t.Id == tmepUserid, isAsNoTracking: false).FirstOrDefault(); blogtype.Insert(new BlogType() { TypeName = typename, CreationTime = DateTime.Now, IsDelte = false, BlogUser = user// new BlogUser { Id = GetUserId(userName), IsLock = false, BlogUserInfo = new BlogUserInfo() } }); blogtype.save(); return(GetTypeId(typename, userName)); } }
//响应微信平台推送消息 private void ResponseMsg(HttpContext httpContext, RequestParams requestParams) { BaseBLL weixin = null; IFactory factory = null; #region 通过微信类型生成对应的业务处理类 var application = new WApplicationInterfaceBLL(requestParams.LoggingSessionInfo); var appEntitys = application.QueryByEntity(new WApplicationInterfaceEntity() { WeiXinID = requestParams.WeixinId }, null); if (appEntitys != null && appEntitys.Length > 0) { var entity = appEntitys.FirstOrDefault(); BaseService.WriteLogWeixin("通过微信类型生成对应的业务处理类"); BaseService.WriteLogWeixin("WeiXinTypeId(微信类型): " + entity.WeiXinTypeId); switch (entity.WeiXinTypeId) { case WeiXinType.SUBSCRIPTION: factory = new SubscriptionFactory(); weixin = factory.CreateWeiXin(httpContext, requestParams); BaseService.WriteLogWeixin("订阅号"); break; case WeiXinType.SERVICE: factory = new ServiceFactory(); weixin = factory.CreateWeiXin(httpContext, requestParams); BaseService.WriteLogWeixin("服务号"); break; case WeiXinType.CERTIFICATION: //目前我们的客户一般是认证服务号,所以关注事件从这里查看 factory = new CertificationFactory(); weixin = factory.CreateWeiXin(httpContext, requestParams); BaseService.WriteLogWeixin("认证服务号"); break; case WeiXinType.SUBSCRIPTION_EXTEND: BaseService.WriteLogWeixin("可扩展订阅号"); break; case WeiXinType.SERVICE_EXTEND: BaseService.WriteLogWeixin("可扩展服务号"); break; case WeiXinType.CERTIFICATION_EXTEND: BaseService.WriteLogWeixin("可扩展认证服务号"); break; default: factory = new SubscriptionFactory(); weixin = factory.CreateWeiXin(httpContext, requestParams); BaseService.WriteLogWeixin("默认订阅号"); break; } } #endregion weixin.ResponseMsg();//根据消息类型,回应事件。有文本消息、图片消息、多客服、地理位置、事件 }
/// <summary> /// 录入个人信息 /// </summary> /// <param name="data"> /// {"author_info_id":0,"uid":1,"user_name":"xxx","sex":"男","area":"xxx","school":"xxxx","grade":"一年级","age":9,"phone":"1234567","teacher":"xxx","idcard":"2424242424242424242424242424"} /// </param> /// <returns></returns> public ApiResult AddUserInfo(dynamic data) { ApiResult apiResult = new ApiResult(); LogHelper.Info("录入个人信息data:" + data); if (Util.isNotNull(data)) { LogHelper.Info("录入个人信息data:" + Newtonsoft.Json.JsonConvert.SerializeObject(data)); string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); var user = Newtonsoft.Json.JsonConvert.DeserializeObject <author_info>(json); if (user == null || user.uid == 0) { return(new ApiResult() { success = false, message = "参数错误" }); } string idcrad = user?.idcard; if (Util.isNull(idcrad) || !System.Text.RegularExpressions.Regex.IsMatch(user.idcard, @"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)")) { return(new ApiResult() { success = false, message = "身份证输入不合法" }); } BaseBLL <author_info> bll = new BaseBLL <author_info>(); if (user.author_info_id > 0) { var _user = bll.Find(o => o.author_info_id == user.author_info_id); if (_user?.author_info_id > 0) { user.update_time = DateTime.Now; user.create_time = _user.create_time; user.uid = _user.uid; bll.Update(user); } else { return(new ApiResult() { success = false, message = "修改失败" }); } } else { user.create_time = DateTime.Now; user.update_time = DateTime.Now; bll.Add(user); } apiResult.success = true; apiResult.message = "成功"; } else { apiResult.success = false; apiResult.message = "参数错误"; } return(apiResult); }
protected void Button5_Click(object sender, EventArgs e) { BaseBLL bll = new BaseBLL(); var data = bll.InnerGetEntities<T_FB_CHARGEAPPLYMASTER>(new QueryExpression()); var b = from item in data orderby item.UPDATEDATE select item; var c = from item in b where item.TOTALMONEY > 0 select item; var d = c.Take(5).ToList(); }
public static IQueryable <BlogType> GetAllType(int id) { BLL.BaseBLL <BlogType> type = new BaseBLL <BlogType>(); return(type.GetList(t => t.BlogUser.Id == id)); }
public static IQueryable <BlogType> GetAllType() { BLL.BaseBLL <BlogType> type = new BaseBLL <BlogType>(); return(type.GetList(t => true)); }
public static string ForwardRealization(BlogUser userinfo, string tag, string type, string url, string siteUrl, bool isshowhome, bool isshowmyhome, bool isBJ = false) { if (userinfo != null) { int typeint = -1; int.TryParse(type, out typeint); var tags = tag.Split(','); var jp = new JumonyParser(); var html = jp.LoadDocument(url); var titlehtml = html.Find(".postTitle a").FirstOrDefault().InnerHtml(); if (!isBJ) { titlehtml = "【转】" + titlehtml; } else { titlehtml = "《" + titlehtml + "》"; } var bodyhtml = html.Find("#cnblogs_post_body").FirstOrDefault().InnerHtml(); bodyhtml += "</br><div class='div_zf'>==================================<a href='" + url + "' target='_blank'>原文链接</a>==================================</div>"; var mtag = BLL.Common.GetDataHelper.GetAllTag().Where(t => tags.Contains(t.TagName)).ToList(); var blogtagid = new List <int>(); for (int i = 0; i < tags.Length; i++) { blogtagid.Add(GetTagId(tags[i], userinfo.Id)); } //&& t.UsersId == userinfo.Id 理论是不用 加用户id 筛选 var myBlogTags = new BLL.BaseBLL <BlogTag>().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList(); var myBlogTypes = new BLL.BaseBLL <BlogType>().GetList(t => t.Id == typeint, isAsNoTracking: false).ToList(); object obj = null; string call = string.Empty; BLL.BaseBLL <BlogInfo> blogbll = new BaseBLL <BlogInfo>(); var blogtemp = blogbll.GetList(t => t.User.Id == userinfo.Id).OrderByDescending(t => t.Id).FirstOrDefault(); if (blogtemp != null && blogtemp.Title == titlehtml) { obj = new { s = "no", m = "已存在相同标题博客文章~", u = siteUrl }; call = obj.ToJson(); //Response.Write(call); return(call); } var blogmode = new BlogInfo() { User = userinfo, Title = titlehtml, Types = myBlogTypes, Tags = myBlogTags, Content = bodyhtml, CreationTime = DateTime.Now, BlogCreateTime = DateTime.Now, BlogUpTime = DateTime.Now, IsShowMyHome = isshowmyhome, IsShowHome = isshowhome }; blogbll.Insert(blogmode); if (blogbll.save() > 0) { obj = new { s = "ok", m = "发布成功", u = siteUrl + "/" + userinfo.UserName + "/" + blogmode.Id + ".html" }; call = obj.ToJson(); //Response.Write(call); return(call); } obj = new { s = "no", m = "发布失败", u = siteUrl + "/" + userinfo.UserName + "/" + blogmode.Id + ".html" }; call = obj.ToJson(); //Response.Write(call); return(call); } else { var obj = new { s = "no", m = "发布失败", u = siteUrl + "/" }; var call = obj.ToJson(); //Response.Write(call); return(call); } }
/// <summary> /// 获取用户所有文章类型 /// </summary> /// <returns></returns> public static IQueryable <BlogType> GetAllType(string name) { BLL.BaseBLL <BlogType> type = new BaseBLL <BlogType>(); return(type.GetList(t => t.BlogUser.UserName == name)); }
/// <summary> /// 迁移cnblog评论 /// </summary> /// <param name="BlogsId">嗨博客 博客id</param> /// <param name="BlogUsersId">嗨博客 评论博客用户id(因为迁移评论者 没有id 所以都默认为1)</param> /// <param name="postId">cnblog 博客id</param>int BlogUsersId = 1, /// <param name="blogApp">cnblog 博客用户名</param> public string testJumonyParser(int BlogsId = 1, string postId = "4368417", string blogApp = "zhaopei") { bool isNext = true; int i = 0; var BlogUsersId = 1; BLL.BaseBLL <BlogUser> userbll = new BaseBLL <BlogUser>(); var usertemp = GetDataHelper.GetAllUser().Where(t => t.UserName == " ").FirstOrDefault(); if (null == usertemp) { var user = new BlogUser() { UserName = "******", UserPass = "******", IsDelte = false, IsLock = false, UserMail = "无效", CreationTime = DateTime.Now, BlogUserInfo = new BlogUserInfo() }; userbll.Insert(user); userbll.save(false); BlogUsersId = user.Id; } else { BlogUsersId = usertemp.Id; } //List<BlogComment> blogcommen = new List<BlogComment>(); BaseBLL <BlogComment> blogcommenbll = new BaseBLL <BlogComment>(); while (isNext) { i++; var url = "http://www.cnblogs.com/mvc/blog/GetComments.aspx?postId=" + postId + "&blogApp=" + blogApp + "&pageIndex=" + i; var jumony = new JumonyParser(); var htmlSource = jumony.LoadDocument(url).InnerHtml(); JavaScriptSerializer _jsSerializer = new JavaScriptSerializer(); CnBlogComments comm = _jsSerializer.Deserialize <CnBlogComments>(htmlSource); var commentsHtml = jumony.Parse(comm.commentsHtml); var pager = commentsHtml.Find("div.pager").FirstOrDefault(); if (null != pager) { var Next = pager.Find("*").LastOrDefault().InnerText(); if (Next != "Next >") { isNext = false; } } else { isNext = false; } var listComment = commentsHtml.Find("div.feedbackItem").ToList(); foreach (var item in listComment) { var commentDataNode = item.Find("div.feedbackListSubtitle span.comment_date").FirstOrDefault(); // var commentData = DateTime.Parse(commentDataNode.InnerText()); var commentUserNode = item.Find("div.feedbackListSubtitle a[target='_blank']").FirstOrDefault(); var commentUser = commentUserNode.InnerText(); var Content = item.Find("div.blog_comment_body").FirstOrDefault().InnerText(); var user = new BLL.BaseBLL <BlogUser>().GetList(t => t.Id == BlogUsersId, isAsNoTracking: false).FirstOrDefault(); var bloginfo = new BLL.BaseBLL <BlogInfo>().GetList(t => t.Id == BlogsId, isAsNoTracking: false).FirstOrDefault(); blogcommenbll.Insert( new BlogComment() { BlogInfo = bloginfo, CommentID = -1, IsDelte = false, Content = Content, CreationTime = commentData, ReplyUserName = commentUser, BlogUser = user,// new BlogUser { Id = BlogUsersId, IsLock = false, BlogUserInfo = new BlogUserInfo() }, IsInitial = true } ); } } try { blogcommenbll.save(false); } catch (Exception) { throw; } return("ok"); }
public DronesController() { _droneBll = new DroneBLL(); _baseBll = new BaseBLL(); }
public BasesController() { _baseBll = new BaseBLL(); }
/// <summary> /// 使用业务对象构造对象 /// </summary> /// <param name="bll"></param> public BaseLocalService(BaseBLL <T> bll) { this.baseBLL = bll; }
public string Configure(ConfigureInput input) { var IsShowCSS = input.IsShowCSS == "on"; var IsDisCSS = input.IsDisCSS == "on"; if (BLLSession.UserInfoSessioin == null) { return("您还没有登录 不能修改~"); } try { //============================================================================================================== //遗留问题: //如下:如果 userinfobll.Up(BLLSession.UserInfoSessioin.BlogUserInfo)两次的话 报异常:[一个实体对象不能由多个 IEntityChangeTracker 实例引用] //那么 我只能 new一个新的对象 修改 然后 同时 BLLSession.UserInfoSessioin.BlogUserInfo里面的属性,不然 其他地方访问的话 是没有修改过来的值 //============================================================================================================== var userinftemp = new BlogUserInfo(); //BLLSession.UserInfoSessioin.BlogUserInfo; BLL.BaseBLL <BlogUserInfo> userinfobll = new BaseBLL <BlogUserInfo>(); if (input.TerminalType == "PC") //如果是PC端 { userinftemp.IsShowCSS = BLLSession.UserInfoSessioin.BlogUserInfo.IsShowCSS = IsShowCSS; userinftemp.IsDisCSS = BLLSession.UserInfoSessioin.BlogUserInfo.IsDisCSS = IsDisCSS; userinftemp.Id = BLLSession.UserInfoSessioin.BlogUserInfo.Id; userinfobll.Updata(userinftemp, "IsShowCSS", "IsDisCSS");//"IsShowHTML",, "IsShowJS" } else { userinftemp.IsShowMCSS = BLLSession.UserInfoSessioin.BlogUserInfo.IsShowMCSS = IsShowCSS; userinftemp.IsDisMCSS = BLLSession.UserInfoSessioin.BlogUserInfo.IsDisMCSS = IsDisCSS; userinftemp.Id = BLLSession.UserInfoSessioin.BlogUserInfo.Id; userinfobll.Updata(userinftemp, "IsShowMCSS", "IsDisMCSS"); } GetDataHelper.GetAllUser().FirstOrDefault(t => t.Id == BLLSession.UserInfoSessioin.Id).BlogUserInfo = BLLSession.UserInfoSessioin.BlogUserInfo; userinfobll.save(); string path = FileHelper.defaultpath + "/MyConfigure/" + BLLSession.UserInfoSessioin.UserName + "/"; FileHelper.CreatePath(path); if (input.conf_css.Length >= 40000 || input.conf_tail_html.Length >= 40000 || input.conf_first_html.Length >= 40000 || input.conf_side_html.Length >= 40000 || input.conf_js.Length >= 40000) { return("您修改的内容字符过多~"); } if (input.TerminalType == "PC")//如果是PC端 { FileHelper.SaveFile(path, "conf.css", input.conf_css); FileHelper.SaveFile(path, "conf_side.txt", input.conf_side_html); FileHelper.SaveFile(path, "conf_first.txt", input.conf_first_html); FileHelper.SaveFile(path, "conf_tail.txt", input.conf_tail_html); FileHelper.SaveFile(path, "conf.js", input.conf_js); } else { FileHelper.SaveFile(path, "Mconf.css", input.conf_css); FileHelper.SaveFile(path, "Mconf_side.txt", input.conf_side_html); FileHelper.SaveFile(path, "Mconf_first.txt", input.conf_first_html); FileHelper.SaveFile(path, "Mconf_tail.txt", input.conf_tail_html); FileHelper.SaveFile(path, "Mconf.js", input.conf_js); } return("修改成功~"); } catch (Exception ex) { LogSave.ErrLogSave("自定义样式出错", ex); return("修改失败~"); } }
private void FormLogin_Load(object sender, EventArgs e) { BaseBLL.InitAll(); radioButton1_CheckedChanged(null, null); }
private void btnWant_Click(object sender, EventArgs e) { try { if (MessageBox.Show("此操作将会展示你的个人信息给对方", "确认竞标", MessageBoxButtons.OKCancel) == DialogResult.OK) { var seBll = new BaseBLL<t_Session>(); var session = new t_Session() { ID = Guid.NewGuid(), AchivementID = Program.loginUserID, RequireID = this.requirement.PostID, RequirementID = this.requirement.ID, SessionDate = DateTime.Now }; var showinfo = userBll.Query(u => u.ID == Program.loginUserID).Select(u => u.ShowInfo).FirstOrDefault(); var chat = new t_ChatContent() { ID = Guid.NewGuid(), Date = DateTime.Now, SessionID = session.ID, SpeakID = Program.loginUserID, Content = showinfo ?? string.Empty }; if (seBll.Add(session) && chatBll.Add(chat)) { MessageBox.Show("已竞标,请静候佳音"); } else { MessageBox.Show("啊偶~前方高能预警,请稍后重试"); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "发生位置网络故障,请稍后重试"); } }
/// <summary> /// 根据用户导入cnblog数据 /// </summary> /// <param name="userName"></param> /// <returns></returns> public string Import(string userName, string iszf, string isshowhome, string isshowmyhome) { userName = userName.Trim(); int blosNumber = 0; JavaScriptSerializer jss = new JavaScriptSerializer(); string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx"; HtmlAgilityPack.HtmlWeb htmlweb = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument document = new HtmlDocument(); var docment = htmlweb.Load(url); string userid = GetCnblogUserId(userName); var liS = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li"); foreach (var item in liS) { var tXPath = item.XPath; var href = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value; var blogtype = htmlweb.Load(href); //var entrylistItem = blogtype.DocumentNode.SelectNodes("//*[@id='mainContent']/div/div[2]/div[@class='entrylistItem']"); var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']"); if (null == entrylistItem) //做兼容 { entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); // } if (null == entrylistItem) { continue; } foreach (var typeitem in entrylistItem) { var typeitemXPath = typeitem.XPath; var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a"); if (null == typeitemhrefObj) //做兼容 { typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a"); } var typeitemhref = typeitemhrefObj.Attributes["href"].Value; if (IsAreBlog(typeitemhref)) { continue;//说明这篇文章已经备份过了的 } var bloghtml = htmlweb.Load(typeitemhref); var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml; if (blogcontextobj == null) { continue; //有可能是加密文章 } var blogcontext = blogcontextobj.InnerHtml; var blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='Header1_HeaderTitle']"); if (null == blogNameObj) { blogNameObj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='lnkBlogTitle']"); } try { blogName = blogNameObj.InnerText; } catch (Exception) { throw; } var blogtitle = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText; var blogurl = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value; var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "&postId=" + typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1); var blogtag = Blogs.Common.Helper.MyHtmlHelper.GetRequest(blogtypetagurl); var jsonobj = jss.Deserialize <Dictionary <string, string> >(blogtag); if (null == jsonobj) { continue;//如果没有 则返回 (这里只能去 数字.html 不能取那种自定义的url) } var tagSplit = jsonobj["Tags"].Split(','); var blogtagid = new List <int>(); for (int i = 0; i < tagSplit.Length; i++) { if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1) { var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1); blogtagid.Add(this.GetTagId(blogtagname, userName)); } } var categoriesSplit = jsonobj["Categories"].Split(','); var blogtypeid = new List <int>(); for (int i = 0; i < categoriesSplit.Length; i++) { if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1) { var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1); blogtypeid.Add(this.GetTypeId(blogtypename, userName)); } } var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']"); var blogtime = ""; if (null != blogtimeobj) { blogtime = blogtimeobj.InnerText; } DateTime?createtime = null; var Outcreatetime = DateTime.Now; if (DateTime.TryParse(blogtime, out Outcreatetime)) { createtime = Outcreatetime; } BLL.BaseBLL <BlogInfo> blog = new BaseBLL <BlogInfo>(); var myBlogTags = new BLL.BaseBLL <BlogTag>().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList(); //.ToList(); var myBlogTypes = new BLL.BaseBLL <BlogType>().GetList(t => blogtypeid.Contains(t.Id), isAsNoTracking: false).ToList(); //.ToList(); var tmepUserid = GetUserId(userName); var user = new BLL.BaseBLL <BlogUser>().GetList(t => t.Id == tmepUserid, isAsNoTracking: false).FirstOrDefault(); try { var modelMyBlogs = new BlogInfo() { Content = blogcontext, BlogCreateTime = createtime, Title = blogtitle, Url = blogurl, IsDelte = false, Tags = myBlogTags, Types = myBlogTypes, User = user,// new BlogUser { Id = tmepUserid, IsLock = false, BlogUserInfo = new BlogUserInfo() }, ForUrl = blogurl, IsForwarding = iszf == "true", IsShowMyHome = isshowmyhome == "true", IsShowHome = isshowhome == "true" }; blog.Insert(modelMyBlogs); //blog.save(false); BLL.BaseBLL <BlogInfo> .StaticSave(); var newtag = string.Empty; try { modelMyBlogs.Tags.Where(t => true).ToList().ForEach(t => newtag += t.TagName + " "); var newblogurl = "/" + modelMyBlogs.User.UserName + "/" + modelMyBlogs.Id + ".html"; SearchResult search = new SearchResult() { flag = modelMyBlogs.User.Id, id = modelMyBlogs.Id, title = blogtitle, clickQuantity = 0, blogTag = newtag, content = getText(blogcontext, document), url = newblogurl }; SafetyWriteHelper <SearchResult> .logWrite(search, PanGuLuceneHelper.instance.CreateIndex); } catch (Exception) { throw; } var postid = blogurl.Substring(blogurl.LastIndexOf('/') + 1); postid = postid.Substring(0, postid.LastIndexOf('.')); testJumonyParser(modelMyBlogs.Id, postid, userName); blosNumber++; } catch (Exception ex) { throw; } } } if (blosNumber > 0) { Blogs.BLL.Common.GetDataHelper.GetAllTag(); //Blogs.BLL.Common.CacheData.GetAllType(true); //Blogs.BLL.Common.CacheData.GetAllUserInfo(true); return("成功导入" + blosNumber + "篇Blog"); } return("ok"); }
public ActivityController() { droneBll = new DroneBLL(); baseBll = new BaseBLL(); }
/// <summary> /// 审核/退回 /// formdata /// state:1退回,2审核 /// return_tag(退回标签):xxxx,xxxx,xxxx /// return_remark(退回理由备注):xxxxxxxxxxx /// ids:1,2,3,4,5,6,7,8,9,10 /// </summary> /// <returns></returns> public ApiResult SubmitArticle() { ApiResult apiResult = new ApiResult(); string _state = HttpContext.Current.Request.Form["state"]; string return_tag = HttpContext.Current.Request.Form["return_tag"]; string return_remark = HttpContext.Current.Request.Form["return_remark"]; string _article_id = HttpContext.Current.Request.Form["ids"]; var checkResult = Util.CheckParameters( new Parameter { Value = _state, Msg = "state 不能为空值" }, new Parameter { Value = _state, Msg = "state 必须是数字类型", Regex = @"^[1-9]\d*$" }, new Parameter { Value = _article_id, Msg = "ids 不能为空值" } ); if (!checkResult.OK) { apiResult.success = false; apiResult.status = ApiStatusCode.InvalidParam; apiResult.message = checkResult.Msg; return(apiResult); } int state = int.Parse(_state); List <int> id_list = new List <int>(); string[] article_ids = _article_id.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in article_ids) { int _id = 0; int.TryParse(id, out _id); if (_id > 0) { id_list.Add(_id); } } BaseBLL <article_states> state_bll = new BaseBLL <article_states>(); var article_states = state_bll.FindList <int>(o => id_list.Contains(o.article_id)); if (state == 1) { List <article_states> back_list = new List <article_states>(); foreach (var article_state in article_states) { article_state.article_state = 1; article_state.update_time = DateTime.Now; article_state.return_tag = return_tag; article_state.return_remark = return_remark; back_list.Add(article_state); } state_bll.UpdateMore(back_list); } else if (state == 2) { List <article_states> sumbit_list = new List <article_states>(); foreach (var article_state in article_states) { article_state.article_state = 2; article_state.update_time = DateTime.Now; article_state.return_remark = ""; article_state.return_tag = ""; sumbit_list.Add(article_state); } state_bll.UpdateMore(sumbit_list); } else { return(new ApiResult() { success = false, message = "参数错误" }); } apiResult.success = true; apiResult.message = state == 1 ? "退回成功" : "审核成功"; return(apiResult); }
/// <summary> /// 所有联系人头像下载并压缩保存 /// </summary> /// <param name="downloadFilePath">原文件路径(压缩之后文件夹删除)</param> /// <param name="actualFilePath">压缩后的文件路径</param> public static void DownloadUserHeadImage() { var downloadUserHeadImagePath = publicMethod.DownloadFilePath() + "\\DownloadUserHeadImage\\"; if (!Directory.Exists(downloadUserHeadImagePath)) { Directory.CreateDirectory(downloadUserHeadImagePath); } if (!Directory.Exists(publicMethod.UserHeadImageFilePath())) { Directory.CreateDirectory(publicMethod.UserHeadImageFilePath()); } //AsyncHandler.AsyncCall(System.Windows.Application.Current.Dispatcher, () => //{ var tSessionBll = new BaseBLL <AntSdkTsession, T_SessionDAL>(); var tSessionList = tSessionBll.GetList(); if (tSessionList != null && tSessionList.Count > 0) { var userSessionList = tSessionList.Where(m => !string.IsNullOrEmpty(m.UserId)); foreach (var userSession in userSessionList) { var contactsUser = AntSdkService.AntSdkListContactsEntity.users.FirstOrDefault(m => m.userId == userSession.UserId); if (contactsUser == null) { continue; } { if (string.IsNullOrEmpty(contactsUser.picture)) { continue; } var tempUserImage = GlobalVariable.ContactHeadImage.UserHeadImages.FirstOrDefault(m => m.UserID == contactsUser.userId); if (tempUserImage != null) { continue; } var index = contactsUser.picture.LastIndexOf("/", StringComparison.Ordinal) + 1; var fileName = contactsUser.picture.Substring(index, contactsUser.picture.Length - index); if (File.Exists(publicMethod.UserHeadImageFilePath() + fileName) || !publicMethod.IsUrlRegex(contactsUser.picture)) { continue; } var filePath = DownloadPicture(contactsUser.picture, downloadUserHeadImagePath + fileName, -1, publicMethod.UserHeadImageFilePath(), contactsUser.userId); if (string.IsNullOrEmpty(filePath)) { continue; } GlobalVariable.ContactHeadImage.UserHeadImages.Add(new ContactUserImage { Url = filePath, UserID = contactsUser.userId }); } } } var contactsUsers = AntSdkService.AntSdkListContactsEntity.users; for (var i = 0; i < contactsUsers.Count; i++) { var contactUser = contactsUsers[i]; if (string.IsNullOrEmpty(contactUser.picture)) { continue; } var tempUserImage = GlobalVariable.ContactHeadImage.UserHeadImages.FirstOrDefault(m => m.UserID == contactUser.userId); if (tempUserImage != null) { continue; } var index = contactUser.picture.LastIndexOf("/", StringComparison.Ordinal) + 1; var fileName = contactUser.picture.Substring(index, contactUser.picture.Length - index); if (!File.Exists(publicMethod.UserHeadImageFilePath() + fileName) && publicMethod.IsUrlRegex(contactUser.picture)) { var filePath = DownloadPicture(contactUser.picture, downloadUserHeadImagePath + fileName, -1, publicMethod.UserHeadImageFilePath(), contactUser.userId); if (string.IsNullOrEmpty(filePath)) { continue; } GlobalVariable.ContactHeadImage.UserHeadImages.Add(new ContactUserImage { Url = filePath, UserID = contactUser.userId }); } else { GlobalVariable.ContactHeadImage.UserHeadImages.Add(new ContactUserImage { Url = publicMethod.UserHeadImageFilePath() + fileName, UserID = contactUser.userId }); } } if (!Directory.Exists(downloadUserHeadImagePath)) { return; } var files = Directory.GetFiles(downloadUserHeadImagePath); if (files.Length == 0) { Directory.Delete(downloadUserHeadImagePath); } else { foreach (string fileName in files) { string fName = fileName.Substring(downloadUserHeadImagePath.Length); try { if (File.Exists(Path.Combine(downloadUserHeadImagePath, fName)) && !File.Exists(Path.Combine(publicMethod.UserHeadImageFilePath(), fName))) { File.Move(Path.Combine(downloadUserHeadImagePath, fName), Path.Combine(publicMethod.UserHeadImageFilePath(), fName)); } else { File.Delete(Path.Combine(downloadUserHeadImagePath, fName)); } } // 捕捉异常. catch (IOException copyError) { LogHelper.WriteError(copyError.Message); } } if (files.Length == 0) { Directory.Delete(downloadUserHeadImagePath); } } }
/// <summary> /// 提交内容的编辑或修改 /// </summary> /// <param name="input"></param> /// <returns></returns> public JSData ReleasePost(ReleaseInput input) { JSData jsdata = new JSData(); #region 数据验证 if (null == BLL.Common.BLLSession.UserInfoSessioin) { jsdata.Messg = "您还未登录~"; } else if (BLL.Common.BLLSession.UserInfoSessioin.IsLock) { jsdata.Messg = "您的账户未激活,暂只能评论。~"; } else if (string.IsNullOrEmpty(input.Content)) { jsdata.Messg = "内容不能为空~"; } if (!string.IsNullOrEmpty(jsdata.Messg)) { jsdata.State = EnumState.失败; return(jsdata); } #endregion BLL.BaseBLL <BlogInfo> blogbll = new BaseBLL <BlogInfo>(); var blogtemp = blogbll.GetList(t => t.Id == input.Blogid, isAsNoTracking: false).FirstOrDefault(); var userid = input.Blogid > 0 ? blogtemp.User.Id : BLLSession.UserInfoSessioin.Id;//如果numblogid大于〇证明 是编辑修改 var sessionuserid = BLLSession.UserInfoSessioin.Id; //获取得 文章 类型集合 对象 var typelist = new List <int>(); if (!string.IsNullOrEmpty(input.Chk_type)) { foreach (string type in input.Chk_type.Split(',').ToList()) { if (!string.IsNullOrEmpty(type)) { typelist.Add(int.Parse(type)); } } } // types.Split(',').ToList().ForEach(t => typelist.Add(int.Parse(t))); var myBlogTypes = new BLL.BaseBLL <BlogType>().GetList(t => typelist.Contains(t.Id), isAsNoTracking: false).ToList(); //获取得 文章 tag标签集合 对象 //old var oldtaglist = string.IsNullOrEmpty(input.Oldtag) ? new List <string>() : input.Oldtag.Split(',').ToList(); var myOldTagTypes = new BLL.BaseBLL <BlogTag>().GetList(t => t.BlogUser.Id == userid && oldtaglist.Contains(t.TagName), isAsNoTracking: false).ToList(); //new var newtaglist = input.Newtag.GetValueOrEmpty().Split(',').ToList(); AddTag(newtaglist, userid);//保存到数据库 var myNweTagTypes = new BLL.BaseBLL <BlogTag>().GetList(t => t.BlogUser.Id == userid && newtaglist.Contains(t.TagName), isAsNoTracking: false).ToList(); myNweTagTypes.ForEach(t => myOldTagTypes.Add(t)); if (input.Blogid > 0) //如果有 blogid 则修改 { if (sessionuserid == blogtemp.User.Id || BLLSession.UserInfoSessioin.UserName == admin) //一定要验证更新的博客是否是登陆的用户 { blogtemp.Content = input.Content; blogtemp.Title = input.Title; blogtemp.IsShowMyHome = input.Isshowmyhome; blogtemp.IsShowHome = input.Isshowhome; blogtemp.Types.Clear();//更新之前要清空 不如会存在主外键约束异常 blogtemp.Types = myBlogTypes; blogtemp.Tags.Clear(); blogtemp.Tags = myOldTagTypes; blogtemp.IsDelte = false; blogtemp.IsForwarding = false; jsdata.Messg = "修改成功~"; } else { jsdata.Messg = "您没有编辑此博文的权限~"; jsdata.JSurl = "/"; jsdata.State = EnumState.失败; return(jsdata); } } else //否则 新增 { var blogfirst = blogbll.GetList(t => t.User.Id == sessionuserid).OrderByDescending(t => t.Id).FirstOrDefault(); if (null != blogfirst && blogfirst.Title == input.Title) { jsdata.Messg = "不能同时发表两篇一样标题的文章~"; } else { var bloguser = new BLL.BaseBLL <BlogUser>().GetList(t => t.Id == BLLSession.UserInfoSessioin.Id, isAsNoTracking: false).FirstOrDefault(); blogtemp = new BlogInfo() { User = bloguser, Content = input.Content, Title = input.Title, BlogUpTime = DateTime.Now, BlogCreateTime = DateTime.Now, IsShowMyHome = input.Isshowmyhome, IsShowHome = input.Isshowhome, Types = myBlogTypes, Tags = myOldTagTypes, IsDelte = false, IsForwarding = false }; blogbll.Insert(blogtemp); jsdata.Messg = "发布成功~"; } } // if (blogbll.save(false) > 0) { #region 添加 或 修改搜索索引 try { var newtagList = string.Empty; blogtemp.Tags.Where(t => true).ToList().ForEach(t => newtagList += t.TagName + " "); var newblogurl = "/" + BLLSession.UserInfoSessioin.UserName + "/" + blogtemp.Id + ".html"; SearchResult search = new SearchResult() { flag = blogtemp.User.Id, id = blogtemp.Id, title = blogtemp.Title, clickQuantity = 0, blogTag = newtagList, content = Blogs.Common.Helper.MyHtmlHelper.GetHtmlText(blogtemp.Content), url = newblogurl }; SafetyWriteHelper <SearchResult> .logWrite(search, PanGuLuceneHelper.instance.CreateIndex); } catch (Exception) { } #endregion jsdata.State = EnumState.成功; jsdata.JSurl = "/" + GetDataHelper.GetAllUser().Where(t => t.Id == blogtemp.User.Id).First().UserName + "/" + blogtemp.Id + ".html"; return(jsdata); } jsdata.Messg = string.IsNullOrEmpty(jsdata.Messg) ? "操作失败~" : jsdata.Messg; jsdata.State = EnumState.失败; return(jsdata); }
/// <summary> /// 上传作品(一个赛季/一个人只能有一份作品)(必须在作品征集时间段内上传) /// formdata:"article_id":0,"article_title":"xxxx","uid":1,"","article_content":"xxxxx","article_pic":"图片","zone_id"(赛区):1,"competiontion_season_id"(赛季):1 /// </summary> /// <returns></returns> public ApiResult UploadArticle() { ApiResult apiResult = new ApiResult(); #region 参数检测 //var pic = System.Web.HttpContext.Current.Request.Files[0]; var _article_pic = System.Web.HttpContext.Current.Request.Form["article_pic"]; string _article_id = System.Web.HttpContext.Current.Request.Form["article_id"]; string _article_title = System.Web.HttpContext.Current.Request.Form["article_title"]; string _uid = System.Web.HttpContext.Current.Request.Form["uid"]; string _article_content = System.Web.HttpContext.Current.Request.Form["article_content"]; string _zone_id = System.Web.HttpContext.Current.Request.Form["zone_id"]; string _competiontion_season_id = System.Web.HttpContext.Current.Request.Form["competiontion_season_id"]; LogHelper.Info("zone_id:" + _zone_id); //一个赛季,一个作者,只能有一份作品 var checkResult = Util.CheckParameters( new Parameter { Value = _zone_id, Msg = "zone_id 不能为空值" }, new Parameter { Value = _zone_id, Msg = "zone_id 必须是数字类型", Regex = @"^[1-9]\d*$" }, new Parameter { Value = _uid, Msg = "uid 不能为空值" }, new Parameter { Value = _uid, Msg = "uid 必须是数字类型", Regex = @"^[1-9]\d*$" }, new Parameter { Value = _article_title, Msg = "article_title 不能为空值" }, new Parameter { Value = _article_content, Msg = "article_content 不能为空值" } ); if (!checkResult.OK) { apiResult.success = false; apiResult.status = ApiStatusCode.InvalidParam; apiResult.message = checkResult.Msg; return(apiResult); } int uid = int.Parse(_uid); int zone_id = int.Parse(_zone_id); int article_id = int.Parse(_article_id); #endregion #region 赛季检查 //开启的赛季 int competiontion_season_id = 0; if (Util.isNotNull(_competiontion_season_id)) { competiontion_season_id = int.Parse(_competiontion_season_id); } else { //查到当前默认开启的赛季 BaseBLL <competition_notice> notice_bll = new BaseBLL <competition_notice>(); var competion_season = notice_bll.Find(o => o.is_delete == 0 && o.is_open == 1); competiontion_season_id = competion_season?.competition_season_id ?? 0; //是否已过期 if (competion_season.preliminaries_start_date > DateTime.Now.Date) { return(new ApiResult() { success = false, message = "大赛投稿时间还没开始" }); } if (competion_season.preliminaries_end_date < DateTime.Now.Date) { return(new ApiResult() { success = false, message = "大赛投稿已截止" }); } } if (competiontion_season_id == 0) { return(new ApiResult() { success = false, message = "当前没有开启任何赛季" }); } #endregion ArticleBLL bll = new ArticleBLL(); BaseBLL <article_states> state_bll = new BaseBLL <article_states>(); BaseBLL <articles> article_bll = new BaseBLL <articles>(); if (article_id > 0) { //判断状态是否可修改 int article_state = state_bll.Find(o => o.article_id == article_id)?.article_state ?? 0; if (article_state > 1) { return(new ApiResult() { success = false, message = "当前状态不可修改" }); } #region 修改 var article = article_bll.Find(o => o.article_id == article_id); if (article?.article_id > 0) { //修改 article.article_pic = _article_pic ?? ""; article.article_title = _article_title; article.article_content = _article_content; article.create_time = DateTime.Now; article.update_time = DateTime.Now; if (article_bll.Update(article)) { //关联表更新 BaseBLL <article_competition_season> article_season_bll = new BaseBLL <article_competition_season>(); var article_competition_season = article_season_bll.Find(o => o.article_id == article_id); if (article_competition_season?.article_season_id > 0) { article_competition_season.zone_id = zone_id; article_competition_season.competiontion_season_id = competiontion_season_id; article_competition_season.update_time = DateTime.Now; article_season_bll.Update(article_competition_season); } //更新作品的状态 BaseBLL <article_states> states_bll = new BaseBLL <article_states>(); var article_states = states_bll.Find(o => o.article_id == article_id); if (article_states?.article_id > 0) { article_states.article_state = 0; article_states.return_remark = ""; article_states.return_tag = ""; article_states.update_time = DateTime.Now; states_bll.Update(article_states); } apiResult.success = true; apiResult.message = "修改成功"; } else { apiResult.success = false; apiResult.message = "修改失败"; } } else { apiResult.success = false; apiResult.message = "数据不存在"; } #endregion } else { #region 新增 //是否已存在 if (bll.ExistUserArticle(uid, competiontion_season_id)) { return(new ApiResult() { success = false, message = "您在当前赛季已经有一份作品了~" }); } articles article = new articles(); //后台自动生成 article.article_pic = _article_pic ?? ""; article.article_title = _article_title; article.article_content = _article_content; article.create_time = DateTime.Now; article.uid = uid; article.update_time = DateTime.Now; var result = article_bll.Add(article); if (result?.article_id > 0) { //更新编号 apiResult = bll.UploadAritcleNo(result); if (apiResult.success) { //更新关联表 BaseBLL <article_competition_season> article_season_bll = new BaseBLL <article_competition_season>(); article_season_bll.Add(new article_competition_season() { article_id = result.article_id, zone_id = zone_id, competiontion_season_id = competiontion_season_id, create_time = DateTime.Now, update_time = DateTime.Now, }); //更新状态表 state_bll.Add(new article_states() { article_id = result.article_id, article_state = 0, create_time = DateTime.Now, update_time = DateTime.Now, }); apiResult.success = true; apiResult.message = "保存成功"; } } else { apiResult.success = false; apiResult.message = "保存失败"; } #endregion } return(apiResult); }
/// <summary> /// 添加通知 /// </summary> /// <param name="data"> /// { /// "notice_id": 若大于零则为修改,小于零则为新增, /// "title": 通知标题, /// "content": 通知内容, /// "logo": 通知的 logo, /// "is_top": 0 不置顶,1 置顶, /// "publish_time": 发布时间,在该时间后才能查询到该通知,若不设置,则为当前时间 /// } /// </param> /// <returns></returns> public ApiResult AddNotice(dynamic data) { ApiResult apiResult = new ApiResult(); if (Util.isNotNull(data)) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); var notice = Newtonsoft.Json.JsonConvert.DeserializeObject <user_notice>(json); BaseBLL <user_notice> bll = new BaseBLL <user_notice>(); if (notice?.notice_id > 0) { //如果是置顶,应先将之前置顶的数据取消 if (notice.is_top == 1) { var is_top_notices = bll.FindList <int>(o => o.is_top == 1); List <user_notice> is_top_notice_list = new List <user_notice>(); foreach (var _notice in is_top_notices) { _notice.is_top = 0; _notice.update_time = DateTime.Now; is_top_notice_list.Add(_notice); } bll.UpdateMore(is_top_notice_list); } // 修改 var findNotice = bll.Find(n => n.notice_id == notice.notice_id); if (findNotice == null) { apiResult.success = false; apiResult.message = "不存在该通知"; return(apiResult); } notice.create_time = findNotice.create_time; notice.update_time = DateTime.Now; bll.Update(notice); } else if (Util.isNotNull(notice)) { //如果是置顶,应先将之前置顶的数据取消 if (notice.is_top == 1) { var is_top_notices = bll.FindList <int>(o => o.is_top == 1); List <user_notice> is_top_notice_list = new List <user_notice>(); foreach (var _notice in is_top_notices) { _notice.is_top = 0; _notice.update_time = DateTime.Now; is_top_notice_list.Add(_notice); } bll.UpdateMore(is_top_notice_list); } // 新增 if (!notice.publish_time.HasValue) { notice.publish_time = DateTime.Now; } notice.create_time = DateTime.Now; notice.update_time = DateTime.Now; bll.Add(notice); } else { apiResult.success = false; apiResult.message = "参数错误"; return(apiResult); } } else { apiResult.success = false; apiResult.message = "参数错误"; } apiResult.success = true; apiResult.message = "成功"; return(apiResult); }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); Bll = new BaseBLL <T>(GetDbContext()); }
private void ProcessShipment(int shipmentId, int droneId) { Random r = new Random(); int travelTime; ShipmentBLL shipBLL = new ShipmentBLL(); DroneBLL droneBLL = new DroneBLL(); DroneShipmentActivityLogBLL logBLL = new DroneShipmentActivityLogBLL(); BaseBLL baseBll = new BaseBLL(); AddressBLL addressBll = new AddressBLL(); // Start ShipmentInfo shipment = shipBLL.GetShipment(shipmentId); shipment.Status = ShipmentStatus.InTransit; shipment.DroneId = droneId; shipBLL.UpdateShipment(shipment); DroneShipmentActivityLogInfo log = new DroneShipmentActivityLogInfo(); log.DroneId = droneId; log.ShipmentId = shipmentId; log.Message = "Beginning processing"; logBLL.AddDroneShipmentActivityLog(log); // Go pick up shipment DroneInfo drone = droneBLL.GetDrone(droneId); drone.Status = DroneStatus.PickingUpShipment; droneBLL.UpdateDrone(drone); log.Message = "Travelling to shipment source for pickup"; logBLL.AddDroneShipmentActivityLog(log); travelTime= r.Next(MIN_TRAVEL_TIME_IN_SECONDS, MAX_TRAVEL_TIME_IN_SECONDS); log.Message = string.Format("Estimated time to reach shipment source (in seconds): {0}", travelTime); logBLL.AddDroneShipmentActivityLog(log); TravelTo(droneBLL, drone, shipment.SourceAddress.Longitude, shipment.SourceAddress.Latitude, travelTime); // Deliver shipment log.Message = "Delivering shipment to destination"; logBLL.AddDroneShipmentActivityLog(log); drone.Status = DroneStatus.DeliveringShipment; droneBLL.UpdateDrone(drone); travelTime = r.Next(MIN_TRAVEL_TIME_IN_SECONDS, MAX_TRAVEL_TIME_IN_SECONDS); log.Message = string.Format("Estimated time to reach shipment destination (in seconds): {0}", travelTime); logBLL.AddDroneShipmentActivityLog(log); TravelTo(droneBLL, drone, shipment.DestinationAddress.Longitude, shipment.DestinationAddress.Latitude, travelTime); // Shipment delivered shipment.Status = ShipmentStatus.Shipped; shipBLL.UpdateShipment(shipment); log.Message = "Shipment delivered"; logBLL.AddDroneShipmentActivityLog(log); // Returning home log.Message = "Returning to base"; logBLL.AddDroneShipmentActivityLog(log); drone.Status = DroneStatus.ReturningToBase; droneBLL.UpdateDrone(drone); // Find the nearest base and go there log.Message = "Locating the nearest base"; logBLL.AddDroneShipmentActivityLog(log); var bases = baseBll.GetAll(); BaseInfo nearestBase = null; double shortestDistance = double.MaxValue; foreach (var baseInfo in bases) { var distance = addressBll.GetDistanceKm((double)drone.Latitude, (double)drone.Longitude, (double)baseInfo.Address.Latitude, (double)baseInfo.Address.Longitude); if (distance < shortestDistance) { shortestDistance = distance; nearestBase = baseInfo; } } log.Message = string.Format("Nearest base is: {0}", nearestBase.Name); logBLL.AddDroneShipmentActivityLog(log); travelTime = r.Next(MIN_TRAVEL_TIME_IN_SECONDS, MAX_TRAVEL_TIME_IN_SECONDS); log.Message = string.Format("Estimated time to reach base (in seconds): {0}", travelTime); logBLL.AddDroneShipmentActivityLog(log); TravelTo(droneBLL, drone, nearestBase.Address.Longitude, nearestBase.Address.Latitude, travelTime); // End log.Message = "Now available"; logBLL.AddDroneShipmentActivityLog(log); drone.Status = DroneStatus.Available; droneBLL.UpdateDrone(drone); }
public object GetBookInfo(BookParm book) { string errmsg = null; if (book == null || book.did < 1 || book.sid < 1 || book.pid < 0) { return(new { Rcode = -1, Rmsg = "参数错误" }); } if (userLoginManager.LoginUser == null || userLoginManager.LoginUser.UserID < 1) { return new { Rcode = -2, Rmsg = "未登录" } } ; string userIP = null; string tablename, serviceno, orderno; int costtype; decimal m_price, m_discount; int status = BaseBLL.GetFullPathResourceCheckCost(book.did, book.sid, userLoginManager.LoginUser.UserID, userLoginManager.LoginUser.Customerid, userIP, out tablename, out costtype, out m_price, out m_discount, out serviceno, out orderno, out errmsg); if (status == -1) { return new { Rcode = -1, Rmsg = errmsg } } ; if (status == 0) { return new { Rcode = -3, Rmsg = "此资源需要付费才能在线阅读,现在去付费", Rdata = orderno } } ; BookInfo bookinfo = ResourcesBLL.GetFilePath(tablename, book.sid, book.pid, "fullpath", out errmsg); if (!string.IsNullOrEmpty(errmsg) || bookinfo == null) { return new { Rcode = -1, Rmsg = "获取资源数据错误" + errmsg } } ; if (string.IsNullOrEmpty(bookinfo.BookPath)) { return(new { Rcode = -1, Rmsg = "资源文件路径不存在" }); } string pdffile = string.Format("{0}{1}", GlobalParameters.RootFilePath, bookinfo.BookPath).Replace("//", "/").Replace("/", "\\"); if (!File.Exists(pdffile)) { return(new { Rcode = -1, Rmsg = "资源文件不存在" }); } if (!Path.GetExtension(pdffile).Equals(".pdf", StringComparison.CurrentCultureIgnoreCase)) { return(new { Rcode = -1, Rmsg = "此资源非在线阅读资源,请直接下载" }); } BookInfo info = new BookInfo(); info.IsCopy = false; info.IsDown = false; info.IsFind = false; string swfpath = Path.GetDirectoryName(pdffile) + "\\swf"; if (!Directory.Exists(swfpath)) { return(new { Rcode = -1, Rmsg = "资源文件未转换" }); } string[] files = Directory.GetFiles(swfpath, "*.swf"); if (files.Length == 0) { return(new { Rcode = -1, Rmsg = "资源文件未转换或转换失败" }); } info.LimitPage = bookinfo.LimitPage; info.PageCount = files.Length; info.Domain = string.Format("http://{0}", HttpContext.Current.Request.Url.Authority); info.BookPath = Path.GetDirectoryName(bookinfo.BookPath) + "/swf"; string[] fiarr = Directory.GetFiles(Path.GetDirectoryName(pdffile), "*.xml"); if (fiarr.Length > 0) { try { //解析xml目录文件 //string xmlstr = File.ReadAllText(fiarr[0]); //XmlDocument xmldoc = new XmlDocument(); //xmldoc.LoadXml(xmlstr); //XmlElement rootnode = (XmlElement)xmldoc.SelectSingleNode("Bookmark"); //RIPS.BaseModels.Options options = new RIPS.BaseModels.Options() { id = "0", text = "", children = new List<RIPS.BaseModels.Options>() }; //int idnum = 0; //getChildren(rootnode, options, idnum); //info.ThemeStr = options.children; } catch (Exception ex) { info.ThemeStr = null; } } return(new { Rcode = 1, Rdata = info }); } //private static void getChildren(XmlElement element, RIPS.BaseModels.Options option, int idnum) //{ // option.children = new List<RIPS.BaseModels.Options>(); // RIPS.BaseModels.Options op; // string text; // foreach (object obja in element.ChildNodes) // { // if (obja.GetType() == typeof(XmlElement)) // { // XmlElement el = (XmlElement)obja; // if (el.FirstChild != null) // text = el.FirstChild.Value; // else // text = el.InnerText; // text = text.Replace("\r\n", ""); // op = new RIPS.BaseModels.Options() { id = idnum.ToString() + "_" + el.GetAttribute("Page"), text = text, children = new List<RIPS.BaseModels.Options>() }; // idnum++; // option.children.Add(op); // if (el.ChildNodes.Count > 0) // { // getChildren(el, op, idnum); // } // } // } //} } }
public ApiResult WeixinLogin(dynamic data) { ApiResult apiResult = new ApiResult(); var checkResult = Util.CheckParameters( new Parameter { Value = data?.code, Msg = "code不能为空" }, new Parameter { Value = data?.userinfo.ToString(), Msg = "userInfo不能为空" }, new Parameter { Value = data?.appcode, Msg = "appcode不能为空!" } ); if (!checkResult.OK) { apiResult.success = false; apiResult.status = ApiStatusCode.InvalidParam; apiResult.message = checkResult.Msg; return(apiResult); } try { //根据code查找APPID与Secret,获取微信session、openid和unionid string appcode = data.appcode.ToString(); BaseBLL <weixin_applet> weixinAppletBll = new BaseBLL <weixin_applet>(); weixin_applet weixinApplet = weixinAppletBll.Find(x => x.appcode == appcode); WeixinXAPI weixinxapi = new WeixinXAPI(weixinApplet.appid, weixinApplet.secret); string str = weixinxapi.codeToSession(data.code.ToString()); JObject session_json = JObject.Parse(str); if (session_json["errcode"].To <string>().IsNotNullAndEmpty()) { apiResult.success = false; apiResult.status = ApiStatusCode.NotFound; apiResult.message = str; return(apiResult); } string openid = session_json["openid"].ToString(); string session_key = session_json["session_key"].ToString(); string unionid = session_json["unionid"].To <string>(); if (StringHelper.IsNullOrEmpty(unionid) && !StringHelper.IsNullOrEmpty(data?.encryptedData) && !StringHelper.IsNullOrEmpty(data?.iv)) { string info = DEncrypt.XCXDecrypt(data?.encryptedData.ToString(), session_key, data?.iv.ToString()); JObject userInfoJson = JObject.Parse(info); unionid = userInfoJson["unionId"].To <string>(); } weixin_user userInfo = new weixin_user { openid = openid, unionid = unionid, nickname = data.userinfo["nickName"], sex = data.userinfo["gender"], language = data.userinfo["language"], city = data.userinfo["city"], province = data.userinfo["province"], country = data.userinfo["country"], headimgurl = data.userinfo["avatarUrl"], source_code = appcode, weixin_applet_id = weixinApplet.id }; if (Util.isNotNull(userInfo.unionid)) { //查询当前openid的用户是否存在 //如果不存在则要创建,创建时,先创建 iuser ,再创建 weixin_user BaseBLL <weixin_user> weixinUserBll = new BaseBLL <weixin_user>(); var weixinUser = weixinUserBll.Find(x => x.unionid == unionid); bool first_login = false; //可能是第一次登陆,在网页端登陆 if (weixinUser == null) { //微信开发平台的openid与小程序的openid不一致 first_login = true; //先存iuser var iuser = new iuser(); BaseBLL <iuser> iuserBll = new BaseBLL <iuser>(); iuser.random = sys.getRandomStr(); iuser.createtime = DateTime.Now; iuser.updatetime = DateTime.Now; iuser = iuserBll.Add(iuser); //再存weixin_user userInfo.uid = iuser.id; userInfo.sub_time = DateTime.Now; userInfo.first_sub_time = DateTime.Now; LogHelper.Info("first_login:"******",userInfo:" + Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUser = weixinUserBll.Add(userInfo); } else { weixinUser.nickname = userInfo.nickname; weixinUser.headimgurl = userInfo.headimgurl; LogHelper.Info("first_login:"******",userInfo:" + Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUserBll.Update(weixinUser); } apiResult.success = true; apiResult.data = new { first_login = first_login, weixinUser = weixinUser }; apiResult.status = ApiStatusCode.OK; } else { return(new ApiResult() { success = false, message = "unionid不能为空,小程序必须绑定开放平台" }); } } catch (Exception ex) { LogHelper.Error(ex.Message, ex); apiResult.success = false; apiResult.status = ApiStatusCode.Error; } return(apiResult); }
/// <summary> /// 回调函数 /// </summary> /// <param name="code">请求微信返回的code</param> /// <param name="state">请求微信的参数state</param> /// <returns></returns> public ApiResult LoginReturn(string code, string state) { ApiResult apiResult = new ApiResult(); LogHelper.Info("code:" + code + ",state:" + state); ////必须用cookie或者session //var session = HttpContext.Current.Session["session_weixin_login_state"]; //string session_state = session == null ? "" : session.ToString(); //string cookie_state = CookieHelper.GetCookieValue("cookie_weixin_login_state"); //LogHelper.Info("session_state:" + session_state + ",cookie_state:" + cookie_state); //if (state == _state) //{ BaseBLL <weixin_open> bll = new BaseBLL <weixin_open>(); var weixin_open = bll.Find(o => o.appid != null && o.secret != null); string appid = weixin_open.appid; string secret = weixin_open.secret; WeixinOpenAPI api = new WeixinOpenAPI(appid, secret); //string access_token = weixin_open.access_token; //string access_token_time = weixin_open.access_token_time == null ? "" : weixin_open.access_token_time.Value.ToString(); api.GetAccessToken(code); LogHelper.Info("access_token:" + api.access_token); string user_json = api.GetUserInfo(api.openid); LogHelper.Info("user_json:" + user_json); JObject obj = JObject.Parse(user_json); string openid = obj["openid"] == null ? "" : obj["openid"].ToString(); LogHelper.Info("openid:" + openid); BaseBLL <weixin_applet> weixinAppletBll = new BaseBLL <weixin_applet>(); weixin_applet weixinApplet = weixinAppletBll.Find(x => x.appcode == "ZHIYIN"); weixin_user userInfo = new weixin_user { openid = obj["openid"] == null ? "" : obj["openid"].ToString(), unionid = obj["unionid"] == null ? "" : obj["unionid"].ToString(), nickname = obj["nickname"] == null ? "" : obj["nickname"].ToString(), sex = obj["sex"] == null ? 0 : int.Parse(obj["sex"].ToString()), language = obj["language"] == null ? "" : obj["language"].ToString(), city = obj["city"] == null ? "" : obj["city"].ToString(), province = obj["province"] == null ? "" : obj["province"].ToString(), country = obj["country"] == null ? "" : obj["country"].ToString(), headimgurl = obj["headimgurl"] == null ? "" : obj["headimgurl"].ToString(), source_code = weixinApplet.appcode, weixin_applet_id = weixinApplet.id }; if (!Util.isNotNull(openid)) { return(new ApiResult() { success = false, message = "openid为空" }); } #region 微信登陆,保存信息 //如果不存在则要创建,创建时,先创建 iuser ,再创建 weixin_user bool first_login = false; BaseBLL <weixin_user> weixinUserBll = new BaseBLL <weixin_user>(); if (Util.isNotNull(userInfo.unionid)) { var weixinUser = weixinUserBll.Find(o => o.unionid == userInfo.unionid); //可能是第一次登陆,在网页端登陆 if (weixinUser == null) { //微信开发平台的openid与小程序的openid不一致 //var _weixin_user = weixinUserBll.Find(o => o.nickname == userInfo.nickname); first_login = true; //先存iuser var iuser = new iuser(); BaseBLL <iuser> iuserBll = new BaseBLL <iuser>(); iuser.random = sys.getRandomStr(); iuser.createtime = DateTime.Now; iuser.updatetime = DateTime.Now; iuser = iuserBll.Add(iuser); //再存weixin_user userInfo.uid = iuser.id; userInfo.sub_time = DateTime.Now; userInfo.first_sub_time = DateTime.Now; LogHelper.Info("first_login:"******",userInfo:" + Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUser = weixinUserBll.Add(userInfo); } else { weixinUser.nickname = userInfo.nickname; weixinUser.headimgurl = userInfo.headimgurl; LogHelper.Info("first_login:"******",userInfo:" + Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUserBll.Update(weixinUser); } apiResult.success = true; apiResult.data = new { first_login = first_login, weixinUser = weixinUser }; apiResult.status = ApiStatusCode.OK; } else { return(new ApiResult() { success = false, message = "微信开发平台未获取到unionid" }); } #endregion //} //else //{ // return new ApiResult() // { // success = false, // message = "请求超时" // }; //} return(apiResult); }