public GARun( int ai_recpergen, string as_path, int ai_poolsize, int ai_generations, double ad_modifyprob, double ad_recomprob, Selectors aen_selector, Recombinators aen_recomb, Randoms aen_random, int ai_elites = 1, int ai_ts_contestants = 2, bool ab_adaptivemut = true, bool ab_rog = false, bool ab_lrog = true ) { ii_recpergen = ai_recpergen; ii_path = as_path; ii_poolsize = ai_poolsize; ii_generations = ai_generations; id_modifyprob = ad_modifyprob; id_recomprob = ad_recomprob; ien_selector = aen_selector; ien_recomb = aen_recomb; ien_random = aen_random; ii_elites = ai_elites; ii_ts_contestants = ai_ts_contestants; ib_adaptivemut = ab_adaptivemut; ib_rog = ab_rog; ib_lrog = ab_lrog; id = id + 1; myid = id; }
public MainForm() { InitializeComponent(); randoms = new Randoms(); randoms.Init(); figureManager = new FigureManager(PictureBox, FigureTree); }
private byte[] GenerateSalt() { return(Randoms.GenerateRandom(LenghtSalt)); }
private string GenerateServerNonce() { var random = Randoms.GenerateRandom(LenghtServerNonce); return(Convert.ToBase64String(random)); }
private void IncrementGains() { // The upper bound is exclusive while the lower is inclusive. // Curvature radius can not be changed as long as AC2F is active. var gainChoice = Randoms.Next(0, (_experimentDataManager._redirectionManager._currentActiveRedirectionAlgorithmType == RedirectionAlgorithms.AC2F) ? 2 : 3); var newGain = 0f; if (gainChoice == 0) { newGain = Mathf.Clamp(_experimentDataManager._redirectionManager.MIN_ROT_GAIN - _rotationGainBaseIncrement + UtilitiesER.Remap(0, 1, -_rotationGainIncrementNoise, _rotationGainIncrementNoise, (float)Randoms.NextDouble()), _maximumNegativeGain, 0); _experimentDataManager._redirectionManager.MIN_ROT_GAIN = newGain; } else if (gainChoice == 1) { newGain = Mathf.Clamp(_experimentDataManager._redirectionManager.MAX_ROT_GAIN + _rotationGainBaseIncrement + UtilitiesER.Remap(0, 1, -_rotationGainIncrementNoise, _rotationGainIncrementNoise, (float)Randoms.NextDouble()), 0, _maximumPositiveGain); _experimentDataManager._redirectionManager.MAX_ROT_GAIN = newGain; } else { newGain = Mathf.Clamp(_experimentDataManager._redirectionManager.CURVATURE_RADIUS - _curvatureRadiusBaseIncrement + UtilitiesER.Remap(0, 1, -_curvatureRadiusIncrementNoise, _curvatureRadiusIncrementNoise, (float)Randoms.NextDouble()), _minimumCurvatureRadius, 1000); _experimentDataManager._redirectionManager.CURVATURE_RADIUS = newGain; } }
private void GenerateRandomTimeStep() { _currentTimestep = _timeStepBase + UtilitiesER.Remap(0, 1, -_timeStepNoise, _timeStepNoise, (float)Randoms.NextDouble()); }
/// <summary> /// 设置用户信息 /// </summary> /// <param name="input"></param> /// <returns></returns> public async Task <SetUserOutput> SetUser(SetUserInput input) { try { _dbContext.Ado.BeginTran(); var model = _mapper.Map <SetUserInput, UserInfo>(input); if (model.Id > 0) { model.UpdateTime = DateTime.Now; if (!model.Password.IsEmpty()) { model.Salt = Randoms.CreateRandomValue(8, false); model.Password = Encrypt.SHA256(model.Password + model.Salt); // 基础字段不容许更新 await _dbContext.Updateable(model) .IgnoreColumns(it => new { it.UserName, it.Mobile, it.CreateTime }) .ExecuteCommandAsync(); } else { // 基础字段不容许更新 await _dbContext.Updateable(model) .IgnoreColumns(it => new { it.UserName, it.Password, it.Salt, it.Mobile, it.CreateTime }) .ExecuteCommandAsync(); } } else { model.CreateTime = DateTime.Now; model.UpdateTime = DateTime.Now; model.Salt = Randoms.CreateRandomValue(8, false); model.Password = Encrypt.SHA256(model.Password + model.Salt); model.Id = Convert.ToInt64($"{Time.GetUnixTimestamp()}{ Randoms.CreateRandomValue(3, true) }"); await _dbContext.Insertable(model).ExecuteCommandAsync(); } // 用户角色操作 List <UserRoleInfo> userRoleList = new List <UserRoleInfo>(); foreach (var id in input.RoleIdList) { // 防止重复数据 if (!userRoleList.Exists(it => it.RoleId == id)) { userRoleList.Add(new UserRoleInfo { Uid = model.Id, RoleId = id }); } } // 删除用户当前角色 await _dbContext.Deleteable <UserRoleInfo>().Where(f => f.Uid == model.Id).ExecuteCommandAsync(); // 添加用户角色 if (userRoleList.Count > 0) { await _dbContext.Insertable(userRoleList).ExecuteCommandAsync(); } _dbContext.Ado.CommitTran(); } catch (Exception ex) { _dbContext.Ado.RollbackTran(); throw new Exception("事务执行失败", ex); } return(new SetUserOutput { }); }
/// <summary> /// 支付 /// </summary> public ActionResult Pay() { //订单id列表 string oidList = WebHelper.GetQueryString("oidList"); decimal allSurplusMoney = 0M; List <OrderInfo> orderList = new List <OrderInfo>(); foreach (string oid in StringHelper.SplitString(oidList)) { //订单信息 OrderInfo orderInfo = Orders.GetOrderByOid(TypeHelper.StringToInt(oid)); if (orderInfo != null && orderInfo.OrderState == (int)OrderState.WaitPaying && orderInfo.PayMode == 1) { orderList.Add(orderInfo); } else { return(Redirect("/mob")); } allSurplusMoney += orderInfo.SurplusMoney; } if (orderList.Count < 1 || allSurplusMoney == 0M) { return(Redirect("/mob")); } //支付类型 string payment_type = "1"; //服务器异步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数 string notify_url = string.Format("http://{0}/mob/alipay/notify", BMAConfig.MallConfig.SiteUrl); //页面跳转同步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/ string return_url = string.Format("http://{0}/mob/alipay/return", BMAConfig.MallConfig.SiteUrl); //商户订单号 string out_trade_no = oidList + Randoms.CreateRandomValue(10, false); //商户网站订单系统中唯一订单号,必填 //订单名称 string subject = BMAConfig.MallConfig.SiteTitle + "购物"; //必填 //付款金额 string total_fee = allSurplusMoney.ToString(); //必填 //商品展示地址 string show_url = string.Format("http://{0}/images/alipay.jgp", BMAConfig.MallConfig.SiteUrl); //必填,需以http://开头的完整路径,例如:http://www.商户网址.com/myorder.html //订单描述 string body = ""; //选填 //超时时间 string it_b_pay = ""; //选填 //钱包token string extern_token = ""; //选填 //////////////////////////////////////////////////////////////////////////////////////////////// //把请求参数打包成数组 SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>(); sParaTemp.Add("partner", Config.Partner); sParaTemp.Add("seller_id", Config.Seller_id); sParaTemp.Add("_input_charset", Config.Input_charset.ToLower()); sParaTemp.Add("service", "alipay.wap.create.direct.pay.by.user"); sParaTemp.Add("payment_type", payment_type); sParaTemp.Add("notify_url", notify_url); sParaTemp.Add("return_url", return_url); sParaTemp.Add("out_trade_no", out_trade_no); sParaTemp.Add("subject", subject); sParaTemp.Add("total_fee", total_fee); sParaTemp.Add("show_url", show_url); sParaTemp.Add("body", body); sParaTemp.Add("it_b_pay", it_b_pay); sParaTemp.Add("extern_token", extern_token); //建立请求 string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认"); return(Content(sHtmlText)); }
/// <summary> /// 支付 /// </summary> public ActionResult Pay() { //订单id列表 string oidList = WebHelper.GetQueryString("oidList"); decimal allSurplusMoney = 0M; List <OrderInfo> orderList = new List <OrderInfo>(); foreach (string oid in StringHelper.SplitString(oidList)) { //订单信息 OrderInfo orderInfo = Orders.GetOrderByOid(TypeHelper.StringToInt(oid)); if (orderInfo != null && orderInfo.OrderState == (int)OrderState.WaitPaying && orderInfo.PayMode == 1) { orderList.Add(orderInfo); } else { return(Content("")); } allSurplusMoney += orderInfo.SurplusMoney; } if (orderList.Count < 1 || allSurplusMoney == 0M) { return(Content("")); } //支付类型,必填,不能修改 string paymentType = "1"; //服务器异步通知页面路径,需http://格式的完整路径,不能加?id=123这类自定义参数 string notifyUrl = string.Format("http://{0}/app/alipay/notify", BMAConfig.MallConfig.SiteUrl); //收款支付宝帐户 string sellerEmail = AlipayConfig.Seller; //合作者身份ID string partner = AlipayConfig.Partner; //交易安全检验码 string key = AlipayConfig.Key; //商户订单号 string outTradeNo = oidList + Randoms.CreateRandomValue(10, false); //订单名称 string subject = BMAConfig.MallConfig.SiteTitle + "购物"; //付款金额 string totalFee = allSurplusMoney.ToString(); //订单描述 string body = ""; Encoding e = Encoding.GetEncoding(AlipayConfig.AppInputCharset); //把请求参数打包成数组 SortedDictionary <string, string> parms = new SortedDictionary <string, string>(); parms.Add("partner", partner); parms.Add("seller_id", sellerEmail); parms.Add("out_trade_no", outTradeNo); parms.Add("subject", subject); parms.Add("body", body); parms.Add("total_fee", totalFee); parms.Add("notify_url", notifyUrl); parms.Add("service", "mobile.securitypay.pay"); parms.Add("payment_type", paymentType); parms.Add("_input_charset", AlipayConfig.AppInputCharset); parms.Add("it_b_pay", "30m"); parms.Add("show_url", "m.alipay.com"); string sign = AlipayRSAFromPkcs8.sign(AlipayCore.CreateLinkString(AlipayCore.FilterPara(parms)), AlipayConfig.PrivateKey, AlipayConfig.AppInputCharset); parms.Add("sign", HttpUtility.UrlEncode(sign, e)); parms.Add("sign_type", AlipayConfig.AppSignType); Dictionary <string, string> dicArray = new Dictionary <string, string>(); foreach (KeyValuePair <string, string> temp in parms) { dicArray.Add(temp.Key, temp.Value); } string content = AlipayCore.CreateLinkString(dicArray); return(Content("{ \"orderString\":\"" + content + "\" }")); }
/// <summary> /// 验证找回密码手机 /// </summary> public ActionResult VerifyFindPwdMobile() { int uid = WebHelper.GetQueryInt("uid"); string mobileCode = WebHelper.GetFormString("mobileCode"); PartUserInfo partUserInfo = Users.GetPartUserById(uid); if (partUserInfo == null) { return(AjaxResult("nouser", "用户不存在")); } if (partUserInfo.Mobile.Length == 0) { return(AjaxResult("nocanfind", "由于您没有设置手机,所以不能通过手机找回此账号的密码")); } //检查手机码 if (string.IsNullOrWhiteSpace(mobileCode)) { return(AjaxResult("emptymobilecode", "手机验证码不能为空")); } else if (Sessions.GetValueString(WorkContext.Sid, "findPwdMoibleCode") != mobileCode) { return(AjaxResult("wrongmobilecode", "手机验证码不正确")); } string v = MallUtils.AESEncrypt(string.Format("{0},{1},{2}", partUserInfo.Uid, DateTime.Now, Randoms.CreateRandomValue(6))); string url = string.Format("http://{0}{1}", Request.Url.Authority, Url.Action("resetpwd", new RouteValueDictionary { { "v", v } })); return(AjaxResult("success", url)); }
protected override void GameStart() { Log.mDebugLevel = 1; Randoms.init(); Randoms.lookId = 1001;//监视该物品掉落概率 }
/// <summary> /// 支付 /// </summary> public ActionResult Pay() { /*微信支付三步:统一下单》调起支付接口》支付结果通知*/ string result = WebHelper.GetPostStr(); NameValueCollection parmas = WebHelper.GetParmList(result); //if (parmas.Keys.Count < 5) //{ // return AjaxResult("error", "缺少请求参数"); //} #region 支付操作============================ #region 基本参数=========================== //商户订单号 string outTradeNo = "hmk" + DateTime.Now.ToString("yyMMdd") + Randoms.CreateRandomValue(6, true); //订单名称 string subject = BSPConfig.ShopConfig.SiteTitle; //付款金额 string totalFee = (double.Parse(parmas["totalfee"]) * 100).ToString(); //时间戳 string timeStamp = TenpayUtil.getTimestamp(); //随机字符串 string nonceStr = TenpayUtil.getNoncestr(); //服务器异步通知页面路径 string notifyUrl = string.Format("{0}/appwechat/notify", BSPConfig.ShopConfig.SiteUrl); //记录充值信息 OWZX.Model.RechargeModel rech = new OWZX.Model.RechargeModel { Out_trade_no = outTradeNo, Account = parmas["account"], SuiteId = parmas["vossuiteid"], PlatForm = "微信", Type = int.Parse(parmas["type"]), Role = int.Parse(parmas["role"]) }; bool addres = Recharge.AddRecharge(rech); if (!addres) { return(AjaxResult("error", "记录充值信息失败")); } //string access_token = ""; //string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", PayConfig.AppId, PayConfig.AppSecret); //string returnStr = HttpUtil.Get_Http(url, 120000); //LogUtil.WriteLog("returnStr 页面 returnStr:" + returnStr); //if (!returnStr.Contains("access_token")) //{ // return Content(""); //} //else //{ // string[] list = returnStr.Split(','); // access_token = list[0].Split(':')[1].Trim('"'); //} //LogUtil.WriteLog("access_token 页面 access_token:" + access_token); //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(System.Web.HttpContext.Current); //初始化 packageReqHandler.init(); //设置package订单参数 具体参数列表请参考官方pdf文档,请勿随意设置 packageReqHandler.setParameter("appid", PayConfig.AppId); packageReqHandler.setParameter("body", subject); //商品信息 127字符 packageReqHandler.setParameter("mch_id", PayConfig.MchId); packageReqHandler.setParameter("nonce_str", nonceStr.ToLower()); packageReqHandler.setParameter("notify_url", notifyUrl); packageReqHandler.setParameter("out_trade_no", outTradeNo); //商家订单号 packageReqHandler.setParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.setParameter("total_fee", totalFee); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.setParameter("trade_type", "APP"); //if (!string.IsNullOrEmpty(this.Attach)) // packageReqHandler.setParameter("attach", this.Attach);//自定义参数 127字符 #endregion #region sign=============================== string sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey); #endregion #region 获取package包====================== packageReqHandler.setParameter("sign", sign); string data = packageReqHandler.parseXML(); string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder"); //LogUtil.WriteLog("WeiPay 页面 prepayXml:" + prepayXml); //获取预支付ID string prepayId = ""; string package = ""; XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(prepayXml); XmlNode xn = xdoc.SelectSingleNode("xml"); XmlNodeList xnl = xn.ChildNodes; if (xnl.Count > 7) { prepayId = xnl[7].InnerText; package = string.Format("prepay_id={0}", prepayId); //LogUtil.WriteLog("WeiPay 页面 package:" + package); } if (xnl[0].InnerText.Trim() == "FAIL") { return(AjaxResult("error", "微信下单失败 " + xnl[1].InnerText)); } #endregion #region 设置支付参数 输出页面 该部分参数请勿随意修改 ============== nonceStr = TenpayUtil.getNoncestr(); RequestHandler paySignReqHandler = new RequestHandler(System.Web.HttpContext.Current); paySignReqHandler.setParameter("appid", PayConfig.AppId); paySignReqHandler.setParameter("noncestr", nonceStr.ToLower()); paySignReqHandler.setParameter("package", "Sign=WXPay"); paySignReqHandler.setParameter("partnerid", PayConfig.MchId); paySignReqHandler.setParameter("prepayid", prepayId); paySignReqHandler.setParameter("timestamp", timeStamp); string paySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey); //LogUtil.WriteLog("WeiPay 页面 paySign:" + paySign); #endregion #endregion return(AjaxResult("success", string.Format("{0}\"appId\":\"{1}\",\"partnerId\":\"{2}\",\"prepayId\":\"{3}\",\"package\":\"{4}\",\"nonceStr\":\"{5}\",\"timeStamp\":\"{6}\",\"sign\":\"{7}\"{8}", "{", PayConfig.AppId, PayConfig.MchId, prepayId, "Sign=WXPay", nonceStr.ToLower(), timeStamp, paySign, "}"), true)); }
/// <summary> /// 登录 /// </summary> public ActionResult Login() { string returnUrl = WebHelper.GetQueryString("returnUrl"); if (returnUrl.Length == 0) { //returnUrl = WorkContext.SubPath + "/malladmin/home/default"; //默认去后台页面 string subpath = Request.ApplicationPath; if (subpath.Equals("/")) { subpath = ""; } returnUrl = subpath + "/malladmin/home/default"; //默认去后台页面 } if (WorkContext.MallConfig.LoginType == "") { return(PromptView(returnUrl, "系统目前已经关闭登录功能!")); } if (WorkContext.Uid > 0) { return(PromptView(returnUrl, "您已经登录,无须重复登录!")); } //get请求 if (WebHelper.IsGet()) { LoginViewModel model = new LoginViewModel(); model.ReturnUrl = returnUrl; model.ShadowName = WorkContext.MallConfig.ShadowName; model.IsRemember = WorkContext.MallConfig.IsRemember == 1; model.IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages); //model.OAuthPluginList = Plugins.GetOAuthPluginList(); model.Random = Randoms.GetRandomInt(0, 5); return(View(model)); } //ajax请求 string accountName = WebHelper.GetFormString("shadowName"); //WebHelper.GetFormString(WorkContext.MallConfig.ShadowName); string password = WebHelper.GetFormString("password"); string verifyCode = WebHelper.GetFormString("verifyCode"); int isRemember = WebHelper.GetFormInt("isRemember"); StringBuilder errorList = new StringBuilder("["); //验证账户名 if (string.IsNullOrWhiteSpace(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}"); } else if (accountName.Length < 4 || accountName.Length > 50) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}"); } else if ((!SecureHelper.IsSafeSqlString(accountName, false))) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不存在", "}"); } //验证密码 if (string.IsNullOrWhiteSpace(password)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不能为空", "}"); } else if (password.Length < 4 || password.Length > 32) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码必须大于3且不大于32个字符", "}"); } //验证验证码 if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages)) { if (string.IsNullOrWhiteSpace(verifyCode)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}"); } else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}"); } } //当以上验证全部通过时 xpGrid_User PartUserInfo xpGrid_User partUserInfo = null; if (errorList.Length == 1) { //用户名登录 if (!BMAConfig.MallConfig.LoginType.Contains("1")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用用户名登录", "}"); } else { partUserInfo = Users.GetUserByName(accountName); if (partUserInfo == null) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名不存在", "}"); } } if (partUserInfo != null) { if (password != partUserInfo.Password)//判断密码是否正确 { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不正确", "}"); } else if (partUserInfo.deleted == 1)//当用户等级是禁止访问等级时 { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "您的账号当前被锁定,不能访问", "}"); } } } if (errorList.Length > 1)//验证失败时 { return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true)); } else//验证成功时 { //将用户信息写入cookie中 MallUtils.SetUserCookie(partUserInfo, (WorkContext.MallConfig.IsRemember == 1 && isRemember == 1) ? 30 : -1); //return Redirect(returnUrl); //登录成功,直接转向 return(AjaxResult("success", returnUrl)); } }
/// <summary> /// 注册 /// </summary> public ActionResult Register() { try { //if (WorkContext.ShopConfig.RegTimeSpan > 0) //{ // DateTime registerTime = Users.GetRegisterTimeByRegisterIP(WorkContext.IP); // if ((DateTime.Now - registerTime).Minutes <= WorkContext.ShopConfig.RegTimeSpan) // return APIResult("error", "你注册太频繁,请间隔一定时间后再注册!"); //} NameValueCollection parmas = WorkContext.postparms; if (parmas.Keys.Count != 3) { return(APIResult("error", "缺少请求参数")); } //ajax请求 string phone = string.Empty; string account = phone = parmas["account"].Trim(); int userid = Users.GetUidByMobile(account); if (userid > 0) { return(APIResult("error", "账号已存在")); } int invitecode = -1; if (parmas.AllKeys.Contains("invitecode")) { invitecode = int.Parse(parmas["invitecode"]); //介绍用户标识号 } string password = parmas["password"]; string imei = parmas["imei"]; UserInfo userInfo = null; userInfo = new UserInfo(); userInfo.UserName = account; userInfo.UserId = Randoms.CreateRandomValue(8); userInfo.Email = string.Empty; userInfo.Mobile = phone; userInfo.Salt = Randoms.CreateRandomValue(6); userInfo.Password = Users.CreateUserPassword(password, userInfo.Salt); userInfo.UserRid = 7; //普通用户 UserRanks.GetLowestUserRank().UserRid; userInfo.AdminGid = 1; //非管理员组 userInfo.NickName = Randoms.CreateRandomValue(6); userInfo.Avatar = ""; userInfo.PayCredits = 0; userInfo.RankCredits = 0; userInfo.VerifyEmail = 0; userInfo.VerifyMobile = 0; userInfo.LastVisitIP = WorkContext.IP; userInfo.LastVisitRgId = WorkContext.RegionId; userInfo.LastVisitTime = DateTime.Now; userInfo.RegisterIP = WorkContext.IP; userInfo.RegisterRgId = WorkContext.RegionId; userInfo.RegisterTime = DateTime.Now; userInfo.Gender = WebHelper.GetFormInt("gender"); userInfo.RealName = WebHelper.HtmlEncode(WebHelper.GetFormString("realName")); userInfo.Bday = new DateTime(1900, 1, 1); userInfo.IdCard = WebHelper.GetFormString("idCard"); userInfo.RegionId = WebHelper.GetFormInt("regionId"); userInfo.Address = WebHelper.HtmlEncode(WebHelper.GetFormString("address")); userInfo.Bio = WebHelper.HtmlEncode(WebHelper.GetFormString("bio")); userInfo.InviteCode = invitecode; userInfo.IMEI = imei; //创建用户 userInfo.Uid = Users.CreateUser(userInfo); //添加用户失败 if (userInfo.Uid < 1) { return(APIResult("error", "注册失败")); } return(APIResult("success", "注册成功")); } catch (Exception ex) { Logs.Write("注册失败:" + ex.Message); return(APIResult("error", "注册失败")); } }
/// <summary> /// 短息发送 /// </summary> /// <param name="mobile"></param> /// <param name="smsTemplateName"></param> public async Task <string> SendSmsCodeAsync(string mobile, string smsTemplateName) { var errCountKey = string.Format(CacheKeys.SmsCodeVerifyErr, mobile); var sendCountKey = string.Format(CacheKeys.SmsCodeSendIdentity, mobile); var loginCodeKey = string.Format(CacheKeys.SmsCodeLoginCode, mobile); var rediscontect = _config.StringGet("RedisDefaultServer"); var redis = _redisClient.GetDatabase(rediscontect, 5); // 错误次数过多 var errCount = await redis.StringGetAsync(errCountKey); if (!errCount.IsNullOrEmpty && errCount.SafeString().ToInt() > 5) { throw new BucketException("GO_0005055", "登陆错误次数过多,请30分钟后再试"); } // 验证一分钟发一条 if (await redis.KeyExistsAsync(sendCountKey)) { throw new BucketException("GO_2001", "一分钟只能发送一条短信"); } // 生成验证码 string loginCode = Randoms.CreateRandomValue(6, true); // 发送短信 //Dictionary<string, object> dic = new Dictionary<string, object> //{ // { "SmsCode", loginCode } //}; // 短发推送 //_eventBus.Publish(new SmsEvent(dic) //{ // ChannelType = 0, // MobIp = Web.Ip, // Sender = "6b4b881169e144da9ae93113c0ca41d4", // SmsTemplateId = 2, // SmsTemplateName = smsTemplateName, // Source = "品值GO用户登陆项目", // Mob = mobile, //}); // 基础键值 // @event.MobIp.Split(',')[0] 当多层代理时x-forwarded-for多ip Dictionary <string, object> dic = new Dictionary <string, object> { { "channelType", "0" }, { "smsTemplateId", "2" }, { "smsTemplateName", smsTemplateName }, { "source", "品值GO用户登陆项目" }, { "sender", "6b4b881169e144da9ae93113c0ca41d4" }, { "mobIp", Web.Ip.Split(',')[0] }, { "mob", mobile }, { "SmsCode", loginCode } }; var body = JsonConvert.SerializeObject(dic); var apiUrl = _config.StringGet("SmsApiUrl"); var client = _httpClientFactory.CreateClient(); var response = await client.PostAsync(apiUrl, new StringContent(body, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode(); // 验证码缓存 await redis.StringSetAsync(loginCodeKey, loginCode, new TimeSpan(0, 0, 0, 300)); // 发送人缓存(60秒发一次) await redis.StringSetAsync(sendCountKey, loginCode, new TimeSpan(0, 0, 0, 60)); return(loginCode); }
/// <summary> /// 注册 /// </summary> public ActionResult Register() { string returnUrl = WebHelper.GetQueryString("returnUrl"); if (returnUrl.Length == 0) { returnUrl = Url.Action("index", "home"); } if (WorkContext.MallConfig.RegType.Length == 0) { return(PromptView(returnUrl, "商城目前已经关闭注册功能!")); } if (WorkContext.Uid > 0) { return(PromptView(returnUrl, "你已经是本商城的注册用户,无需再注册!")); } if (WorkContext.MallConfig.RegTimeSpan > 0) { DateTime registerTime = Users.GetRegisterTimeByRegisterIP(WorkContext.IP); if ((DateTime.Now - registerTime).Minutes <= WorkContext.MallConfig.RegTimeSpan) { return(PromptView(returnUrl, "你注册太频繁,请间隔一定时间后再注册!")); } } //get请求 if (WebHelper.IsGet()) { RegisterModel model = new RegisterModel(); model.ReturnUrl = returnUrl; model.ShadowName = WorkContext.MallConfig.ShadowName; model.IsVerifyCode = CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages); return(View(model)); } //ajax请求 string accountName = WebHelper.GetFormString(WorkContext.MallConfig.ShadowName).Trim().ToLower(); string password = WebHelper.GetFormString("password"); string confirmPwd = WebHelper.GetFormString("confirmPwd"); string verifyCode = WebHelper.GetFormString("verifyCode"); StringBuilder errorList = new StringBuilder("["); #region 验证 //账号验证 if (string.IsNullOrWhiteSpace(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名不能为空", "}"); } else if (accountName.Length < 4 || accountName.Length > 50) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名必须大于3且不大于50个字符", "}"); } else if (accountName.Contains(" ")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含空格", "}"); } else if (accountName.Contains(":")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含冒号", "}"); } else if (accountName.Contains("<")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'<'符号", "}"); } else if (accountName.Contains(">")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名中不允许包含'>'符号", "}"); } else if ((!SecureHelper.IsSafeSqlString(accountName))) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名已经存在", "}"); } else if (CommonHelper.IsInArray(accountName, WorkContext.MallConfig.ReservedName, "\n")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名已经存在", "}"); } else if (FilterWords.IsContainWords(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "账户名包含禁止单词", "}"); } //密码验证 if (string.IsNullOrWhiteSpace(password)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码不能为空", "}"); } else if (password.Length < 4 || password.Length > 32) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "密码必须大于3且不大于32个字符", "}"); } else if (password != confirmPwd) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "password", "两次输入的密码不一样", "}"); } //验证码验证 if (CommonHelper.IsInArray(WorkContext.PageKey, WorkContext.MallConfig.VerifyPages)) { if (string.IsNullOrWhiteSpace(verifyCode)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不能为空", "}"); } else if (verifyCode.ToLower() != Sessions.GetValueString(WorkContext.Sid, "verifyCode")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "verifyCode", "验证码不正确", "}"); } } //其它验证 int gender = WebHelper.GetFormInt("gender"); if (gender < 0 || gender > 2) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "gender", "请选择正确的性别", "}"); } string nickName = WebHelper.GetFormString("nickName"); if (nickName.Length > 10) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称的长度不能大于10", "}"); } else if (FilterWords.IsContainWords(nickName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "nickName", "昵称中包含禁止单词", "}"); } if (WebHelper.GetFormString("realName").Length > 5) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "realName", "真实姓名的长度不能大于5", "}"); } string bday = WebHelper.GetFormString("bday"); if (bday.Length == 0) { string bdayY = WebHelper.GetFormString("bdayY"); string bdayM = WebHelper.GetFormString("bdayM"); string bdayD = WebHelper.GetFormString("bdayD"); bday = string.Format("{0}-{1}-{2}", bdayY, bdayM, bdayD); } if (bday.Length > 0 && bday != "--" && !ValidateHelper.IsDate(bday)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bday", "请选择正确的日期", "}"); } string idCard = WebHelper.GetFormString("idCard"); if (idCard.Length > 0 && !ValidateHelper.IsIdCard(idCard)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "idCard", "请输入正确的身份证号", "}"); } int regionId = WebHelper.GetFormInt("regionId"); if (regionId > 0) { if (Regions.GetRegionById(regionId) == null) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "regionId", "请选择正确的地址", "}"); } if (WebHelper.GetFormString("address").Length > 75) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "address", "详细地址的长度不能大于75", "}"); } } if (WebHelper.GetFormString("bio").Length > 150) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "bio", "简介的长度不能大于150", "}"); } //当以上验证都通过时 UserInfo userInfo = null; if (errorList.Length == 1) { if (WorkContext.MallConfig.RegType.Contains("2") && ValidateHelper.IsEmail(accountName))//验证邮箱 { string emailProvider = CommonHelper.GetEmailProvider(accountName); if (WorkContext.MallConfig.AllowEmailProvider.Length != 0 && (!CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.AllowEmailProvider, "\n"))) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}"); } else if (CommonHelper.IsInArray(emailProvider, WorkContext.MallConfig.BanEmailProvider, "\n")) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "不能使用'" + emailProvider + "'类型的邮箱", "}"); } else if (Users.IsExistEmail(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "邮箱已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = string.Empty; userInfo.Email = accountName; userInfo.Mobile = string.Empty; } } else if (WorkContext.MallConfig.RegType.Contains("3") && ValidateHelper.IsMobile(accountName))//验证手机 { if (Users.IsExistMobile(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "手机号已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = string.Empty; userInfo.Email = string.Empty; userInfo.Mobile = accountName; } } else if (WorkContext.MallConfig.RegType.Contains("1"))//验证用户名 { if (BrnMall.Services.Users.IsExistUserName(accountName)) { errorList.AppendFormat("{0}\"key\":\"{1}\",\"msg\":\"{2}\"{3},", "{", "accountName", "用户名已经存在", "}"); } else { userInfo = new UserInfo(); userInfo.UserName = accountName; userInfo.Email = string.Empty; userInfo.Mobile = string.Empty; } } } #endregion if (errorList.Length > 1)//验证失败 { return(AjaxResult("error", errorList.Remove(errorList.Length - 1, 1).Append("]").ToString(), true)); } else//验证成功 { #region 绑定用户信息 userInfo.Salt = Randoms.CreateRandomValue(6); userInfo.Password = Users.CreateUserPassword(password, userInfo.Salt); userInfo.UserRid = UserRanks.GetLowestUserRank().UserRid; userInfo.StoreId = 0; userInfo.MallAGid = 1;//非管理员组 if (nickName.Length > 0) { userInfo.NickName = WebHelper.HtmlEncode(nickName); } else { userInfo.NickName = "bma" + Randoms.CreateRandomValue(7); } userInfo.Avatar = ""; userInfo.PayCredits = 0; userInfo.RankCredits = 0; userInfo.VerifyEmail = 0; userInfo.VerifyMobile = 0; userInfo.LastVisitIP = WorkContext.IP; userInfo.LastVisitRgId = WorkContext.RegionId; userInfo.LastVisitTime = DateTime.Now; userInfo.RegisterIP = WorkContext.IP; userInfo.RegisterRgId = WorkContext.RegionId; userInfo.RegisterTime = DateTime.Now; userInfo.Gender = WebHelper.GetFormInt("gender"); userInfo.RealName = WebHelper.HtmlEncode(WebHelper.GetFormString("realName")); userInfo.Bday = bday.Length > 0 ? TypeHelper.StringToDateTime(bday) : new DateTime(1900, 1, 1); userInfo.IdCard = WebHelper.GetFormString("idCard"); userInfo.RegionId = WebHelper.GetFormInt("regionId"); userInfo.Address = WebHelper.HtmlEncode(WebHelper.GetFormString("address")); userInfo.Bio = WebHelper.HtmlEncode(WebHelper.GetFormString("bio")); #endregion //创建用户 userInfo.Uid = Users.CreateUser(userInfo); //添加用户失败 if (userInfo.Uid < 1) { return(AjaxResult("exception", "创建用户失败,请联系管理员")); } //发放注册积分 Credits.SendRegisterCredits(ref userInfo, DateTime.Now); //更新购物车中用户id Carts.UpdateCartUidBySid(userInfo.Uid, WorkContext.Sid); //将用户信息写入cookie MallUtils.SetUserCookie(userInfo, 0); //发送注册欢迎信息 if (WorkContext.MallConfig.IsWebcomeMsg == 1) { if (userInfo.Email.Length > 0) { Emails.SendWebcomeEmail(userInfo.Email); } if (userInfo.Mobile.Length > 0) { SMSes.SendWebcomeSMS(userInfo.Mobile); } } //同步上下午 WorkContext.Uid = userInfo.Uid; WorkContext.UserName = userInfo.UserName; WorkContext.UserEmail = userInfo.Email; WorkContext.UserMobile = userInfo.Mobile; WorkContext.NickName = userInfo.NickName; return(AjaxResult("success", "注册成功")); } }
public void init( GARun ao_run, ref Wrapper ao_wrapper ) { io_wrapper = ao_wrapper; io_run = ao_run; ii_recpergen = ao_run.ii_recpergen; ii_path = ao_run.ii_path; ii_poolsize = ao_run.ii_poolsize; ii_generations = ao_run.ii_generations; id_modifyprob = ao_run.id_modifyprob; id_recomprob = ao_run.id_recomprob; ien_selector = ao_run.ien_selector; ien_recomb = ao_run.ien_recomb; ien_random = ao_run.ien_random; ii_elites = ao_run.ii_elites; ii_ts_contestants = ao_run.ii_ts_contestants; ib_adaptivemut = ao_run.ib_adaptivemut; ib_rog = ao_run.ib_rog; ib_lrog = ao_run.ib_lrog; ida_starttime = new DateTime(); }
/// <summary> /// 发送找回密码邮件 /// </summary> public ActionResult SendFindPwdEmail() { int uid = WebHelper.GetQueryInt("uid"); PartUserInfo partUserInfo = Users.GetPartUserById(uid); if (partUserInfo == null) { return(AjaxResult("nouser", "用户不存在")); } if (partUserInfo.Email.Length == 0) { return(AjaxResult("nocanfind", "由于您没有设置邮箱,所以不能通过邮箱找回此账号的密码")); } //发送找回密码邮件 string v = MallUtils.AESEncrypt(string.Format("{0},{1},{2}", partUserInfo.Uid, DateTime.Now, Randoms.CreateRandomValue(6))); string url = string.Format("http://{0}{1}", Request.Url.Authority, Url.Action("resetpwd", new RouteValueDictionary { { "v", v } })); Emails.SendFindPwdEmail(partUserInfo.Email, partUserInfo.UserName, url); return(AjaxResult("success", "邮件已发送,请查收")); }
public void SendMessage(string content) { GameSession.LastActiveTime = DateTime.Now; string messagePacket = ""; var packet = content.Replace("@", "%").Split('%'); var roomId = packet[1]; var message = packet[2]; var cmd = message.Split(' ')[0]; if (message.StartsWith("/reconnect")) { ShutdownConnection(); } else if (cmd == "/w") { var userName = message.Split(' ')[1]; if (userName.ToLower() == GameSession.Player.Name.ToLower()) { Send("fk%" + roomId + "@" + "Kendine fısıldayamazsın." + "#"); return; } if (GameManager.GetPlayerByName(userName) == null) { Send("ct%#"); return; } foreach (var user in ServerManager.ChatClients.Values) { if (string.Equals(user.GameSession.Player.Name.ToLower(), userName.ToLower(), StringComparison.CurrentCultureIgnoreCase) && user.ChatsJoined.Contains(Convert.ToInt32(roomId))) { message = message.Remove(0, userName.Length + 4); user.Send("cv%" + GameSession.Player.Name + "@" + message + "#"); Send("cw%" + userName + "@" + message + "#"); } } } else if (cmd == "/kick" && (Permission == Permissions.ADMINISTRATOR || Permission == Permissions.CHAT_MODERATOR)) { var userName = message.Split(' ')[1]; var player = GameManager.GetPlayerByName(userName); if (player != null && player.GameSession.Chat.Permission != Permissions.ADMINISTRATOR && userName != GameSession.Player.Name) { var chatClient = player.GameSession.Chat; if (chatClient != null) { chatClient.Send("as%#"); ShutdownConnection(); } } } else if (cmd == "/duel" && Permission == Permissions.ADMINISTRATOR) { var userName = message.Split(' ')[1]; var duelPlayer = GameManager.GetPlayerByName(userName); if (duelPlayer == null || duelPlayer == GameSession.Player) { return; } var duelId = Randoms.CreateRandomID(); Send($"cr%{duelPlayer.Name}#"); GameSession.Player.Storage.DuelInvites.Add(duelId, duelPlayer); var chatClient = duelPlayer.GameSession.Chat; chatClient.Send("cj%" + duelId + "@" + "Room" + "@" + GameSession.Player.Id + "@" + GameSession.Player.Name + "#"); } else if (cmd == "/a" && Permission == Permissions.ADMINISTRATOR) { /* * if (Player.DuelUser != null) * { * if (Player.IsInEquipZone && Player.DuelUser.IsInEquipZone) * { * Player.Jump(101, new Position(700, 3000)); * Player.DuelUser.Jump(101, new Position(9500, 3000)); * } * } * else * { * Send($"dq%Herhangi bir meydan okuman bulunmuyor.#"); * } */ } else if (cmd == "/r" && Permission == Permissions.ADMINISTRATOR) { /* * if (Player.DuelUser != null) * { * var chatClient = Player.DuelUser.GetGameSession().Chat; * Send($"dq%{Player.DuelUser.Name} adlı oyuncunun meydan okumasını reddettin.#"); * chatClient.Send($"dq%{Player.Name} adlı oyuncu meydan okumanı reddetti.#"); * Player.DuelUser = null; * } * else * { * Send($"dq%Herhangi bir meydan okuman bulunmuyor.#"); * } */ } else if (cmd == "/msg" && Permission == Permissions.ADMINISTRATOR) { var msg = message.Remove(0, 4); GameManager.SendPacketToAll($"0|A|STD|{msg}"); } else if (cmd == "/patlat" && Permission == Permissions.ADMINISTRATOR) { var userName = message.Split(' ')[1]; var player = GameManager.GetPlayerByName(userName); if (player != null) { player.Destroy(GameSession.Player, Game.DestructionType.PLAYER); } } else if (cmd == "/ship" && Permission == Permissions.ADMINISTRATOR) { var shipId = Convert.ToInt32(message.Split(' ')[1]); GameSession.Player.Ship = GameManager.GetShip(shipId); GameSession.Player.Jump(GameSession.Player.Spacemap.Id, GameSession.Player.Position); } else if (cmd == "/jump" && Permission == Permissions.ADMINISTRATOR) { var mapId = Convert.ToInt32(message.Split(' ')[1]); GameSession.Player.Jump(mapId, new Position(0, 0)); } else if (cmd == "/speed+" && Permission == Permissions.ADMINISTRATOR) { var speed = Convert.ToInt32(message.Split(' ')[1]); GameSession.Player.SetSpeedBoost(speed); } else if (cmd == "/god" && Permission == Permissions.ADMINISTRATOR) { var mod = message.Split(' ')[1]; switch (mod) { case "on": GameSession.Player.Storage.GodMode = true; break; case "off": GameSession.Player.Storage.GodMode = false; break; } } else if (cmd == "/start_spaceball" && Permission == Permissions.ADMINISTRATOR) { EventManager.Spaceball.Start(); } else if (cmd == "/stop_spaceball" && Permission == Permissions.ADMINISTRATOR) { EventManager.Spaceball.Stop(); } else if (cmd == "/start_jpb" && Permission == Permissions.ADMINISTRATOR) { GameManager.SendPacketToAll($"0|A|STD|System preparing for Jackpot Battle!"); EventManager.JackpotBattle.Start(); } else if (cmd == "/ban" && (Permission == Permissions.ADMINISTRATOR || Permission == Permissions.CHAT_MODERATOR)) { /* * 0 CHAT BAN * 1 OYUN BANI */ var playerName = message.Split(' ')[1]; var typeId = Convert.ToInt32(message.Split(' ')[2]); var day = Convert.ToInt32(message.Split(' ')[3]); var reason = message.Remove(0, playerName.Length + typeId.ToString().Length + day.ToString().Length + 8); if (typeId == 1 && Permission == Permissions.CHAT_MODERATOR) { return; } if (typeId == 0 || typeId == 1) { var player = GameManager.GetPlayerByName(playerName); if (player == null) { return; } //player.SendPacket($"0|A|STD|{day} gün yasaklandın."); player.GameSession.Chat.ShutdownConnection(); QueryManager.ChatFunctions.AddBan(player.Id, GameSession.Player.Id, reason, typeId, (DateTime.Now.AddDays(day)).ToString("yyyy-MM-dd HH:mm:ss.fff")); } } else if (cmd == "/restart" && Permission == Permissions.ADMINISTRATOR) { var seconds = Convert.ToInt32(message.Split(' ')[1]); Restart(seconds); } else if (cmd == "/users") { var users = ServerManager.ChatClients.Values.Aggregate(String.Empty, (current, user) => current + user.GameSession.Player.Name + ", "); users = users.Remove(users.Length - 2); Send($"dq%Users online {ServerManager.ChatClients.Count}: {users}#"); } else { if (!cmd.StartsWith("/")) { foreach (var m in Filter) { if (message.Contains(m)) { Console.WriteLine("BAN, mesaj = " + m); } } foreach (var pair in ServerManager.ChatClients.Values) { if (pair.ChatsJoined.Contains(Convert.ToInt32(roomId))) { if (Permission == Permissions.ADMINISTRATOR || Permission == Permissions.CHAT_MODERATOR) { messagePacket = "j%" + roomId + "@" + GameSession.Player.Name + "@" + message; } else { messagePacket = "a%" + roomId + "@" + GameSession.Player.Name + "@" + message; } if (Clan != "") { messagePacket += "@" + Clan; } pair.Send(messagePacket + "#"); } } } } }
async Task Fire(Vector3 direction, bool byPlayer) { var bulletNode = CreateRigidBullet(byPlayer); bulletNode.Rotation = new Quaternion(-50, 0, 0); bulletNode.SetScale(0.1f); var color = Color.White; var nodeX = bulletNode.CreateChild(); nodeX.Scale = new Vector3(5, 1, 1); var boxX = nodeX.CreateComponent <Box>(); boxX.Color = color; var nodeZ = bulletNode.CreateChild(); nodeZ.Scale = new Vector3(1, 1, 5); var boxZ = nodeZ.CreateComponent <Box>(); boxZ.Color = color; var nodeY = bulletNode.CreateChild(); nodeY.Scale = new Vector3(1, 5, 1); var boxY = nodeY.CreateComponent <Box>(); boxY.Color = color; bulletNode.RunActions(new RepeatForever(new RotateBy(0.2f, Randoms.Next(30, 60), Randoms.Next(30, 60), 0f))); await bulletNode.RunActionsAsync( new MoveBy(5f, direction), new CallFunc(() => bulletNode.SetScale(0f))); //collapse); bulletNode.Remove(); }
void UpdateAnchor(Node node, ARAnchor anchor) { if (anchor is ARPlaneAnchor planeAnchor) { Material tileMaterial = null; Node planeNode = null; if (node == null) { var id = planeAnchor.Identifier.ToString(); node = AnchorsNode.CreateChild(id); planeNode = node.CreateChild("SubPlane"); var plane = planeNode.CreateComponent <StaticModel>(); planeNode.Position = new Vector3(); plane.Model = CoreAssets.Models.Plane; tileMaterial = new Material(); tileMaterial.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/PlaneTile.png")); var tech = new Technique(); var pass = tech.CreatePass("alpha"); pass.DepthWrite = false; pass.BlendMode = BlendMode.Alpha; pass.PixelShader = "PlaneTile"; pass.VertexShader = "PlaneTile"; tileMaterial.SetTechnique(0, tech); tileMaterial.SetShaderParameter("MeshColor", new Color(Randoms.Next(), 1, Randoms.Next())); tileMaterial.SetShaderParameter("MeshAlpha", 0.75f); // set 0.0f if you want to hide them tileMaterial.SetShaderParameter("MeshScale", 32.0f); var planeRb = planeNode.CreateComponent <RigidBody>(); planeRb.Friction = 1.5f; CollisionShape shape = planeNode.CreateComponent <CollisionShape>(); shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity); plane.Material = tileMaterial; } else { planeNode = node.GetChild("SubPlane"); tileMaterial = planeNode.GetComponent <StaticModel>().Material; } ApplyTransform(node, planeAnchor.Transform); planeNode.Scale = new Vector3(planeAnchor.Extent.X, 0.1f, planeAnchor.Extent.Z); planeNode.Position = new Vector3(planeAnchor.Center.X, planeAnchor.Center.Y, -planeAnchor.Center.Z); //var animation = new ValueAnimation(); //animation.SetKeyFrame(0.0f, 0.3f); //animation.SetKeyFrame(0.5f, 0.0f); //tileMaterial.SetShaderParameterAnimation("MeshAlpha", animation, WrapMode.Once, 1.0f); Debug.WriteLine($"ARPlaneAnchor Extent({planeAnchor.Extent}), Center({planeAnchor.Center}), Position({planeAnchor.Transform.Row3}"); } }
public Particle(int n) { Position = Enumerable.Range(0, n).Select(i => Randoms.NextDouble()).ToArray(); Velocity = Enumerable.Repeat(0.0, n).ToArray(); Fitness = double.MaxValue; }
public ActionResult Add(UserModel model) { if (string.IsNullOrWhiteSpace(model.Password)) { ModelState.AddModelError("Password", "密码不能为空"); } if (AdminUsers.IsExistUserName(model.UserName)) { ModelState.AddModelError("UserName", "名称已经存在"); } if (AdminUsers.IsExistEmail(model.Email)) { ModelState.AddModelError("Email", "email已经存在"); } if (AdminUsers.IsExistMobile(model.Mobile)) { ModelState.AddModelError("Mobile", "手机号已经存在"); } if (ModelState.IsValid) { string salt = Users.GenerateUserSalt(); string nickName; if (string.IsNullOrWhiteSpace(model.NickName)) { nickName = "bma" + Randoms.CreateRandomValue(7); } else { nickName = model.NickName; } UserInfo userInfo = new UserInfo() { UserName = model.UserName, Email = model.Email == null ? "" : model.Email, Mobile = model.Mobile == null ? "" : model.Mobile, Salt = salt, Password = Users.CreateUserPassword(model.Password, salt), UserRid = model.UserRid, StoreId = 0, MallAGid = model.MallAGid, NickName = WebHelper.HtmlEncode(nickName), Avatar = model.Avatar == null ? "" : WebHelper.HtmlEncode(model.Avatar), PayCredits = model.PayCredits, RankCredits = AdminUserRanks.GetUserRankById(model.UserRid).CreditsLower, VerifyEmail = 1, VerifyMobile = 1, LiftBanTime = UserRanks.IsBanUserRank(model.UserRid) ? DateTime.Now.AddDays(WorkContext.UserRankInfo.LimitDays) : new DateTime(1900, 1, 1), LastVisitTime = DateTime.Now, LastVisitIP = WorkContext.IP, LastVisitRgId = WorkContext.RegionId, RegisterTime = DateTime.Now, RegisterIP = WorkContext.IP, RegisterRgId = WorkContext.RegionId, Gender = model.Gender, RealName = model.RealName == null ? "" : WebHelper.HtmlEncode(model.RealName), Bday = model.Bday ?? new DateTime(1970, 1, 1), IdCard = model.IdCard == null ? "" : model.IdCard, RegionId = model.RegionId, Address = model.Address == null ? "" : WebHelper.HtmlEncode(model.Address), Bio = model.Bio == null ? "" : WebHelper.HtmlEncode(model.Bio) }; AdminUsers.CreateUser(userInfo); AddMallAdminLog("添加用户", "添加用户,用户为:" + model.UserName); return(PromptView("用户添加成功")); } Load(model.RegionId); return(View(model)); }