public void TestEndRule() { var rule = new StringRule("test") + new EndRule(); Assert.IsTrue(rule.Match("test")); Assert.IsFalse(rule.Match("tes")); }
public void ResetPassword(string usernaem, string oldPassword, string newPassword, string code, ValidateType codeType, string ip) { ExceptionHelper.ThrowIfNullOrEmpty(usernaem, "username"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyPassword(newPassword), "password", "密码长度必须介于6到20位之间"); ExceptionHelper.ThrowIfTrue(string.IsNullOrWhiteSpace(oldPassword) && String.IsNullOrWhiteSpace(code), "旧密码和验证码不能同时为空"); if (!String.IsNullOrWhiteSpace(code)) { _MobileManager.Verify(code, usernaem, codeType); } var result = _OAuth2Service.ResetPassword(OAuth2Context.Current.ClientId, OAuth2Context.Current.ClientSecret, usernaem, oldPassword, newPassword, ip, null); switch (result.error) { case ErrorResponseType.none: break; case ErrorResponseType.invalid_grant: case ErrorResponseType.invalid_request: throw new ExceptionWithErrorCode(ErrorCode.帐号或密码不正确, result.error_description); case ErrorResponseType.username_non_existent: throw new ExceptionWithErrorCode(ErrorCode.未找到该用户, result.error_description); case ErrorResponseType.server_error: throw new ExceptionWithErrorCode(ErrorCode.务器错误, result.error_description); default: throw new AuthorizationException("State:" + result.error.ToString() + ",Msg:" + result.error_description); } }
public void GenerateData(StringRule rule, DataStore store) { DataColumn aColumn = store.ActualData.Columns[rule.FieldName]; if (rule.IsRandom) { RandomStringPick(rule, store, aColumn.Ordinal); } else if (rule.RandomPosition) { RandomStringPosition(rule, store, aColumn.Ordinal); } else { int counter = -1; foreach (DataRow aRow in store.ActualData.Rows) { counter++; if (counter == rule.Entries.Count) { counter = 0; } aRow.ItemArray[aColumn.Ordinal] = rule.Entries[counter]; } } }
public async Task GetValidationLogicShouldReturnWorkingLogicForRuleWhichOperatesOnCollectionOfStrings([Frozen] IResolvesRule ruleResolver, ValidationLogicFactory sut, string str, [RuleContext] RuleContext context) { var value = new ManifestValue { ValidatedType = typeof(IEnumerable <string>), CollectionItemValue = new ManifestCollectionItem { ValidatedType = typeof(string), }, }; var rule = new ManifestRule(value.CollectionItemValue, new ManifestRuleIdentifier(value.CollectionItemValue, typeof(StringRule))); value.Rules.Add(rule); var ruleBody = new StringRule(); Mock.Get(ruleResolver).Setup(x => x.ResolveRule(typeof(StringRule))).Returns(ruleBody); var result = sut.GetValidationLogic(rule); await result.GetResultAsync(str, null, context); Assert.That(ruleBody.Executed, Is.True); }
public void UpdateMobile(string mobile) { ExceptionHelper.ThrowIfNullOrWhiteSpace(mobile, nameof(mobile)); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "手机号不符合格式"); if (mobile != _LazyValue.Value.mobile) { using (var scope = new TransactionScope()) { var isExist = _UserRepository.Entities.FirstOrDefault(p => p.mobile == mobile) != null; if (isExist) { throw new ExceptionWithErrorCode(ErrorCode.该手机号码已被注册); } _LazyValue.Value.mobile = mobile; _UserRepository.SaveChanges(); scope.Complete(); } //推送到图数据库 var taskFactory = new TaskFactory(); taskFactory.StartNew(() => { _FCRMAPIPushManager.UpdateFootUserMobile(_Uid, mobile, false); }); } }
public Day19() : base(19, 2020, "") { string[] problemParts = Input.Split("\n\n"); foreach (string line in problemParts[0].Split("\n")) { new StringRule(line); } int countOne = 0; int countTwo = 0; // Get the sets of rules we care about HashSet <string> baseRule = StringRule.GetMatches(0); HashSet <string> frontRule = StringRule.GetMatches(42); HashSet <string> backRule = StringRule.GetMatches(31); // Check each string in the input foreach (string line in problemParts[1].Split("\n")) { if (baseRule.Contains(line)) { countOne++; } if (PartTwoMatches(line, frontRule, backRule, 0)) { countTwo++; } } partOne = countOne.ToString(); partTwo = countTwo.ToString(); }
/// <summary> /// Check if property value match regex. /// </summary> /// <param name="pattern">Regex pattern.</param> /// <param name="options">Regex options.</param> /// <returns>Current instance.</returns> public PropertyValidator <TRow> TryRegex(string pattern, RegexOptions options = RegexOptions.None) { StringRule <TRow> method = new StringRule <TRow>((x) => this.getter(x)); method.TryRegex(pattern, options); this.validationRules.Add(method); return(this); }
/// <summary> /// Check if property is in list values. /// </summary> /// <param name="values">List of values.</param> /// <param name="comparer">An optionnal equality comparer to compare value.</param> /// <returns>Current instance.</returns> public PropertyValidator <TRow> IsStringValues(string[] values, IEqualityComparer <string> comparer = null) { StringRule <TRow> method = new StringRule <TRow>((x) => this.getter(x)); method.IsStringValues(values, comparer); this.validationRules.Add(method); return(this); }
/// <summary> /// Check if property has required length. /// </summary> /// <param name="min">min length.</param> /// <param name="max">maw length.</param> /// <returns>Current instance.</returns> public PropertyValidator <TRow> HasLength(int min, int max) { StringRule <TRow> method = new StringRule <TRow>((x) => this.getter(x)); method.HasLength(min, max); this.validationRules.Add(method); return(this); }
/// <summary> /// Check if property is not null or empty. /// </summary> /// <returns>Current instance.</returns> public PropertyValidator <TRow> IsNotNullOrEmpty() { StringRule <TRow> method = new StringRule <TRow>((x) => this.getter(x)); method.IsNotNullOrEmpty(); this.validationRules.Add(method); return(this); }
public void ChangeMobile(string mobile) { ExceptionHelper.ThrowIfNullOrEmpty(mobile, "mobile"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "mobile", "手机号码格式不正确"); ExceptionHelper.ThrowIfTrue(!_UserManager.IsUsableMobile(mobile), "mobile", "此手机已经被注册"); _LazyUser.Value.mobile = mobile.Trim(); _UserRepository.SaveChanges(); }
public IQueryable <Data.AddressBookMobile> GetHas(string mobile) { if (!StringRule.VerifyMobile(mobile)) { return(Enumerable.Empty <Data.AddressBookMobile>().AsQueryable()); } return(_AddressBookMobileRepository.Entities.Where(b => b.mobile == mobile && !b.haveRecommended)); }
public void TestStartRule() { var rule = new StartRule(); var randomRule = new StringRule("Test"); Assert.IsTrue(rule.Match("sometihng")); Assert.IsFalse((randomRule + rule).Match("Test dingen")); }
public void LoadDate() { string strIsAll = "0"; int strType = 0; EntityData entityNotice = RemindDAO.GetNoticeByCode(strNoticeCode); if (entityNotice.HasRecord()) { if (entityNotice.GetInt("status").ToString() != "0") { strType = entityNotice.GetInt("Type"); if (strType == 99) { this.trNotice.Visible = false; } this.DDLNoticeClass.Value = Server.HtmlEncode(entityNotice.GetString("NoticeClass")); this.txtTitle.Value = Server.HtmlEncode(entityNotice.GetString("Title")); this.lbSubmitname.Text = RmsPM.BLL.SystemRule.GetUserName(entityNotice.GetString("SubmitPerson").ToString()).ToString(); this.lblSubmitDate.Text = entityNotice.GetDateTimeOnlyDate("SubmitDate"); this.taContent.Value = StringRule.FormartOutput(entityNotice.GetString("Content")); strIsAll = entityNotice.GetString("IsAll"); this.lbLastUpdate.Text = RmsPM.BLL.SystemRule.GetUserName(entityNotice.GetString("UserCode").ToString()).ToString() + " 于 " + entityNotice.GetDateTimeOnlyDate("UpdateDate") + "修改"; } else { Response.Write(JavaScript.ScriptStart); Response.Write("window.alert('通知已删除');"); Response.Write("window.close();"); Response.Write(JavaScript.ScriptEnd); } } if (strIsAll == "0") //部分人员 { string strUsers = ""; string strUserNames = ""; string strStations = ""; string strStationNames = ""; RmsPM.BLL.ResourceRule.GetAccessRange(this.strNoticeCode, "0801", "080104", ref strUsers, ref strUserNames, ref strStations, ref strStationNames); this.txtUsers.Value = RmsPM.BLL.StringRule.CutRepeat(strUsers); this.SelectName.InnerText = RmsPM.BLL.StringRule.CutRepeat(strUserNames); this.txtStations.Value = RmsPM.BLL.StringRule.CutRepeat(strStations); this.SelectName.InnerText += "," + RmsPM.BLL.StringRule.CutRepeat(strStationNames); } else { this.txtUsers.Value = this.GetAllUser(); this.SelectName.InnerText = "全体人员"; } entityNotice.Dispose(); // this.lblTitle.Text = "修改通知"; //EntityData entityNotice = RemindDAO.GetNoticeByCode(this.strNoticeCode); //this.txtTitle.Value = System.Web.HttpUtility.HtmlEncode(entityNotice.GetString("Title")); //this.taContent.Value = StringRule.FormartOutput(entityNotice.GetString("Content")); //this.LoadUser(entityNotice.GetString("IsAll")); }
public void TestStringRule() { var rule = new StringRule("Test"); Assert.IsTrue(rule.Match("Test")); Assert.IsTrue(rule.Match("Test123")); Assert.IsFalse(rule.Match("test123")); Assert.IsFalse(rule.Match("Failing Test")); }
public void SetRecommendedState(bool recommended, string mobile, long[] uids) { if (StringRule.VerifyMobile(mobile) && uids != null && uids.Length > 0) { _AddressBookMobileRepository.Update(a => a.mobile == mobile && uids.Contains(a.uid), a => new Data.AddressBookMobile { haveRecommended = recommended }); } }
public void TestOrUsingOperatorRule() { var rule = new StringRule("cat") | new StringRule("dog"); Assert.IsFalse(rule.Match("something")); Assert.IsFalse(rule.Match("fishcatdog")); Assert.IsTrue(rule.Match("catfish")); Assert.IsTrue(rule.Match("dogfish")); }
public void SendVerifyCode(string mobile, ValidateType verifyType, long?uid, string signName, string ip, string from) { ExceptionHelper.ThrowIfNullOrWhiteSpace(mobile, "mobile", "手机号码不能为空"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "mobile", "手机号码格式错误"); using (var service = _UserManagerService.NewChannelProvider()) { service.Channel.SendCode(new OAuth2ClientIdentity(), mobile, verifyType, uid, signName, ip, from); } }
public void TestSequenceUsingOperatorRule() { var rule = new StringRule("cat") + new StringRule("fish"); Assert.IsFalse(rule.Match("catsomething")); Assert.IsFalse(rule.Match("fishcat")); Assert.IsTrue(rule.Match("catfish")); Assert.IsTrue(rule.Match("catfish something")); }
public void TestStringCaseInsensitiveRule() { var rule = new StringRule("Test", true); Assert.IsTrue(rule.Match("Test")); Assert.IsTrue(rule.Match("Test123")); Assert.IsTrue(rule.Match("test123")); Assert.IsFalse(rule.Match("Failing Test")); }
public long AddUserByFootChatAdmin(string mobile, string password, string ip, string from) { ExceptionHelper.ThrowIfNullOrWhiteSpace(from, "from", "注册来源不能为空"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyPassword(password), "password", "密码格式错误"); var areaNo = "0001"; var area = _StaticResourceManager.GetIPArea(ip); if (area != null) { areaNo = area.area_no; } long uid; using (var service = _UserManagerServiceChannelProvider.NewChannelProvider()) { uid = service.Channel.GetUidIfNonexistentRegister(new OAuth2ClientIdentity(), mobile, true, password, ip, from); } ExceptionHelper.ThrowIfTrue(uid <= 0, "uid", "创建用户失败"); var securityPsw = string.Empty; using (var provider = _UserManagerServiceChannelProvider.NewChannelProvider()) { var id = Tgnet.Security.NumberConfuse.Confuse(uid); securityPsw = provider.Channel.GetPassword(new OAuth2ClientIdentity(), id); } if (!_UserRepository.Entities.Any(p => p.uid == uid)) { _UserRepository.Add(new FootUser() { mobile = mobile, uid = uid, password = securityPsw, areaNo = areaNo, isInner = false, isLocked = false, loginCount = 1, lastLogin = DateTime.Now, created = DateTime.Now, verifyImage = String.Empty, verifyStatus = VerifyStatus.None, cover = "", }); _UserRepository.SaveChanges(); //推送到图数据库 var taskFactory = new TaskFactory(); taskFactory.StartNew(() => { _PushManager.AddUser(uid, mobile, false); }); } else { throw new ExceptionWithErrorCode(ErrorCode.对应条目已存在, "该用户已经存在"); } return(uid); }
public void AddValidation(Control c, StringRule rule) { if (ruleMap.ContainsKey(c)) { return; } c.TextChanged += Tb_TextChanged; ruleMap.Add(c, rule); }
public string Verify(string code, string mobile, ValidateType verifyType) { ExceptionHelper.ThrowIfNullOrWhiteSpace(code, "code", "手机验证码不能为空"); ExceptionHelper.ThrowIfNullOrWhiteSpace(mobile, "mobile"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "mobile", "手机号码格式错误"); var result = String.Empty; result = _VerifyHelper.Verify(mobile, code, verifyType); return(result); }
public void SendVerifyCode(string mobile, VerifyType verifyType) { ExceptionHelper.ThrowIfNullOrWhiteSpace(mobile, "mobile"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "mobile", "手机号码格式不正确"); switch (verifyType) { case VerifyType.Common: case VerifyType.FormatPwd: if (!_UserRepository.Entities.Any(u => u.mobile == mobile.Trim())) { throw new Flh.FlhException(ErrorCode.NotExists, "该手机未注册"); } break; case VerifyType.ChangeMobile: case VerifyType.Register: if (_UserRepository.Entities.Any(u => u.mobile == mobile.Trim())) { throw new Flh.FlhException(ErrorCode.Exists, "该手机已被注册"); } break; } var entity = GetValidityCode(mobile); var message = String.Empty; if (entity == null || entity.createDate.AddMinutes(10) < DateTime.Now) { var code = CreateCode(); using (var scope = new TransactionScope()) { _VerifyCodeRepository.Delete(vc => vc.mobile == mobile); _VerifyCodeRepository.Add(entity = new Data.VerifyCode { code = code, createDate = DateTime.Now, mobile = mobile, endDate = DateTime.Now.AddMinutes(30) }); _VerifyCodeRepository.SaveChanges(); SendSmsMessage(mobile, verifyType, code); scope.Complete(); } } else { SendSmsMessage(mobile, verifyType, entity.code); } }
public static InCheck ExecuteAllCheck(InCheck item) { Dictionary <string, Predicate <InCheck> > All_Rule = new StringRule().GetRuleList(); List <string> ExecuteList = new List <string>(); ExecuteList.Add("is_null"); ExecuteList.Add("is_equal_to_A"); foreach (string Execute_Rule in ExecuteList) { item.isValid = All_Rule[Execute_Rule](item); if (!item.isValid) { item.ErrorRule = Execute_Rule; } } return(item); }
public void ChangePassword(string oldPassword, string newPasswrod) { ExceptionHelper.ThrowIfNullOrWhiteSpace(newPasswrod, "newPasswrod", "新密码"); ExceptionHelper.ThrowIfNullOrWhiteSpace(oldPassword, "oldPassword", "旧密码"); newPasswrod = newPasswrod.Trim(); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyPassword(newPasswrod), "password", "新密码格式不正确,密码长度为6-20位"); if (!new Security.MD5().Verify(oldPassword.Trim(), _LazyUser.Value.pwd)) { throw new FlhException(ErrorCode.ErrorUserNoOrPwd, "账号或密码错误"); } _LazyUser.Value.pwd = new Security.MD5().Encrypt(newPasswrod); _UserRepository.SaveChanges(); }
public string Verify(string mobile, string code, ValidateType type) { var error = ErrorCode.None; ExceptionHelper.ThrowIfNullOrWhiteSpace(mobile, "mobile", "手机号码不能为空"); ExceptionHelper.ThrowIfTrue(!StringRule.VerifyMobile(mobile), "mobile", "手机号码格式错误"); using (var service = _UserManagerService.NewChannelProvider()) { return(service.Channel.Verify(new OAuth2ClientIdentity(), mobile, code, type)); } }
private void RandomStringPosition(StringRule rule, DataStore store, int colIndex) { String result = String.Empty; int range = rule.Entries[0].Length - rule.StringLength; Random randomGenerator = new Random(); foreach (DataRow aRow in store.ActualData.Rows) { int randomChar = randomGenerator.Next(0, range); result = rule.Entries[0].Substring(randomChar, rule.StringLength); aRow.ItemArray[colIndex] = result; } }
public IEnumerable <AddressBookMobile> Change(IEnumerable <AddressBookItem> items) { List <AddressBookMobile> result = new List <AddressBookMobile>(); if (items == null) { return(Enumerable.Empty <AddressBookMobile>().ToArray()); } var books = items.Where(b => StringRule.VerifyMobile(b.Mobile) && (b.TgUid == null || b.TgUid != _User.Uid)).ToArray(); if (books.Length == 0) { return(Enumerable.Empty <AddressBookMobile>().ToArray()); } foreach (var item in books) { item.Mobile = (item.Mobile ?? String.Empty).Trim(); item.Name = (item.Name ?? String.Empty).Trim().Left(50); item.Company = (item.Company ?? String.Empty).Trim().Left(100); } var mobiles = books.Select(b => b.Mobile).Distinct().ToArray(); lock (_Locker) { var exist = _AddressBookMobileRepository.Entities.Where(m => m.uid == _User.Uid && mobiles.Contains(m.mobile)).Select(m => m.mobile).ToArray(); if (exist.Length > 0) { mobiles = mobiles.Except(exist).ToArray(); } if (mobiles.Length > 0) { result.AddRange(mobiles.Select(m => new Data.AddressBookMobile { mobile = m, createDate = DateTime.Now, uid = _User.Uid, tguid = books.Where(b => b.Mobile == m).Select(b => b.TgUid).FirstOrDefault(), company = books.Where(b => b.Mobile == m).Select(b => b.Company).FirstOrDefault(), name = books.Where(b => b.Mobile == m).Select(b => b.Name).FirstOrDefault() })); _AddressBookMobileRepository.AddRange(result); _AddressBookMobileRepository.SaveChanges(); } _PushManager.GenContact(_User.Uid, _User.Mobile, result.Select(b => new FCRMAPI.Request.Contact() { Aid = b.id, Mobile = b.mobile }).ToArray()); } return(result); }
public IUserService Login(string mobileOrEmail, string password, string ip) { ExceptionHelper.ThrowIfNullOrWhiteSpace(mobileOrEmail, "mobileOrEmail", "账号不能为空"); ExceptionHelper.ThrowIfNullOrWhiteSpace(password, "password", "密码不能为空"); var source = _UserRepository.Entities; if (StringRule.VerifyMobile(mobileOrEmail)) { source = source.Where(u => u.mobile == mobileOrEmail.Trim()); } else if (StringRule.VerifyEmail(mobileOrEmail)) { source = source.Where(u => u.email == mobileOrEmail.Trim()); } else { ExceptionHelper.ThrowIfTrue(true, "mobileOrEmail", "请输入手机或者邮箱进行登陆"); } var user = source.FirstOrDefault(); if (user == null) { throw new FlhException(ErrorCode.NotExists, "账号不存在"); } if (!user.enabled) { throw new FlhException(ErrorCode.Locked, "账号已被锁定"); } if (!new Security.MD5().Verify(password.Trim(), user.pwd)) { throw new FlhException(ErrorCode.ErrorUserNoOrPwd, "账号或密码错误"); } ip = (ip ?? String.Empty).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? String.Empty; user.last_login_date = DateTime.Now; _UserRepository.SaveChanges(); var history = new Data.LoginHistory { ip = ip, login_date = DateTime.Now, uid = user.uid }; _LoginHistoryRepository.Add(history); _LoginHistoryRepository.SaveChanges(); return(GetUser(user)); }