private void button2_Click(object sender, EventArgs e) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\d+"); if (listBox1.SelectedIndex > -1 && reg.IsMatch(textBox1.Text) && reg.IsMatch(textBox2.Text)) { res = string.Format("{0}({1},{2})",listBox1.Items[listBox1.SelectedIndex].ToString(),textBox1.Text,textBox2.Text); } else res = ""; }
protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); // 只读, 不处理 if (this.ReadOnly) return; string regex = @"^[\w ]+$"; //匹配数字、字母、汉字 if (isNumber) regex = "^[0-9]*$"; //匹配数字 var reg = new System.Text.RegularExpressions.Regex(regex);// var str = this.Text.Replace(" ", ""); var sb = new StringBuilder(); if (!reg.IsMatch(str)) { for (int i = 0; i < str.Length; i++) { if (reg.IsMatch(str[i].ToString())) { sb.Append(str[i].ToString()); } } this.Text = sb.ToString(); this.SelectionStart = this.Text.Length; //定义输入焦点在最后一个字符 } }
private void button1_Click(object sender, EventArgs e) { System.Text.RegularExpressions.Regex reg=new System.Text.RegularExpressions.Regex(@"\d+"); if (comboBox1.Text != "" && reg.IsMatch(textBox1.Text)&& reg.IsMatch(textBox2.Text)) { res = string.Format("{0}({1},{2})", comboBox1.Text, textBox1.Text, textBox2.Text); } else { res = ""; } }
public FunctionCall(ISyntaxNode parent, ref string Input) : base(parent) { Pattern regExPattern = "^\\s*" + new Group("def", new Group("identifier", Provider.identifier) + "\\s*\\(" + new Group("params", "[a-zA-Z_0-9*\\+/!&|%()=,\\s]*") + "\\)"); System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern); System.Text.RegularExpressions.Match match = regEx.Match(Input); if (!match.Success) throw new ParseException(); //if (match.Index != 0) // throw new ParseException(); Input = Input.Remove(0, match.Index+match.Length); // Also removes all starting spaces etc... Identifier = match.Groups["identifier"].Value; //System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\s*,\\s*" + new Group("", "")); if (!parent.IsFunctionDeclared(Identifier)) throw new SyntaxException("Syntax error: Call of undeclared function \"" + Identifier + "\"."); String param = match.Groups["params"].Value; List<IRightValue> parameters = new List<IRightValue>(); System.Text.RegularExpressions.Regex endRegEx = new System.Text.RegularExpressions.Regex("^\\s*$"); System.Text.RegularExpressions.Regex commaRegEx = new System.Text.RegularExpressions.Regex("^\\s*,\\s*"); while (!endRegEx.IsMatch(param)) { IRightValue val = IRightValue.Parse(this, ref param); if (val == null) throw new SyntaxException ("syntax error: Can't parse rvalue at function call."); parameters.Add(val); if (endRegEx.IsMatch(param)) break; System.Text.RegularExpressions.Match comma = commaRegEx.Match(param); if (!comma.Success) throw new SyntaxException("syntax error: Function arguments must be separated by a comma."); param = param.Remove(0, comma.Index + comma.Length); // Also removes all starting spaces etc... } this.Parameters = parameters.ToArray(); ; }
public void Check(Image img) { if (text.Length > 0) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pattern); if (!r.IsMatch(text)) { MessageBox.Show(errorMessageLocal); resultLocal = false; img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/img/registration/" + resultServer.ToString() + ".png", UriKind.Relative)); } else { resultLocal = true; if (type != "password") { ServerCheck(img); } else { resultServer = true; img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/img/registration/" + resultServer.ToString() + ".png", UriKind.Relative)); } } } else { resultLocal = false; resultServer = false; img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/img/registration/" + resultServer.ToString() + ".png", UriKind.Relative)); } }
/// <summary> /// Function that builds the contents of the generated file based on the contents of the input file /// </summary> /// <param name="inputFileContent">Content of the input file</param> /// <returns>Generated file as a byte array</returns> protected override byte[] GenerateCode(string inputFileContent) { //if (InputFilePath.EndsWith("_md")) var mdRegex = new System.Text.RegularExpressions.Regex(@"\w+\.\w+_md"); if (mdRegex.IsMatch(Path.GetFileName(InputFilePath))) { try { var input = File.ReadAllText(InputFilePath); var md = new MarkdownSharp.Markdown(); var output = md.Transform(input); return ConvertToBytes(output); } catch (Exception exception) { GeneratorError(0, exception.Message, 0, 0); } } else { GeneratorError(0, "The Markdown tool is only for Markdown files with the following filename format: filename.[required_extension]_md", 0, 0); } return null; }
public static bool validarCorreo(string cadenaUsuario) { bool val = true; bool result = false; foreach (char c in cadenaUsuario) { if (c == '"') { val = false; break; } } if (val == true) { patron = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"; auto = new System.Text.RegularExpressions.Regex(patron); result = auto.IsMatch(cadenaUsuario); } else { result = false; } return result; }
public void IsDateTimeTest() { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$"); var d = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); var res= reg.IsMatch(d); Assert.IsTrue(res); }
public static long getByteFromGMKBString(String text) { long result = 0; System.Text.RegularExpressions.Regex gbReg = new System.Text.RegularExpressions.Regex(@"(\d+)GB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex kbReg = new System.Text.RegularExpressions.Regex(@"(\d+)KB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex mbReg = new System.Text.RegularExpressions.Regex(@"(\d+)MB", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex bReg = new System.Text.RegularExpressions.Regex(@"(\d+)B", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (bReg.IsMatch(text)) { var m = bReg.Match(text); result += long.Parse(m.Groups[1].Value); } if (kbReg.IsMatch(text)) { var m = kbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte; } if (mbReg.IsMatch(text)) { var m = mbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte; } if (gbReg.IsMatch(text)) { var m = gbReg.Match(text); result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte * BaseByte; } return result; }
public void Update(string argument) { if (_expression?.IsMatch(argument) == true || argument == _exactMatch) { Run(); } }
private static string HandleCreateAccount(HttpServer server, HttpListenerRequest request, Dictionary<string, string> parameters) { if (!parameters.ContainsKey("username")) throw new Exception("Missing username."); if (!parameters.ContainsKey("password")) throw new Exception("Missing password."); string username = parameters["username"]; string password = parameters["password"]; if (Databases.AccountTable.Count(a => a.Username.ToLower() == username.ToLower()) > 0) return JsonEncode("Username already in use!"); System.Text.RegularExpressions.Regex invalidCharacterRegex = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]"); if (invalidCharacterRegex.IsMatch(username)) return JsonEncode("Invalid characters detected in username!"); Random getrandom = new Random(); String token = getrandom.Next(10000000, 99999999).ToString(); AccountEntry entry = new AccountEntry(); entry.Index = Databases.AccountTable.GenerateIndex(); entry.Username = username; entry.Password = password; entry.Verifier = ""; entry.Salt = ""; entry.RTW_Points = 0; entry.IsAdmin = 0; entry.IsBanned = 0; entry.InUse = 0; entry.extrn_login = 0; entry.CanHostDistrict = 1; entry.Token = token; Databases.AccountTable.Add(entry); Log.Succes("HTTP", "Successfully created account '" + username + "'"); return JsonEncode("Account created!\n\nYour token is: " + token + ".\nCopy and paste given token in \"_rtoken.id\" file and put it in the same folder where your \"APB.exe\" is located."); }
/// <summary> /// 检测是否含有危险字符(防止Sql注入) /// </summary> /// <param name="contents">预检测的内容</param> /// <returns>返回True或false</returns> public static bool HasDangerousContents(this string contents) { bool bReturnValue = true; if (string.IsNullOrEmpty(contents)) return bReturnValue; if (contents.Length > 0) { //convert to lower string sLowerStr = contents.ToLower(); //RegularExpressions string sRxStr = @"(\sand\s)|(\sand\s)|(\slike\s)|(select\s)|(insert\s)| (delete\s)|(update\s[\s\S].*\sset)|(create\s)|(\stable)|(<[iframe|/iframe|script|/script])| (')|(\sexec)|(\sdeclare)|(\struncate)|(\smaster)|(\sbackup)|(\smid)|(\scount)"; //Match bool bIsMatch = true; System.Text.RegularExpressions.Regex sRx = new System.Text.RegularExpressions.Regex(sRxStr); bIsMatch = sRx.IsMatch(sLowerStr, 0); if (bIsMatch) { bReturnValue = false; } } return bReturnValue; }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { String filePath = openFileDialog1.FileName; openFileDialog1.InitialDirectory = filePath; mobiles.Clear(); listBox1.Items.Clear(); if (File.Exists(filePath)){ using (StreamReader sr = File.OpenText(filePath)) { string s = ""; while ((s = sr.ReadLine()) != null) { System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$"); if (s.Length == 11&& rex.IsMatch(s)) { if (!mobiles.Contains(s)) { mobiles.Add(s); listBox1.Items.Add(s); } } } } } msgLab.Text = "你将给 " + mobiles.Count + " 个人群发信息,短信字数共计为 " + contentTxt.Text.Length + " 个"; }
/// <summary> /// ajax method for chek routing /// </summary> /// <param name="pattern"></param> /// <param name="replaceStr"></param> public void CheckRouting(string pattern, string replaceStr) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pattern); string flag = reg.IsMatch(replaceStr) ? "匹配" : "不匹配"; RenderText(flag); CancelView(); }
/// <summary> /// Search Running Object Table for a running VisualStudio instance which has open a particular solution. /// Typical usage might be EnvDTE.Solution sln = DesignTime.GetVisualStudioInstanceBySolution(@"\\My Solution\.sln$") /// </summary> /// <param name="solution_file_regex">Regular expression matching the solution fullname</param> /// <returns>The Solution object if a match was found, null otherwise</returns> public static EnvDTE.Solution GetVisualStudioInstanceBySolution(string solution_file_regex) { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(solution_file_regex); IRunningObjectTable runningObjectTable; GetRunningObjectTable(0, out runningObjectTable); IEnumMoniker monikerEnumerator; runningObjectTable.EnumRunning(out monikerEnumerator); monikerEnumerator.Reset(); IMoniker[] monikers = new IMoniker[1]; IntPtr numFetched = IntPtr.Zero; while (monikerEnumerator.Next(1, monikers, numFetched) == 0) { IBindCtx ctx; CreateBindCtx(0, out ctx); string runningObjectName; monikers[0].GetDisplayName(ctx, null, out runningObjectName); if (re.IsMatch(runningObjectName)) { object runningObjectVal; runningObjectTable.GetObject(monikers[0], out runningObjectVal); EnvDTE.Solution sln = runningObjectVal as EnvDTE.Solution; if (sln != null) return sln; } } return null; }
public static bool IsValidLetterKey(string value) { if (value == null) return false; System.Text.RegularExpressions.Regex regexMatch = new System.Text.RegularExpressions.Regex("[A-Z]"); return regexMatch.IsMatch(value); }
public static void CheckString(FieldInfo fieldInfo, string val) { if (val == null) return; if (fieldInfo.maxLength > 0) { if (!string.IsNullOrEmpty(val)) { if (val.Length > fieldInfo.maxLength) { throw new ValidationException(string.Format(ErrorStrings.ERR_VAL_EXCEEDS_MAXLENGTH, fieldInfo.fieldName, fieldInfo.maxLength)); } } } if (!string.IsNullOrEmpty(val) && !string.IsNullOrEmpty(fieldInfo.regex)) { var rx = new System.Text.RegularExpressions.Regex(fieldInfo.regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (!rx.IsMatch(val)) { throw new ValidationException(string.Format(ErrorStrings.ERR_VAL_IS_NOT_VALID, fieldInfo.fieldName)); } } }
public string Send_Email(String SendFrom,string SendTo, string Subject, string Body, string cc) { try { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); bool result = regex.IsMatch(SendTo); if (result == false) { return "Địa chỉ email không hợp lệ."; } else { Checkbeforesendmail(SendTo,Body,Subject,cc); //System.Net.Mail.SmtpClient smtp = new SmtpClient(); //System.Net.Mail.MailMessage msg = new MailMessage(SendFrom,SendTo,Subject,Body); //msg.IsBodyHtml = true; //smtp.Host = "smtp.gmail.com";//Sử dụng SMTP của gmail //smtp.Send(msg); return "Email đã được gửi đến: " + SendTo + "."; } } catch { return ""; } }
public string TextValidation(string passingText, string type,string Field) { string returnString = ""; decimal value; switch (type) { case "Decimal": bool isDecimal = decimal.TryParse(passingText, out value); if (isDecimal == false) { returnString = "Please Enter Valid Decimal Value for "+Field; } break; case "String": System.Text.RegularExpressions.Regex stringCheck = new System.Text.RegularExpressions.Regex("^[a-zA-Z][a-zA-Z\\s]+$"); if (!stringCheck.IsMatch(passingText)) { returnString = "Please Enter Valid "+Field; } break; } return returnString; }
static FunctionBounds CreateBounds(string[] parts) { System.Text.RegularExpressions.Regex rg_bound = new System.Text.RegularExpressions.Regex("{.*}"); FunctionBounds Bounds = new FunctionBounds(); foreach (string part in parts.Skip(1)) { if (rg_bound.IsMatch(part)) { string[] bound = part.Remove(part.Length - 1, 1).Remove(0, 1).Split(','); Bounds.AddBound((float)Convert.ToDouble(bound[0]), (float)Convert.ToDouble(bound[bound.Length - 1])); if (bound.Length == 3) { Bounds.AddStep((float)Convert.ToDouble(bound[1])); } else { Bounds.AddDefaultStep((float)Convert.ToDouble(bound[0]), (float)Convert.ToDouble(bound[bound.Length - 1])); } } else { } } return Bounds; }
public bool ValidateEmail() { bool result = true; try { if (txtMailId.Text.Trim() != string.Empty) { System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");//^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$ if (txtMailId.Text.Length > 0) { if (!rEMail.IsMatch(txtMailId.Text)) { MessageBox.Show("Invalid Email", "Pharmasoft", MessageBoxButtons.OK, MessageBoxIcon.Information); result = false; txtMailId.Focus(); } } } } catch (Exception ex) { MessageBox.Show("SM" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return result; }
public static Object ObjectField (GUIContent label, Object obj, System.Type objType, bool allowSceneObjects) { obj = EditorGUILayout.ObjectField(label, obj, objType, allowSceneObjects); if (obj != null) { if (allowSceneObjects && !EditorUtility.IsPersistent(obj)) { //Object is in the scene var com = obj as Component; var go = obj as GameObject; if (com != null) { go = com.gameObject; } if (go != null) { var urh = go.GetComponent<UnityReferenceHelper>(); if (urh == null) { if (FixLabel("Object's GameObject must have a UnityReferenceHelper component attached")) { go.AddComponent<UnityReferenceHelper>(); } } } } else if (EditorUtility.IsPersistent(obj)) { string path = AssetDatabase.GetAssetPath(obj); var rg = new System.Text.RegularExpressions.Regex(@"Resources[/|\\][^/]*$"); if (!rg.IsMatch(path)) { if (FixLabel("Object must be in the 'Resources' folder, top level")) { if (!System.IO.Directory.Exists(Application.dataPath+"/Resources")) { System.IO.Directory.CreateDirectory(Application.dataPath+"/Resources"); AssetDatabase.Refresh(); } string ext = System.IO.Path.GetExtension(path); string error = AssetDatabase.MoveAsset(path, "Assets/Resources/"+obj.name+ext); if (error == "") { //Debug.Log ("Successful move"); path = AssetDatabase.GetAssetPath(obj); } else { Debug.LogError("Couldn't move asset - "+error); } } } if (!AssetDatabase.IsMainAsset(obj) && obj.name != AssetDatabase.LoadMainAssetAtPath(path).name) { if (FixLabel("Due to technical reasons, the main asset must\nhave the same name as the referenced asset")) { string error = AssetDatabase.RenameAsset(path, obj.name); if (error == "") { //Debug.Log ("Successful"); } else { Debug.LogError("Couldn't rename asset - "+error); } } } } } return obj; }
public static bool ValidateFile(string contents) { if (string.IsNullOrEmpty(contents)) return false; const string pattern = @"^\d*\.\d*\.\d*\.\d*$"; var re = new System.Text.RegularExpressions.Regex(pattern); var val = re.IsMatch(contents); return val; }
/// <summary> /// 更新TAG /// </summary> /// <param name="tagid">标签ID</param> /// <param name="orderid">排序,-1为不可用</param> /// <param name="color">颜色</param> /// <returns></returns> public static bool UpdateForumTags(int tagid, int orderid, string color) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^#?([0-9|A-F]){6}$"); if (color != "" && !r.IsMatch(color)) return false; Data.DataProvider.Tags.UpdateForumTags(tagid, orderid, color.Replace("#", "")); return true; }
public string CleanInvalidXmlChars(string xml) { string pattern = @"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF]);"; System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex.IsMatch(xml)) xml = regex.Replace(xml, String.Empty); return xml; }
/// <summary> /// Determines whether the specified symbol is an index. /// </summary> /// <param name="sym">The sym.</param> /// <returns> /// <c>true</c> if the specified sym is idx; otherwise, <c>false</c>. /// </returns> public static bool isIdx(string sym) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[A-Z0-9#]{1,4}$"); System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex("^[/$]"); string us = sym.ToUpper(); bool match = r.IsMatch(us) && (r2.IsMatch(us) || us.Contains("#")); return match; }
public static bool IsValidHexByteString(this string data) { if (string.IsNullOrWhiteSpace(data)) return false; var base16Match = new System.Text.RegularExpressions.Regex (@"^(?:[A-Fa-f0-9]{2})*$"); // any letter A-F a-f, any number 0-9, but in PAIRS, no whitespace of any kind return base16Match.IsMatch(data); }
public Document(string Input) : base(null) { Variables = new Dictionary<string, VariableDeclaration>(); Constants = new Dictionary<string, ConstantDeclaration>(); Functions = new Dictionary<string, FunctionDeclaration>(); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^\\s*$"); while (!regex.IsMatch(Input)) // Gets true once the Input string contains only spaces, \n etc... { /* Try parse any possible construct * like: * - Variable declaration * - Constant declaration * - Function declaration */ VariableDeclaration v = TryParse<VariableDeclaration>(ref Input, delegate(ref string i) { return new VariableDeclaration(this, ref i); }); if (v != null) { if (Variables.ContainsKey(v.Identifier)) throw new SyntaxException ("Semantic error: Variable \""+v.Identifier+"\" is already declared in this scope."); Variables.Add (v.Identifier, v); continue; } ConstantDeclaration c = TryParse<ConstantDeclaration>(ref Input, delegate(ref string i) { return new ConstantDeclaration(this, ref i); }); if (c != null) { if (Constants.ContainsKey(c.Identifier)) throw new SyntaxException ("Semantic error: Constant \""+c.Identifier+"\" is already declared in this scope."); Constants.Add (c.Identifier, c); continue; } FunctionDeclaration f = TryParse<FunctionDeclaration>(ref Input, delegate(ref string i) { return new FunctionDeclaration(this, ref i); }); if (f != null) { if (!Functions.ContainsKey(f.Identifier)) Functions.Add(f.Identifier, f); else if (f.HasBody) { if (!Functions[f.Identifier].HasBody) // Oh, well. Function was declared, but not defined.... Functions[f.Identifier] = f; else throw new SyntaxException("Semantic error: The function \"" + f.Identifier + "\" was already defined."); } else throw new SyntaxException("Semantic error: The function \"" + f.Identifier + "\" was already declared."); continue; } // Well, if nothing got parsed, then it's a invalid expression throw new SyntaxException("Syntax error: Invalid token \""+Input+"\""); } }
public static bool IsValidEmailAddress(this string input) { const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; var re = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); return re.IsMatch(input); }
/// <summary> /// The answer is valid if it is alphabetic /// </summary> public static bool IsAlphabetic(string answer) { if (answer == null) { return false; } System.Text.RegularExpressions.Regex regexAlphabetic = new System.Text.RegularExpressions.Regex("[^a-zA-Z]"); return !regexAlphabetic.IsMatch(answer); }
public virtual bool Identify(string userAgent) { var pattern = UserAgentPattern; if (String.IsNullOrEmpty(pattern)) return false; if(String.IsNullOrEmpty(userAgent)) return false; var expr = new System.Text.RegularExpressions.Regex(pattern); return expr.IsMatch(userAgent); }
internal static bool IsVariableOrIdentifier(this List <Token> list, int index) => list[index].Type == 0 && VariableOrIdentifier.IsMatch(list[index].Content);
protected bool IsNumeric(string value) { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^[-+]?\d+\.?\d*$|^[-+]?\d*\.?\d+$"); return(re.IsMatch(value)); }
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { var regex = new System.Text.RegularExpressions.Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); }
/// <summary> /// 将数字转换为人民币大写格式 /// </summary> /// <returns></returns> public string convertCurrency() { const decimal MAXIMUM_NUMBER = 99999999999.99M; const string CN_ZERO = "零"; const string CN_ONE = "壹"; const string CN_TWO = "贰"; const string CN_THREE = "叁"; const string CN_FOUR = "肆"; const string CN_FIVE = "伍"; const string CN_SIX = "陆"; const string CN_SEVEN = "柒"; const string CN_EIGHT = "捌"; const string CN_NINE = "玖"; const string CN_TEN = "拾"; const string CN_HUNDRED = "佰"; const string CN_THOUSAND = "仟"; const string CN_TEN_THOUSAND = "万"; const string CN_HUNDRED_MILLION = "亿"; const string CN_SYMBOL = "人民币(大写):"; const string CN_DOLLAR = "元"; const string CN_TEN_CENT = "角"; const string CN_CENT = "分"; const string CN_INTEGER = "整"; string integral = ""; // Represent integral part of digit number. string dec = ""; // Represent decimal part of digit number. string outputstringacters = ""; // The output result. string[] parts; int zeroCount; int i, p; string d = ""; int quotient, modulus; System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$"); if (reg.IsMatch(money.ToString()) == false) { return("非法数字格式!"); } // Assert the number is not greater than the maximum number. if (money > MAXIMUM_NUMBER) { return("数字太大!"); } // Process the coversion from currency digits to stringacters: // Separate integral and decimal parts before processing coversion: parts = money.ToString().Split('.'); if (parts.Length > 1) { integral = parts[0]; dec = parts[1]; // Cut down redundant decimal digits that are after the second. dec = dec.Substring(0, 2); } else { integral = parts[0]; dec = ""; } // Prepare the stringacters corresponding to the digits: string[] digits = { CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE }; string[] radices = { "", CN_TEN, CN_HUNDRED, CN_THOUSAND }; string[] bigRadices = { "", CN_TEN_THOUSAND, CN_HUNDRED_MILLION }; string[] decimals = { CN_TEN_CENT, CN_CENT }; // Start processing: outputstringacters = ""; // Process integral part if it is larger than 0: if (Convert.ToInt64(integral) > 0) { zeroCount = 0; for (i = 0; i < integral.Length; i++) { p = integral.Length - i - 1; d = integral.Substring(i, 1); quotient = p / 4; modulus = p % 4; if (d == "0") { zeroCount++; } else { if (zeroCount > 0) { outputstringacters += digits[0]; } zeroCount = 0; outputstringacters += digits[Convert.ToInt32(d)] + radices[modulus]; } if (modulus == 0 && zeroCount < 4) { outputstringacters += bigRadices[quotient]; } } outputstringacters += CN_DOLLAR; } // Process decimal part if there is: if (dec != "") { for (i = 0; i < dec.Length; i++) { d = dec.Substring(i, 1); if (d != "0") { outputstringacters += digits[Convert.ToInt32(d)] + decimals[i]; } } } // Confirm and return the final output string: if (outputstringacters == "") { outputstringacters = CN_ZERO + CN_DOLLAR; } if (dec == "") { outputstringacters += CN_INTEGER; } outputstringacters = CN_SYMBOL + outputstringacters; return(outputstringacters); }
//public override List<Mercury.Server.Services.Responses.ConfigurationImportResponse> XmlImport (System.Xml.XmlNode objectNode) { // List<Mercury.Server.Services.Responses.ConfigurationImportResponse> response = new List<Mercury.Server.Services.Responses.ConfigurationImportResponse> (); // Services.Responses.ConfigurationImportResponse importResponse = new Mercury.Server.Services.Responses.ConfigurationImportResponse (); // importResponse.ObjectType = objectNode.Name; // importResponse.ObjectName = objectNode.Attributes["Name"].InnerText; // importResponse.Success = true; // if (importResponse.ObjectType == "WorkQueueView") { // foreach (System.Xml.XmlNode currentNode in objectNode.ChildNodes) { // switch (currentNode.Name) { // case "Properties": // foreach (System.Xml.XmlNode currentProperty in currentNode.ChildNodes) { // switch (currentProperty.Attributes["Name"].InnerText) { // case "WorkQueueViewName": workQueueViewName = currentProperty.InnerText; break; // case "Description": description = currentProperty.InnerText; break; // case "Enabled": enabled = Convert.ToBoolean (currentProperty.InnerText); break; // case "Visible": visible = Convert.ToBoolean (currentProperty.InnerText); break; // } // } // break; // } // } // importResponse.Success = Save (); // importResponse.Id = Id; // if (!importResponse.Success) { importResponse.SetException (base.application.LastException); } // } // else { importResponse.SetException (new ApplicationException ("Invalid Object Type Parsed as WorkQueueView.")); } // response.Add (importResponse); // return response; //} #endregion #region Validation Functions public Dictionary <String, String> ValidateFieldDefinition(WorkQueueViewFieldDefinition fieldDefinition) { Dictionary <String, String> validationResponse = new Dictionary <String, String> (); fieldDefinition.DisplayName = fieldDefinition.DisplayName.Trim(); fieldDefinition.PropertyName = fieldDefinition.PropertyName.Trim(); if (String.IsNullOrEmpty(fieldDefinition.DisplayName.Trim())) { validationResponse.Add("Display Name", "Empty or Null."); } if (String.IsNullOrEmpty(fieldDefinition.PropertyName.Trim())) { validationResponse.Add("Property Name", "Empty or Null."); } System.Text.RegularExpressions.Regex expressionSpecialCharacters; String excludedCharacters = String.Empty; excludedCharacters = excludedCharacters + @"\\|/|\.|,|'|~|`|!|@|#|\$|%|\^|&|\*|\(|\)|\-|\+|\=|\{|\}|\[|\]|:|;|\?|<|>"; expressionSpecialCharacters = new System.Text.RegularExpressions.Regex(excludedCharacters); if (expressionSpecialCharacters.IsMatch(fieldDefinition.DisplayName)) { validationResponse.Add("Display Name", "Special Characters not allowed."); } foreach (WorkQueueViewFieldDefinition currentFieldDefinition in fieldDefinitions) { if (currentFieldDefinition != fieldDefinition) { if (currentFieldDefinition.DisplayName == fieldDefinition.DisplayName) { validationResponse.Add("Display Name", "Duplicate."); } if (currentFieldDefinition.PropertyName == fieldDefinition.PropertyName) { validationResponse.Add("Property Name", "Duplicate."); } } } if (WellKnownFields.ContainsKey(fieldDefinition.DisplayName)) { if (!validationResponse.ContainsKey("Display Name")) { validationResponse.Add("Display Name", "Reserved Name not allowed."); } } return(validationResponse); }
protected void Validate_Numeric3(object source, ServerValidateEventArgs args) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[A-Z,a-z]+$"); args.IsValid = r.IsMatch(txtcity.Text); }
public virtual bool FormatSuggestions(String prefixText, String resultItem, int columnLength, String AutoTypeAheadDisplayFoundText, String autoTypeAheadSearch, String AutoTypeAheadWordSeparators, ArrayList resultList, bool stripHTML) { if (stripHTML) { prefixText = StringUtils.ConvertHTMLToPlainText(prefixText); resultItem = StringUtils.ConvertHTMLToPlainText(resultItem); } // Formats the result Item and adds it to the list of suggestions. int index = resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).IndexOf(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture)); String itemToAdd = null; bool isFound = false; bool isAdded = false; if (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("wordsstartingwithsearchstring") && !(index == 0)) { // Expression to find word which contains AutoTypeAheadWordSeparators followed by prefixText System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex1.IsMatch(resultItem)) { index = regex1.Match(resultItem).Index; isFound = true; } //If the prefixText is found immediatly after white space then starting of the word is found so don not search any further if (resultItem[index].ToString() != " ") { // Expression to find beginning of the word which contains AutoTypeAheadWordSeparators followed by prefixText System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\S*" + AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (regex.IsMatch(resultItem)) { index = regex.Match(resultItem).Index; isFound = true; } } } // If autoTypeAheadSearch value is wordsstartingwithsearchstring then, extract the substring only if the prefixText is found at the // beginning of the resultItem (index = 0) or a word in resultItem is found starts with prefixText. if (index == 0 || isFound || StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring")) { if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("atbeginningofmatchedstring")) { // Expression to find beginning of the word which contains prefixText System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex("\\S*" + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Find the beginning of the word which contains prefexText if (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") && regex1.IsMatch(resultItem)) { index = regex1.Match(resultItem).Index; isFound = true; } // Display string from the index till end of the string if, sub string from index till end of string is less than columnLength value. if ((resultItem.Length - index) <= columnLength) { if (index == 0) { itemToAdd = resultItem; } else { itemToAdd = resultItem.Substring(index); } } else { itemToAdd = StringUtils.GetSubstringWithWholeWords(resultItem, index, index + columnLength, StringUtils.Direction.forward); } } else if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("inmiddleofmatchedstring")) { int subStringBeginIndex = (int)(columnLength / 2); if (resultItem.Length <= columnLength) { itemToAdd = resultItem; } else { // Sanity check at end of the string if (((index + prefixText.Length) >= resultItem.Length - 1) || (resultItem.Length - index < subStringBeginIndex)) { itemToAdd = StringUtils.GetSubstringWithWholeWords(resultItem, resultItem.Length - 1 - columnLength, resultItem.Length - 1, StringUtils.Direction.backward); } else if (index <= subStringBeginIndex) { // Sanity check at beginning of the string itemToAdd = StringUtils.GetSubstringWithWholeWords(resultItem, 0, columnLength, StringUtils.Direction.forward); } else { // Display string containing text before the prefixText occures and text after the prefixText itemToAdd = StringUtils.GetSubstringWithWholeWords(resultItem, index - subStringBeginIndex, index - subStringBeginIndex + columnLength, StringUtils.Direction.both); } } } else if (StringUtils.InvariantLCase(AutoTypeAheadDisplayFoundText).Equals("atendofmatchedstring")) { // Expression to find ending of the word which contains prefexText System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex("\\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Find the ending of the word which contains prefexText if (regex1.IsMatch(resultItem, index + 1)) { index = regex1.Match(resultItem, index + 1).Index; } else { // If the word which contains prefexText is the last word in string, regex1.IsMatch returns false. index = resultItem.Length; } if (index > resultItem.Length) { index = resultItem.Length; } // If text from beginning of the string till index is less than columnLength value then, display string from the beginning till index. if (index <= columnLength) { itemToAdd = resultItem.Substring(0, index); } else { // Truncate the string to show only columnLength has to be appended. itemToAdd = StringUtils.GetSubstringWithWholeWords(resultItem, index - columnLength, index, StringUtils.Direction.backward); } } // Remove newline character from itemToAdd int prefixTextIndex = itemToAdd.IndexOf(prefixText, StringComparison.CurrentCultureIgnoreCase); if (prefixTextIndex < 0) { return(false); } // If itemToAdd contains any newline after the search text then show text only till newline System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex("(\r\n|\n)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); int newLineIndexAfterPrefix = -1; if (regex2.IsMatch(itemToAdd, prefixTextIndex)) { newLineIndexAfterPrefix = regex2.Match(itemToAdd, prefixTextIndex).Index; } if ((newLineIndexAfterPrefix > -1)) { itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix); } // If itemToAdd contains any newline before search text then show text which comes after newline System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex("(\r\n|\n)", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.RightToLeft); int newLineIndexBeforePrefix = -1; if (regex3.IsMatch(itemToAdd, prefixTextIndex)) { newLineIndexBeforePrefix = regex3.Match(itemToAdd, prefixTextIndex).Index; } if ((newLineIndexBeforePrefix > -1)) { itemToAdd = itemToAdd.Substring(newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length); } if (!string.IsNullOrEmpty(itemToAdd) && !resultList.Contains(itemToAdd)) { resultList.Add(itemToAdd); isAdded = true; } } return(isAdded); }
/// <summary> /// Converts an XML document to an IJavaScriptObject (JSON). /// <see cref="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html?page=1">Stefan Goessner</see> /// <see cref="http://developer.yahoo.com/common/json.html#xml">Yahoo XML JSON</see> /// </summary> /// <param name="n">The XmlNode to serialize to JSON.</param> /// <returns>A IJavaScriptObject.</returns> public static IJavaScriptObject GetIJavaScriptObjectFromXmlNode(XmlNode n) { if (n == null) { return(null); } //if (xpath == "" || xpath == "/") // xpath = n.Name; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+|\W+", System.Text.RegularExpressions.RegexOptions.Compiled); JavaScriptObject o = new JavaScriptObject(); if (n.NodeType == XmlNodeType.Element) { for (int i = 0; i < n.Attributes.Count; i++) { o.Add("@" + n.Attributes[i].Name, new JavaScriptString(n.Attributes[i].Value)); } if (n.FirstChild != null) // element has child nodes { int textChild = 0; bool hasElementChild = false; for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling) { if (e.NodeType == XmlNodeType.Element) { hasElementChild = true; } if (e.NodeType == XmlNodeType.Text && r.IsMatch(e.InnerText)) { textChild++; // non-whitespace text } } if (hasElementChild) { if (textChild < 2) // structured element with evtl. a single text node { for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling) { if (e.NodeType == XmlNodeType.Text) { o.Add("#text", new JavaScriptString(e.InnerText)); } else if (o.Contains(e.Name)) { if (o[e.Name] is JavaScriptArray) { ((JavaScriptArray)o[e.Name]).Add(GetIJavaScriptObjectFromXmlNode(e)); } else { IJavaScriptObject _o = o[e.Name]; JavaScriptArray a = new JavaScriptArray(); a.Add(_o); a.Add(GetIJavaScriptObjectFromXmlNode(e)); o[e.Name] = a; } } else { o.Add(e.Name, GetIJavaScriptObjectFromXmlNode(e)); } } } } else if (textChild > 0) { if (n.Attributes.Count == 0) { return(new JavaScriptString(n.InnerText)); } else { o.Add("#text", new JavaScriptString(n.InnerText)); } } } if (n.Attributes.Count == 0 && n.FirstChild == null) { return(new JavaScriptString(n.InnerText)); } } else if (n.NodeType == XmlNodeType.Document) { return(GetIJavaScriptObjectFromXmlNode(((XmlDocument)n).DocumentElement)); } else { throw new NotSupportedException("Unhandled node type '" + n.NodeType + "'."); } return(o); }
/// <summary> /// A helper method to attempt to discover known SqlInjection attacks. /// For use when using one of the flexible non-parameterized access methods, such as GetPaged() /// </summary> /// <param name="whereClause">string of the whereClause to check</param> /// <returns>true if found, false if not found </returns> public static bool DetectSqlInjection(string whereClause) { return regSystemThreats.IsMatch(whereClause); }
public static bool SimplifiedToEnglish(string strChinese, ref string strEnglish, bool bUpperFirstLetter, int nSeparatePolicy, string strSeparator) { try { if (m_xpathDoc == null || m_xpathNav == null) { string strFile = HttpContext.Current.Server.MapPath("~/Configurations/PinYin/pingyin.xml"); if (!File.Exists(strFile)) { //throw new FileNotFoundException("拼音文件不存在"); return(false); } m_xpathDoc = new XPathDocument(strFile); m_xpathNav = m_xpathDoc.CreateNavigator(); } bool bFirst = false; string strTemp = ""; strEnglish.Remove(0, strEnglish.Length); strChinese = strChinese.Trim(); if (strChinese.Length == 0) { return(true); } System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[\u2E80-\u9FFF]+$"); foreach (char sz in strChinese) { if (reg.IsMatch(sz.ToString()))//HZ { string strHz = string.Format("/catalog/hz[Character='{0}']/Spell", sz); // Compile a standard XPath expression XPathExpression expr; //if (m_xpathNav == null) //{ // OpenPingyinFile(); //} if (m_xpathNav == null) { return(false); } expr = m_xpathNav.Compile(strHz); XPathNodeIterator iterator = m_xpathNav.Select(expr); if (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); string[] polyphones = null; polyphones = nav2.Value.Split("|".ToCharArray()); var strLetter = (polyphones.Length == 1 ? polyphones[0] : polyphones[1]); if (bUpperFirstLetter) { string strFirstLetter = strLetter.Substring(0, 1); string strLast = strLetter.Remove(0, 1); strLetter = strFirstLetter.ToUpper() + strLast; } //the surname if (strTemp.Length == 0) { strTemp = strLetter; } else { if (nSeparatePolicy == 1) { strTemp += strSeparator; } else { if (!bFirst) { strTemp += strSeparator; bFirst = true; } } strTemp += strLetter; } } else { strHz = sz.ToString(); if (bUpperFirstLetter) { string strFirstLetter = strHz.Substring(0, 1); string strLast = strHz.Remove(0, 1); strHz = strFirstLetter.ToUpper() + strLast; } if (strTemp.Length == 0) { strTemp += strHz; } else { if (nSeparatePolicy == 1) { strTemp += strSeparator; } else { if (!bFirst) { strTemp += strSeparator; bFirst = true; } } strTemp += strHz; } } } else { strTemp += sz; } } strEnglish = strTemp; } catch (Exception ex) { return(false); } return(true); }
// when save button clicks private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection(conURL); // connection opens con.Open(); if (buffer < 0) // for creation of new data { try { // here check whether boxes are empty for not if (String.IsNullOrEmpty(textBoxName.Text) || String.IsNullOrEmpty(textBoxEmail.Text) || String.IsNullOrEmpty(comboBox1.Text)) { MessageBox.Show("Fill First Name, Email, Designation must"); } else { if (isalphaTest(textBoxName.Text) && (String.IsNullOrEmpty(textBoxLast.Text) || (!String.IsNullOrEmpty(textBoxLast.Text) && (isalphaTest(textBoxLast.Text)))) && Convert.ToDouble(textBoxSalary.Text) >= 0 && (String.IsNullOrEmpty(textBoxContact.Text) || (!String.IsNullOrEmpty(textBoxContact.Text) && contactNoValid(textBoxContact.Text)))) { // getting value of radio button string val = ""; bool isCheck = male.Checked; if (isCheck) { val = male.Text; } bool isCheck2 = female.Checked; if (isCheck2) { val = female.Text; } System.Text.RegularExpressions.Regex expr = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"); if (expr.IsMatch(textBoxEmail.Text)) { string cmdText = "INSERT INTO Person (FirstName,LastName, Contact, Email, DateOfBirth, Gender ) VALUES (@FirstName,@LastName, @Contact, @Email, @DateOfBirth, (SELECT Id FROM Lookup WHERE Category = 'Gender' AND Value = @Value))"; SqlCommand c = new SqlCommand(cmdText, con); c.Parameters.Add(new SqlParameter("@FirstName", textBoxName.Text)); c.Parameters.Add(new SqlParameter("@LastName", textBoxLast.Text)); c.Parameters.Add(new SqlParameter("@Contact", textBoxContact.Text)); c.Parameters.Add(new SqlParameter("@Email", textBoxEmail.Text)); c.Parameters.Add(new SqlParameter("@DateOfBirth", dateTimePicker1.Text)); c.Parameters.Add(new SqlParameter("@Value", val)); //execute it int result = c.ExecuteNonQuery(); if (result < 0) { MessageBox.Show("Error"); } string cmdText3 = "INSERT INTO Advisor (Id, Designation, Salary) VALUES((SELECT Id FROM Person WHERE Email = @Email AND Contact = @Contact AND FirstName = @FirstName), (SELECT Id FROM Lookup WHERE Category = 'DESIGNATION' AND Value = @Value), @Salary)"; SqlCommand c3 = new SqlCommand(cmdText3, con); c3.Parameters.Add(new SqlParameter("@FirstName", textBoxName.Text)); c3.Parameters.Add(new SqlParameter("@Contact", textBoxContact.Text)); c3.Parameters.Add(new SqlParameter("@Email", textBoxEmail.Text)); c3.Parameters.Add(new SqlParameter("@Value", comboBox1.Text)); c3.Parameters.Add(new SqlParameter("@Salary", textBoxSalary.Text)); c3.ExecuteNonQuery(); // connection closed // show dialog box if added MessageBox.Show("Successfully Added"); con.Close(); this.Hide(); Advisor datap = new Advisor(); datap.ShowDialog(); this.Close(); // close the form } else { throw new ArgumentNullException(); } } else { throw new ArgumentNullException(); } } } catch (Exception) { MessageBox.Show("Enter Name, Email, Salary in correct Format!! Name should be all alphabets, no extra spaces. email should have at least 4 chars before @ . contact should have digits"); } } else // for updation of data { try { if (isalphaTest(textBoxName.Text) && (String.IsNullOrEmpty(textBoxLast.Text) || (!String.IsNullOrEmpty(textBoxLast.Text) && (isalphaTest(textBoxLast.Text)))) && Convert.ToDouble(textBoxSalary.Text) >= 0 && (String.IsNullOrEmpty(textBoxContact.Text) || (!String.IsNullOrEmpty(textBoxContact.Text) && contactNoValid(textBoxContact.Text)))) { string val = ""; bool isCheck = male.Checked; if (isCheck) { val = male.Text; } bool isCheck2 = female.Checked; if (isCheck2) { val = female.Text; } System.Text.RegularExpressions.Regex expr = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"); if (expr.IsMatch(textBoxEmail.Text)) { string cmdText2 = "Update Person SET FirstName = @FirstName ,LastName =@LastName , Contact = @Contact, Email = @Email, DateOfBirth = @DateOfBirth, Gender = (SELECT Id FROM Lookup WHERE Category = 'Gender' AND Value = @Value) WHERE Id = @Id"; SqlCommand c2 = new SqlCommand(cmdText2, con); c2.Parameters.Add(new SqlParameter("@Id", buffer)); c2.Parameters.Add(new SqlParameter("@FirstName", textBoxName.Text)); c2.Parameters.Add(new SqlParameter("@LastName", textBoxLast.Text)); c2.Parameters.Add(new SqlParameter("@Contact", textBoxContact.Text)); c2.Parameters.Add(new SqlParameter("@Email", textBoxEmail.Text)); c2.Parameters.Add(new SqlParameter("@DateOfBirth", dateTimePicker1.Text)); c2.Parameters.Add(new SqlParameter("@Value", val)); c2.ExecuteNonQuery(); string cmdText3 = "Update Advisor SET Designation = (SELECT Id FROM Lookup WHERE Category = 'DESIGNATION' AND Value = @Value), Salary = @Salary where Id = @Id"; SqlCommand c3 = new SqlCommand(cmdText3, con); c3.Parameters.Add(new SqlParameter("@Id", buffer)); c3.Parameters.Add(new SqlParameter("@Value", comboBox1.Text)); c3.Parameters.Add(new SqlParameter("@Salary", textBoxSalary.Text)); c3.ExecuteNonQuery(); MessageBox.Show("Successfully Updated!!"); con.Close(); this.Hide(); Advisor datap = new Advisor(); datap.ShowDialog(); this.Close(); // close the form } else { throw new ArgumentNullException(); } } else { throw new ArgumentNullException(); } } catch (Exception) { MessageBox.Show("Enter Name, Email, Salary in correct Format!! Name should be all alphabets, no extra spaces and Enter Name, Email, Designation must. email should have at least 4 chars before @. contact should have digits!!"); } } }
//allow to input only numbers private void NumericOnly(object sender, TextCompositionEventArgs e) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^[0-9]"); e.Handled = !reg.IsMatch(e.Text); }
private bool IsHex(string text) { var reg = new System.Text.RegularExpressions.Regex("^[0-9A-Fa-f]*$"); return(reg.IsMatch(text)); }
internal static bool IsText(this List <Token> list, int index) => list[index].Type != 2 && Text.IsMatch(list[index].ToString());
//txbInventoryCount_PreviewTextInput private void txbInventoryCount_PreviewTextInput(object sender, TextCompositionEventArgs e) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[0-9]$"); e.Handled = !regex.IsMatch(e.Text); }
private void Register() { string UID = g_Context.Request["user_id"]; string NAME = g_Context.Request["user_name"]; if (string.IsNullOrEmpty(NAME)) { NAME = UID; } string PWD = g_Context.Request["password"]; string PWD_CK = g_Context.Request["password_ck"]; string AUTH_CODE = g_Context.Request["auth_code"]; if (UID == "") { SendError sendError = new SendError("100", "登陆名不能为空", "user_id"); Send(sendError); return; } System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$"); if (!reg1.IsMatch(UID)) { SendError sendError = new SendError("100", "登陆名只能是英文字母或者数字", "user_id"); Send(sendError); return; } if (PWD == "") { SendError sendError = new SendError("100", "密码不能为空", "password"); Send(sendError); return; } if (PWD_CK == "") { SendError sendError = new SendError("100", "密码确认不能为空", "password_ck"); Send(sendError); return; } if (PWD != PWD_CK) { SendError sendError = new SendError("100", "两次输入密码不一致", "password"); Send(sendError); return; } if (AUTH_CODE == "") { SendError sendError = new SendError("100", "注册邀请码不能为空", "auth_code"); Send(sendError); return; } //验证账户登录名的有效性 string sql = string.Format(@"SELECT COUNT(1) AS T,'A' AS F FROM ARES_USER WHERE UID=@UID UNION ALL SELECT COUNT(1),'B' FROM ARES_AUTHCODE WHERE AUTH_CODE=@AUTH_CODE AND STATUS=0"); DataTable dt = DbHelperSQL.QueryTable(sql, new SqlParameter[] { new SqlParameter("@UID", UID), new SqlParameter("@AUTH_CODE", AUTH_CODE) }); if (dt != null && dt.Rows.Count > 0) { bool CanReg = false; foreach (DataRow row in dt.Rows) { if (row["F"].ToString() == "A") { if (Convert.ToInt32(row["T"]) > 0) { SendError sendError = new SendError("100", "用户名已存在,请更换后重试", "user_id"); Send(sendError); return; } else { CanReg = true; } } else { if (Convert.ToInt32(row["T"]) == 0) { SendError sendError = new SendError("100", "注册邀请码已经失效,请更换后重试", "auth_code"); Send(sendError); return; } } } if (CanReg) { //注册信息 Hashtable hs = new Hashtable(); hs.Add("insert into ARES_USER (UID,NAME,PWD,RegistDate,AdminLv) values(@UID,@NAME,@PWD,GETDATE(),@AdminLv)", new SqlParameter[] { new SqlParameter("@UID", UID), new SqlParameter("@NAME", NAME), new SqlParameter("@PWD", System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(PWD, "MD5")), new SqlParameter("@AdminLv", "1") }); //更新邀请码状态 hs.Add("update ARES_AUTHCODE set STATUS=1,UID=@UID where AUTH_CODE=@AUTH_CODE", new SqlParameter[] { new SqlParameter("@UID", UID), new SqlParameter("@AUTH_CODE", AUTH_CODE) }); //分配菜单 (上线前请注释) hs.Add("insert into ARES_USER_ROLE_LINK (USER_ID,ROLE_ID) values(@UID,1)", new SqlParameter[] { new SqlParameter("@UID", UID) }); try { DbHelperSQL.ExecuteSqlTran(hs); SendError sendError = new SendError("200", "注册成功,请返回登陆!", "auth_code"); Send(sendError); return; } catch (Exception e) { SendError sendError = new SendError("100", e.ToString(), "auth_code"); Send(sendError); return; } } } }
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); }
private static bool IsTextNumeric(string str) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]+"); return(reg.IsMatch(str)); }
//男士西服裤子001解析 public static bool N_XF_KZ_001(HttpFileCollectionBase files, out string errMsg, out object data) { try { errMsg = ""; data = null; #region 解析excel DataTable table = Analysis.Excel_analysis_trousrs(files); #endregion List <OriginalDataTrousers> cslist = new List <OriginalDataTrousers>(); #region 验证并处理数据 for (int i = 0; i < table.Rows.Count; i++) { OriginalDataTrousers ts = new OriginalDataTrousers(); ts.Order_no = table.Rows[i]["order_no"] + ""; int tyint = 0; if (int.TryParse(table.Rows[i]["order_xc"] + "", out tyint)) { ts.Order_xc = tyint; } else { ts.Order_xc = 0; } ts.Name = table.Rows[i]["name"] + ""; ts.Ret_code_size = table.Rows[i]["ret_code_size"] + ""; if (int.TryParse(table.Rows[i]["number"] + "", out tyint)) { ts.Number = tyint; } else { ts.Number = 0; } ts.Remarks = table.Rows[i]["remarks"] + ""; cslist.Add(ts); } #endregion data = cslist; #region 对比数据 DataTable rettable = new DataTable(); List <Entity.Ret_CodeTrousers> ct = new List <Ret_CodeTrousers>(); for (int i = 0; i < table.Rows.Count; i++) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"//^\s*[\u4E00-\u9FA5\s]\s*[0-9]\s*[0-9]\s*[0-9_a-z_A-Z]\s*"); if (reg1.IsMatch(table.Rows[i]["ret_code_size"] + "")) { DataRow rerow = rettable.NewRow(); rettable.Rows.Add(rerow); } } #endregion return(true); } catch (Exception) { throw; } }
private static bool IsTextAllowed(string text) { return(!regex.IsMatch(text)); }
public static bool IsGraphic(string FileName) { System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex (@"\.ico$|\.tiff$|\.gif$|\.jpg$|\.jpeg$|\.png$|\.bmp$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return(Regex.IsMatch(FileName)); }
private static bool isOperator(string expr) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[<=>&]"); return(regex.IsMatch(expr)); }
static public Dictionary <string, string> GetComPortsWithDeviceDescription(string friendlyNamePrefix) { Dictionary <string, string> result = new Dictionary <string, string>(); const string className = "Ports"; Guid[] guids = GetClassGUIDs(className); System.Text.RegularExpressions.Regex friendlyNameToComPort = new System.Text.RegularExpressions.Regex(@".? \((COM\d+)\)$"); // "..... (COMxxx)" -> COMxxxx foreach (Guid guid in guids) { string key = ""; string value = ""; // We start at the "root" of the device tree and look for all // devices that match the interface GUID of a disk Guid guidClone = guid; IntPtr h = SetupDiGetClassDevs(ref guidClone, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_PROFILE); if (h.ToInt32() != INVALID_HANDLE_VALUE) { int nDevice = 0; while (true) { SP_DEVINFO_DATA da = new SP_DEVINFO_DATA(); da.cbSize = (uint)Marshal.SizeOf(da); if (0 == SetupDiEnumDeviceInfo(h, nDevice++, ref da)) { break; } uint RegType; byte[] ptrBuf = new byte[BUFFER_SIZE]; uint RequiredSize; if (SetupDiGetDeviceRegistryProperty(h, ref da, (uint)SPDRP.FRIENDLYNAME, out RegType, ptrBuf, BUFFER_SIZE, out RequiredSize)) { const int utf16terminatorSize_bytes = 2; string friendlyName = System.Text.UnicodeEncoding.Unicode.GetString(ptrBuf, 0, (int)RequiredSize - utf16terminatorSize_bytes); if (!friendlyName.StartsWith(friendlyNamePrefix)) { continue; } if (!friendlyNameToComPort.IsMatch(friendlyName)) { continue; } key = friendlyNameToComPort.Match(friendlyName).Groups[1].Value; } else { key = "N/A"; } DEVPROPKEY DEVPKEY_Device_BusReportedDeviceDesc = new DEVPROPKEY { fmtid = new Guid((uint)0x540b947e, (ushort)0x8b40, (ushort)0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2), pid = 4 }; ulong propertyRegDataType = 0; int requiredSize = 0; byte[] buffer = new byte[BUFFER_SIZE]; //IntPtr buffer = Marshal.AllocHGlobal(1024); if (SetupDiGetDevicePropertyW(h, ref da, ref DEVPKEY_Device_BusReportedDeviceDesc, out propertyRegDataType, buffer, 1024, out requiredSize, 0)) { const int utf16terminatorSize_bytes = 2; string busReportedDeviceDesc = System.Text.UnicodeEncoding.Unicode.GetString(buffer, 0, (int)requiredSize - utf16terminatorSize_bytes); value = busReportedDeviceDesc; Console.WriteLine(busReportedDeviceDesc); } else { value = "N/A"; } result.Add(key, value); } // devices SetupDiDestroyDeviceInfoList(h); } } // class guids return(result); }
public static bool IsValidEmailAddress(this string email) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); return(regex.IsMatch(email)); }
private bool IsInts(string str) { System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$"); return(rex.IsMatch(str)); }
private void button2_Click(object sender, EventArgs e) //发送 { int dwFlag = 0; if (!InternetGetConnectedState(ref dwFlag, 0)) { if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-CN") { MessageBox.Show("Opps~~~若要顺利发邮件,请您先插好网线!", "Aurora智能提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-Hant") { MessageBox.Show("Opps~~~若要順利發郵件,請您先插好網線!", "Aurora智慧提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else //if (Thread.CurrentThread.CurrentUICulture.ToString() == "en") { MessageBox.Show("Opps~~~Please connect to Internet first!", "Aurora Intelligent Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { string regexEmail = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"; System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline) | System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Regex regEmail = new System.Text.RegularExpressions.Regex(regexEmail, options); string email = textBox1.Text; if (!regEmail.IsMatch(email))//email 填写符合正则表达式 { if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-CN") { MessageBox.Show("Email格式错误!", "Aurora智能提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-Hant") { MessageBox.Show("Email格式錯誤!", "Aurora智慧提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else //if (Thread.CurrentThread.CurrentUICulture.ToString() == "en") { MessageBox.Show("Wrong Email format!", "Aurora Intelligent Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } if (textBox2.Text.Trim().ToString() == "") { if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-CN") { MessageBox.Show("请填写邮件主题!", "Aurora智能提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-Hant") { MessageBox.Show("請填寫郵件主題!", "Aurora智慧提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else //if (Thread.CurrentThread.CurrentUICulture.ToString() == "en") { MessageBox.Show("Don't forget Email theme!", "Aurora Intelligent Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } try { if (this.textBox4.Text.Trim().ToString() != "") { //发送 SmtpClient Client = new SmtpClient("smtp.qq.com"); //设置邮件协议 Client.UseDefaultCredentials = false; //这一句得写前面 Client.DeliveryMethod = SmtpDeliveryMethod.Network; //通过网络发送到Smtp服务器 Client.Credentials = new NetworkCredential("xxxxxx", "xxxxx"); //通过用户名和密码 认证 MailMessage Mail = new MailMessage("xxxxxx", "xxxxxx"); Mail.Subject = "【Aurora反馈】" + this.textBox2.Text.Trim().ToString(); Mail.SubjectEncoding = Encoding.UTF8; //主题编码 Mail.Body = "来自:" + textBox1.Text.Trim().ToString() + "\r\n" + "主题:" + textBox2.Text.Trim().ToString() + "\r\n" + "内容:" + "\r\n" + this.textBox4.Text.Trim().ToString(); Mail.BodyEncoding = Encoding.UTF8; //正文编码 Mail.IsBodyHtml = false; //设置为HTML格式 Mail.Priority = MailPriority.Normal; //优先级 //附件 if (textBox3.Text.Length > 0) { Mail.Attachments.Add(new Attachment(textBox3.Text, MediaTypeNames.Application.Octet)); } Client.Send(Mail); if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-CN") { MessageBox.Show("邮件发送成功!", "Aurora智能提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-Hant") { MessageBox.Show("郵件發送成功!", "Aurora智慧提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else //if (Thread.CurrentThread.CurrentUICulture.ToString() == "en") { MessageBox.Show("Email send success!", "Aurora Intelligent Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-CN") { MessageBox.Show("请填写邮件内容!", "Aurora智能提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (Thread.CurrentThread.CurrentUICulture.ToString() == "zh-Hant") { MessageBox.Show("請填寫郵件內容!", "Aurora智慧提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else //if (Thread.CurrentThread.CurrentUICulture.ToString() == "en") { MessageBox.Show("Please complete Email content!", "Aurora Intelligent Tips", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
private ThreadParameters getThreadParameters() { ThreadParameters parameters = new ThreadParameters(); parameters.SourceDirectories = stripBlankLines(richTextBox_SourceDirectories.Lines); parameters.ImageFileExtensions = stripBlankLines(richTextBox_ImageFileExtensions.Lines); parameters.ExcludeFileExtensions = stripBlankLines(richTextBox_ExcludeFileExtensions.Lines); System.Collections.Generic.List <string> includeFileExtensions = new System.Collections.Generic.List <string>(); System.Collections.Generic.List <string> includeFileNameExtensions = new System.Collections.Generic.List <string>(); foreach (string line in richTextBox_IncludeFileExtensions.Lines) { if (line.Length > 0 && fileExtensionPattern.IsMatch(line)) { includeFileExtensions.Add(line); } else { includeFileNameExtensions.Add(line); } } parameters.IncludeFileExtensions = includeFileExtensions.ToArray(); parameters.IncludeFileExtensionAndFileNameMap = new System.Collections.Generic.Dictionary <string, System.Text.RegularExpressions.Regex>(); foreach (string includeFileName in includeFileNameExtensions) { string pattern = System.IO.Path.GetFileNameWithoutExtension(includeFileName); if (pattern == "*") { includeFileExtensions.Add(System.IO.Path.GetExtension(includeFileName)); parameters.IncludeFileExtensions = includeFileExtensions.ToArray(); continue; } else if (pattern.Length == 0) { continue; } if (!parameters.IncludeFileExtensionAndFileNameMap.ContainsKey(System.IO.Path.GetExtension(includeFileName))) { parameters.IncludeFileExtensionAndFileNameMap.Add(System.IO.Path.GetExtension(includeFileName), new System.Text.RegularExpressions.Regex(pattern)); } } parameters.SearchDirectoriesBypassPatterns = stripBlankLines(richTextBox_SearchDirectoriesBypassPatterns.Lines); System.Collections.Generic.List <System.Text.RegularExpressions.Regex> regexList = new System.Collections.Generic.List <System.Text.RegularExpressions.Regex>(); foreach (string bypassPattern in parameters.SearchDirectoriesBypassPatterns) { regexList.Add(new System.Text.RegularExpressions.Regex(bypassPattern)); } parameters.BypassRegexes = regexList.ToArray(); if (richTextBox_SourcePaths.Text.EndsWith(getCollectPhotoDataExtension())) { parameters.LogFilePath_ThreadResult = richTextBox_SourcePaths.Lines[richTextBox_SourcePaths.Lines.Length - 1]; } else { parameters.SourcePaths = richTextBox_SourcePaths.Lines; } parameters.DestinationRootDirectory = richTextBox_DestinationRootDirectory.Text; parameters.DestinationSubDirectories = stripBlankLines(richTextBox_DestinationSubDirectories.Lines); parameters.FileNameComponent = stripBlankLines(richTextBox_FileNameComponent.Lines); parameters.Command = richTextBox_Command.Text; parameters.CommandOptions = richTextBox_CommandOptions.Text; parameters.SearchDirectoryDeepnessLimitation = getSearchDirectoryDeepnessLimitation(); parameters.AutoStart = checkBox_AutoStart.Checked; parameters.AutoDetermine = checkBox_AutoDetermine.Checked; parameters.FilterWhileSearching = checkBox_FilterWhileSearching.Checked; parameters.CopyLowGradeImage = checkBox_CopyLowGradeImage.Checked; parameters.DeleteAfterCopy = checkBox_DeleteAfterCopy.Checked; parameters.DeleteSourceIfDestinationAlreadyExists = checkBox_DeleteAlreadyExists.Checked; parameters.DeleteReadOnly = checkBox_DeleteReadOnly.Checked; parameters.AutoRename = checkBox_AutoRename.Checked; parameters.MultipleJobs = checkBox_MultipleJobs.Checked; parameters.CreateSubDestinationRootDirectory = checkBox_CreateSubDestinationRootDirectory.Checked; try { FileWriterWithAppendMode logger = FileWriterWithAppendMode.Open(buildCollectPhotoLogFilePath(richTextBox_DestinationRootDirectory.Text, CultureStrings.TextTaskParameters)); string configContent = GetConfigContent(parameters); logger.Write(configContent); logger.Close(); } catch (System.Exception ex) { logException(ex); } return(parameters); }
public static IEnumerable <string> GetFiles(this string path, string regexPattern = "", SearchOption searchOption = SearchOption.TopDirectoryOnly) { System.Text.RegularExpressions.Regex reSearchPattern = new System.Text.RegularExpressions.Regex(regexPattern); return(Directory.EnumerateFiles(path, "*", searchOption).Where(file => reSearchPattern.IsMatch(Path.GetFileName(file)))); }
public static bool IsLetterOrNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$"); return(reg1.IsMatch(str)); }