public static string UpdateStatus(string status, TwUser user, string replyId) { Regex regex = new Regex(@"\[(.*?)\]"); List<FileInfo> media = new List<FileInfo>(); foreach (System.Text.RegularExpressions.Match match in regex.Matches(status)) { status = status.Replace(match.Value, ""); FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", "")); if (!file.Exists) throw new FileNotFoundException("File not found", file.FullName); media.Add(file); } if (media.Count > 4) //limited by the twitter API throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet"); if (user == null) user = TwUser.LoadCredentials(); string encodedStatus = Util.EncodeString(status); if (media.Count == 0) return InternalUpdateStatus(user, encodedStatus, replyId); else return InternalUpdateWithMedia(user, encodedStatus, replyId, media); }
private IEnumerable<string> LoadProjects( string solutionPath) { const string projectRegEx = "Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\""; var content = File.ReadAllText(solutionPath); var projReg = new Regex(projectRegEx, RegexOptions.Compiled); var matches = projReg.Matches(content).Cast<Match>(); var projects = matches.Select(x => x.Groups[2].Value).ToList(); for (var i = 0; i < projects.Count; ++i) { if (!Path.IsPathRooted(projects[i])) { var folderName = Path.GetDirectoryName(solutionPath); if (folderName != null) projects[i] = Path.Combine(folderName, projects[i]); } try { projects[i] = Path.GetFullPath(projects[i]); } catch (NotSupportedException ex) { resolver_ProgressMessageEvent($"Path: {projects[i]}, Error: {ex.Message}"); } } return projects; }
public override IEnumerable<IVertex> GetMatchingVertices(IVertexType myInterestingVertexType) { Regex regexpression; try { regexpression = new Regex((String)_constant.Value); } catch (Exception e) { throw new InvalidLikeOperationException(String.Format("Invalid regular expression given:{0}{1}", Environment.NewLine, e.Message), e); } foreach (var aVertex in _vertexStore.GetVerticesByTypeID(_securityToken, _transactionToken, myInterestingVertexType.ID, _property.Edition, VertexRevisionFilter)) { var value = _property.Property.GetValue(aVertex); if (value != null && (regexpression.IsMatch((String)value))) { yield return aVertex; } } yield break; }
/// <summary> /// Обрабатывает шаблон, вставляет значение полей моделей в макросы в шаблоне /// </summary> /// <param name="content"></param> /// <returns></returns> protected override string Process(string content) { // Подгатавливаем данные var parseRegEx = new Regex(@"\$\{([A-Za-z0-9]+?)\}"); var sb = new StringBuilder(content); var ti = Model.GetType(); // Находим все вхождения макросов по регулярному выражению var matches = parseRegEx.Matches(content); foreach (Match match in matches) { var propertyName = match.Groups[1].Value; // Ищем свойство у модели var propertyInfo = ti.GetProperty(propertyName); if (propertyInfo == null) { // Похоже что данное свойство у модели не найдено continue; } var value = propertyInfo.GetValue(Model,null); // Выполняем замену sb.Replace(match.Value, value != null ? value.ToString() : String.Empty); } // Отдаем преобразованный результат return sb.ToString(); }
public int RowCount(string source) { Regex rowRegex = new Regex(_rowDelimiter); _source = source; _rows = rowRegex.Matches(_source); return _rows.Count; }
/// <summary/> protected CodeFormat() { //generate the keyword and preprocessor regexes from the keyword lists var r = new Regex(@"\w+|-\w+|#\w+|@@\w+|#(?:\\(?:s|w)(?:\*|\+)?\w+)+|@\\w\*+"); string regKeyword = r.Replace(Keywords, @"(?<=^|\W)$0(?=\W)"); string regPreproc = r.Replace(Preprocessors, @"(?<=^|\s)$0(?=\s|$)"); r = new Regex(@" +"); regKeyword = r.Replace(regKeyword, @"|"); regPreproc = r.Replace(regPreproc, @"|"); if (regPreproc.Length == 0) { regPreproc = "(?!.*)_{37}(?<!.*)"; //use something quite impossible... } //build a master regex with capturing groups var regAll = new StringBuilder(); regAll.Append("("); regAll.Append(CommentRegex); regAll.Append(")|("); regAll.Append(StringRegex); if (regPreproc.Length > 0) { regAll.Append(")|("); regAll.Append(regPreproc); } regAll.Append(")|("); regAll.Append(regKeyword); regAll.Append(")"); RegexOptions caseInsensitive = CaseSensitive ? 0 : RegexOptions.IgnoreCase; CodeRegex = new Regex(regAll.ToString(), RegexOptions.Singleline | caseInsensitive); }
public void ExecuteMethodFromRegex(IrcEventArgs e) { if(isRunning==true) { SendUnscramble(e); } foreach(KeyValuePair<string,string> pair in regexDictionary) { regex = new Regex(pair.Key); if(regex.IsMatch(e.Data.Message)) { string methodName = pair.Value; //Get the method information using the method info class MethodInfo mi = this.GetType().GetMethod(methodName); object[] objargs = new object[1]; objargs[0]=e; // //Invoke the method // // (null- no paramyeseter for the method call // // or you can pass the array of parameters...) if(mi==null) { //client.SendMessage(SendType.Message, e.Data.Channel,"mi is null! "+e.Data.Message); SharpBotClient.SharpBotClient.SendChannelMessag(e.Data.Channel,"handled from client"); } else { mi.Invoke(this,objargs); } } } }
private string CheckMetaCharSetAndReEncode(Stream memStream, string html) { Match m = new Regex(@"<meta\s+.*?charset\s*=\s*(?<charset>[A-Za-z0-9_-]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html); if (m.Success) { string charset = m.Groups["charset"].Value.ToLower() ?? "iso-8859-1"; if ((charset == "unicode") || (charset == "utf-16")) { charset = "utf-8"; } try { Encoding metaEncoding = Encoding.GetEncoding(charset); if (Encoding != metaEncoding) { memStream.Position = 0L; StreamReader recodeReader = new StreamReader(memStream, metaEncoding); html = recodeReader.ReadToEnd().Trim(); recodeReader.Close(); } } catch (ArgumentException) { } } return html; }
public override void DataSet(string myPath, string myPattern) { string[] fileList = Directory.GetFiles(myPath, myPattern, SearchOption.AllDirectories); Regex regexMov = new Regex(MovieContents.REGEX_MOVIE_EXTENTION, RegexOptions.IgnoreCase); Regex regexJpg = new Regex(@".*\.jpg$|.*\.jpeg$", RegexOptions.IgnoreCase); Regex regexLst = new Regex(@".*\.wpl$|.*\.asx$", RegexOptions.IgnoreCase); foreach (string file in fileList) { listFileInfo.Add(new common.FileContents(file, myPath)); if (regexMov.IsMatch(file)) MovieCount++; if (regexJpg.IsMatch(file)) ImageCount++; if (regexLst.IsMatch(file)) ListCount++; if (regexJpg.IsMatch(file) && ImageCount == 1) StartImagePathname = file; } ColViewListFileInfo = CollectionViewSource.GetDefaultView(listFileInfo); if (ColViewListFileInfo != null && ColViewListFileInfo.CanSort == true) { ColViewListFileInfo.SortDescriptions.Clear(); ColViewListFileInfo.SortDescriptions.Add(new SortDescription("FileInfo.LastWriteTime", ListSortDirection.Ascending)); } }
private void ValidateInputText() { if (regexPattern == String.Empty) { Message = "Regex is Empty"; return; } try { regex = new Regex(regexPattern); Message = String.Empty; } catch (ArgumentException error) { Message = error.Message; return; } if (InputText != null) { bool isMatch = regex.IsMatch(InputText); if (isMatch) { Message = "It's works!"; } else { Message = "No working :("; } } }
/// <summary> /// Gets inner HTML string from the first found element with the given class name (e.g. class="sample-test"). /// </summary> /// <param name="sourceString">An HTML string to parse.</param> /// <param name="className">Class name.</param> /// <returns>An HTML string.</returns> public static string getInnerHTML(string sourceString, string className) { Match match = new Regex(className).Match(sourceString); if (!match.Success) return ""; int lb = match.Index + className.Length; for (; lb < sourceString.Length && !(sourceString[lb - 1] == '>' && sourceString[lb - 2] != '\\'); lb++); int rb = lb, tmp, bracketCounter = 1; while (bracketCounter > 0) { while (rb < sourceString.Length && !(sourceString[rb] == '<' && sourceString[rb - 1] != '\\')) rb++; tmp = rb + 1; while (tmp < sourceString.Length && !(sourceString[tmp] == '>' && sourceString[tmp - 1] != '\\')) tmp++; if (sourceString[rb + 1] == '/') bracketCounter--; else if (sourceString[tmp - 1] != '/') bracketCounter++; rb++; } while (!(sourceString[--rb] == '<' && sourceString[rb - 1] != '\\')) ; return sourceString.Substring(lb, rb - lb); }
public MessInfo(string s) { const string FILE = "file"; const string LINE = "line"; const string COND = "cond"; const string ERROR = "error"; const string MESSAGE = "message"; Regex rex = new Regex(@"""?(?<" + FILE + @">[a-zA-Z]:\\(?:[^\\/:*?<>|\r\n]+\\)*(?:[^\\/:*?""<>|\r\n]+))""?,\sline\s(?<" + LINE + @">[0-9]+):\s(?<" + COND + @">Error|Warning):[^#]+#(?<"+ERROR+@">[0-9]+(?:-\D)?):\s*(?<"+MESSAGE+@">.+)\z"); Match m = rex.Match(s); if (m.Success) { try { this.File = m.Groups[FILE].Value; this.Line = int.Parse(m.Groups[LINE].Value); this.Cond = (Level)Enum.Parse(typeof(Level), m.Groups[COND].Value); this.Error = m.Groups[ERROR].Value; this.Message = m.Groups[MESSAGE].Value; this.Success = true; } catch { this.Success = false; } } }
/// <summary> /// Corrects the image path relative to the requested page or css where they originate from /// </summary> /// <param name="url"></param> /// <param name="requestPath"></param> /// <returns></returns> public static string CorrectUrl(string url, string requestPath) { var correctedImgPath = url.TrimStart('~'); // make sure 'requestPath' starts with a '/' if (!requestPath.StartsWith("/")) requestPath = "/" + requestPath; if (!url.StartsWith("/") && !url.StartsWith("../")) { correctedImgPath = VirtualPathUtility.GetDirectory(requestPath) + url.TrimStart('/'); } else if (url.StartsWith("../")) { var path = VirtualPathUtility.GetDirectory(requestPath); var regex = new Regex(@"\.\./"); var levelUpMatches = regex.Matches(url); var numberOfLevelsUp = levelUpMatches.Count; var pathDirs = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var newPathDirs = pathDirs.Take(pathDirs.Length - numberOfLevelsUp); var newPath = String.Join("/", newPathDirs).Trim(); correctedImgPath = regex.Replace(url, ""); correctedImgPath = String.IsNullOrEmpty(newPath) ? String.Format("/{0}", correctedImgPath) : String.Format("/{0}/{1}", newPath, correctedImgPath); } return correctedImgPath; }
public void ShouldRegexMatchColonTerminatedFirstMultilineSlashNTerminated() { string content = string.Format("blah:{0}blah", "\n"); Regex regex = new Regex(".*:$", RegexOptions.Multiline); regex.IsMatch(content).Should().BeTrue(); regex.Matches(content).Count.Should().Be(1); }
public void ShouldRegexMatchTwoLines() { string content = string.Format("blah:{0}blah", Environment.NewLine); Regex regex = new Regex("^.*$", RegexOptions.Multiline); regex.IsMatch(content).Should().BeTrue(); regex.Matches(content).Count.Should().Be(2); }
private IList<string> ParseBaseTypes(string fileContents) { const string tagName = "baseType"; string regexPattern = "class\\s+?" + _className + "(?<" + tagName + ">(.|\\s)*?)(\\{|where)"; var regex = new Regex(regexPattern, RegexOptions.Multiline | RegexOptions.Compiled); var match = regex.Match(fileContents); if (!match.Success) { return new List<string>(); } var contents = match.Groups[tagName].Value; var firstColonIndex = contents.IndexOf(':'); if (firstColonIndex < 0) { return new List<string>(); } contents = contents.Substring(firstColonIndex + 1, contents.Length - firstColonIndex - 1); contents = contents.Replace("\r", String.Empty); contents = contents.Replace("\n", String.Empty); contents = contents.Replace("\t", String.Empty); contents = contents.Replace(" ", String.Empty); var result = contents.Split(',').ToList(); return result; }
public static List<Category> GetBoards(this string url) { var temp = new List<Category>(); if (url.Contains("collection")) { temp.Add(Category.General); temp.Add(Category.Manga); temp.Add(Category.HighRes); return temp; } var board = new Regex("(board=[0-9]{0,3})"); var boardMatch = board.Match(url); var boards = Regex.Replace(boardMatch.Value, "[^0-9]+", string.Empty); if (boards.Contains("2")) temp.Add(Category.General); if (boards.Contains("1")) temp.Add(Category.Manga); if (boards.Contains("3")) temp.Add(Category.HighRes); return temp; }
public static string ToWords(this string s) { if (!s.HasValue()) return s; var regex = new Regex("(?<=[a-z])(?<x>[A-Z0-9])|(?<=.)(?<x>[A-Z0-9])(?=[a-z])"); return regex.Replace(s, " ${x}"); }
public static int GetThpp(this string str) { var numReg = new Regex("thpp=([0-9]{0,9})"); var numMatch = numReg.Match(str); return Convert.ToInt32(numMatch.Groups[1].ToString()); }
private static int GetSumOfInts(string input) { var regex = new Regex(@"(-?\d+)"); var matches = regex.Matches(input).OfType<Match>().ToList(); var sum = matches.Sum(x => int.Parse(x.Value)); return sum; }
public static string RefreshMacros(this string sourceText, string macrosName, string macrosCode) { var vars = MacrosTemplates.GetParameters(sourceText, macrosName); var rawArgs = MacrosTemplates.GetPartOfMacros(sourceText, macrosName, "macrosArgs"); var macrosText = macrosTemplate.Replace("{{NAME}}", macrosName); macrosText = macrosText.Replace("{{CODE}}", macrosCode); Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); var match = rgx.Match(sourceText); var spaces = match.Groups[1].Value; macrosText = macrosText.Replace(Environment.NewLine, Environment.NewLine + spaces); var pt = @"(\s?)#region\s+macros\s+" + macrosName + "\\s+(.*?)#endregion"; rgx = new Regex(pt, RegexOptions.IgnoreCase | RegexOptions.Singleline); //Debug.Log(macrosName + ": " + sourceText + " => " + macrosText); sourceText = rgx.Replace(sourceText, spaces + macrosText); foreach (var item in vars) { sourceText = sourceText.Replace("/*{" + item.Key + "}*/", item.Value); sourceText = sourceText.Replace("{" + item.Key + "}", item.Value); } sourceText = sourceText.Replace(macrosName, macrosName + " " + rawArgs); return sourceText; }
public FlexibleFloat(string value) { // Variables Regex re= new Regex(@"([0-9]+)(px|%||em|ex|ch|rem|vw|cm|mm|inches|pt|pc)"); string[] splits= re.Replace(value.Trim(), "$1 $2").Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); val= float.Parse(splits[0]); switch(splits[1]) { case "px": unitType= FlexFloatType.px; break; case "%": unitType= FlexFloatType.percentage; break; case "em": unitType= FlexFloatType.em; break; case "ex": unitType= FlexFloatType.ex; break; case "ch": unitType= FlexFloatType.ch; break; case "rem": unitType= FlexFloatType.rem; break; case "vw": unitType= FlexFloatType.vw; break; case "vh": unitType= FlexFloatType.vh; break; case "cm": unitType= FlexFloatType.cm; break; case "mm": unitType= FlexFloatType.mm; break; case "inches": unitType= FlexFloatType.inches; break; case "pt": unitType= FlexFloatType.pt; break; case "pc": unitType= FlexFloatType.pc; break; default: unitType= FlexFloatType.px; break; } }
private void WriteBson(BsonWriter writer, Regex regex) { // Regular expression - The first cstring is the regex pattern, the second // is the regex options string. Options are identified by characters, which // must be stored in alphabetical order. Valid options are 'i' for case // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. string options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) options += "i"; if (HasFlag(regex.Options, RegexOptions.Multiline)) options += "m"; if (HasFlag(regex.Options, RegexOptions.Singleline)) options += "s"; options += "u"; if (HasFlag(regex.Options, RegexOptions.ExplicitCapture)) options += "x"; writer.WriteRegex(regex.ToString(), options); }
private void tb_humidity_input_TextChanged(object sender, EventArgs e) { if(tb_humidity_input.Text != "") { string pattern = @"^[0-9]*(?:\.[0-9]*)?$";//@"^[0 - 9]([.][0 - 9])?$"; //@"^[0-9]+$"; //for integers only Regex rgx = new Regex(pattern); string text = tb_humidity_input.Text; //string sentence = "Who writes these notes?"; if (rgx.IsMatch(text) == true) { //matched no need to edit double x = double.Parse(tb_humidity_input.Text); if (x >= 0 && x <= 100) { } else { //show error message. MessageBox.Show("Value out of range"); tb_humidity_input.Text = 0.ToString(); } } else { MessageBox.Show("You can only input integer values between 0-100%"); // dataGridView1.CurrentCell.Value = initialNodeSize; tb_humidity_input.Text = 0.ToString(); } } else { tb_humidity_input.Text = 0.ToString(); } }
public void TestPromotionForStorage() { string test = @"integer g() { return 0; } f() { integer i; float f = 1; float h = g(); float j = i; float l = i++; float k = i - 5; f = 1; h = g(); j = i; l = i++; k = i - 5; } default { state_entry() {} } "; TestListener listener = new TestListener(); MCompilerFrontend testFrontend = new MCompilerFrontend(listener, "..\\..\\..\\..\\grammar", true); CompiledScript script = testFrontend.Compile(test); string byteCode = testFrontend.GeneratedByteCode; Console.WriteLine(byteCode); int castCount = new Regex("fcast").Matches(byteCode).Count; Assert.IsTrue(listener.HasErrors() == false); Assert.AreEqual(castCount, 10); }
public JobDefinition ParseJIL(TextReader instr) { JobDefinition jobdef = new JobDefinition(); char[] delim = {':'}; string [] keyval = new string[2]; string jil; Regex rx = new Regex("[A-Za-z-_]+:.*"); // Looks like a JIL key/value pair while ( (jil = instr.ReadLine()) != null ) { if (rx.IsMatch(jil)) { keyval = jil.Split(delim, 2); jobdef.SetField(keyval[0], keyval[1]); } else { Console.Error.WriteLine("Warning: Malformed JIL encountered and ignored: {0}", jil); } } return jobdef; }
public List<ESPNGame> GetGames(int year, int seasonType, int weekNum) { var games = new List<ESPNGame>(); Regex gameRX = new Regex("gameId=[0-9]+"); var url = string.Format("{0}/{1}", GAME_URL, string.Format("_/year/{0}/seasontype/{1}/week/{2}", year.ToString(), seasonType.ToString(), weekNum.ToString())); var html = HelperMethods.LoadHtmlFromUrl(url); var gameIds = gameRX.Matches(html); foreach (Match gId in gameIds) { var gameId = System.Convert.ToInt32(gId.Value.Replace("gameId=", string.Empty)); if (!games.Select(g => g.GameId).Contains(gameId)) { try { var teamsForGame = GetTeamsByGame(gameId); ESPNGame game = new ESPNGame(); game.GameId = gameId; game.HomeTeamId = teamsForGame["home"]; game.AwayTeamId = teamsForGame["away"]; games.Add(game); } catch { } } } return games.Distinct().ToList(); }
/// <summary> /// Gets a list of inner HTML strings from all elements with the given class name (e.g. class="sample-test"). /// </summary> /// <param name="sourceString">An HTML string to parse.</param> /// <param name="className">Class name.</param> /// <returns>An HTML string.</returns> public static List<string> getInnerHTMLList(string sourceString, string className) { List<string> result = new List<string>(); MatchCollection matches = new Regex(className).Matches(sourceString); int lb, rb, tmp = 0, bracketCounter; foreach (Match match in matches) { lb = match.Index + className.Length; if (lb <= tmp) continue; for (; lb < sourceString.Length && !(sourceString[lb - 1] == '>' && sourceString[lb - 2] != '\\'); lb++) ; rb = lb; bracketCounter = 1; while (bracketCounter > 0) { while (rb < sourceString.Length && !(sourceString[rb] == '<' && sourceString[rb - 1] != '\\')) rb++; tmp = rb + 1; while (tmp < sourceString.Length && !(sourceString[tmp] == '>' && sourceString[tmp - 1] != '\\')) tmp++; if (sourceString[rb + 1] == '/') bracketCounter--; else if (sourceString[tmp - 1] != '/') bracketCounter++; rb++; } while (!(sourceString[--rb] == '<' && sourceString[rb - 1] != '\\')) ; result.Add(sourceString.Substring(lb, rb - lb)); } return result; }
public TypePattern() { IPattern descritePattern = PatternFactory.GetInstance().Get(typeof (DiscreteTypePattern)); IPattern compositePattern = PatternFactory.GetInstance().Get(typeof (CompositeTypePattern)); m_TextPattern = "(" + descritePattern.TextPattern + "|" + compositePattern.TextPattern + ")"; m_Regex = new Regex(m_TextPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); }
private void SizeValidation(object sender, CancelEventArgs e) { if (!(sender is TextBox)) { return; } Regex sizeReg = new Regex(@"^\d{1,4}$"); string errorMessage = "Некорректный размер изображения"; TextBox currentTextBox = sender as TextBox; if (!sizeReg.IsMatch(currentTextBox.Text)) { this.errorProvider1.SetError(currentTextBox, errorMessage); this.isValid = false; } else { this.isValid = true; this.errorProvider1.SetError(currentTextBox, ""); switch (currentTextBox.Name) { case "tb_width": this.ImageWidth = Int32.Parse(this.tb_width.Text); break; case "tb_heigth": this.ImageHeight = Int32.Parse(this.tb_heigth.Text); break; default: break; } } }
public static string NormalizeURL(this string s) { //tolower breaks youtube // s = s.ToLower(); System.Text.RegularExpressions.Regex r = new Text.RegularExpressions.Regex("\\s"); s = r.Replace(s, ""); return(s); }
/// <summary> /// 转换UTC字符串eg:13 Oct 2014 03:50:20 +0800为日期时间 /// eg:Mon, 13 Oct 2014 03:50:20 +0800 (CST) /// </summary> public static DateTime?ToUTCTime(this string dateTime) { DateTime?result = ToSafeDateTime(dateTime); if (result != null) { return(result); } Text.RegularExpressions.Regex rgex = new Text.RegularExpressions.Regex(@"(?i)\d+ [a-z]+ \d{4} \d+:\d+:\d+ [-\+]\d+"); return(ToSafeDateTime(rgex.Match(dateTime).Value)); }
public static string InnerHTML(this string html, string tagName) { string retVal = ""; if (!string.IsNullOrEmpty(html)) { System.Text.RegularExpressions.Regex r = new Text.RegularExpressions.Regex(string.Format("<{0}.*>([^<]+)", tagName)); var matches = r.Match(html); if (matches != null && matches.Groups.Count > 0 && matches.Groups[1] != null) { retVal = matches.Groups[1].Value; } } return(retVal); }
/// <summary> /// 转换为日期时间 /// </summary> public static DateTime?ToSafeDateTime(this string dateTime) { DateTime result; Text.RegularExpressions.Regex re = new Text.RegularExpressions.Regex(@"^\d+$"); if (re.IsMatch(dateTime) && dateTime.Length == 18) { // 如果为18位的文件时间,那么在这里处理 var tempDate = System.DateTime.FromFileTime(Convert.ToInt64(dateTime)); return(tempDate); } else if (DateTime.TryParse(dateTime, out result)) { return(result); } return(null); }
protected override void AttachChildControls() { if (!int.TryParse(this.Page.Request.QueryString["productId"], out this.productId)) { base.GotoResourceNotFound(""); } this.rptProductImages = (VshopTemplatedRepeater)this.FindControl("rptProductImages"); this.litProdcutName = (System.Web.UI.WebControls.Literal) this.FindControl("litProdcutName"); this.litSalePrice = (System.Web.UI.WebControls.Literal) this.FindControl("litSalePrice"); this.litMarketPrice = (System.Web.UI.WebControls.Literal) this.FindControl("litMarketPrice"); this.litShortDescription = (System.Web.UI.WebControls.Literal) this.FindControl("litShortDescription"); this.litDescription = (System.Web.UI.WebControls.Literal) this.FindControl("litDescription"); this.litTaxRate = (System.Web.UI.WebControls.Literal) this.FindControl("litTaxRate"); this.litShipping = (System.Web.UI.WebControls.Literal) this.FindControl("litShipping"); this.litStock = (System.Web.UI.WebControls.Literal) this.FindControl("litStock"); this.litBuyCardinality = (System.Web.UI.WebControls.Literal) this.FindControl("litBuyCardinality"); this.litSupplier = (System.Web.UI.WebControls.Literal) this.FindControl("litSupplier"); this.lblsmalltitle = (System.Web.UI.WebControls.Literal) this.FindControl("lblsmalltitle"); this.litDiscrunt = (System.Web.UI.WebControls.Literal) this.FindControl("litDiscrunt"); this.litpropricemsg = (System.Web.UI.WebControls.Literal) this.FindControl("litpropricemsg"); this.litProPromration = (System.Web.UI.WebControls.Literal) this.FindControl("litProPromration"); this.litOrderPromration = (System.Web.UI.WebControls.Literal) this.FindControl("litOrderPromration"); this.litFreeShip = (System.Web.UI.WebControls.Literal) this.FindControl("litFreeShip"); this.skuSelector = (Common_SKUSelector)this.FindControl("skuSelector"); this.linkDescription = (System.Web.UI.WebControls.HyperLink) this.FindControl("linkDescription"); this.expandAttr = (Common_ExpandAttributes)this.FindControl("ExpandAttributes"); this.litSoldCount = (System.Web.UI.WebControls.Literal) this.FindControl("litSoldCount"); this.litConsultationsCount = (System.Web.UI.WebControls.Literal) this.FindControl("litConsultationsCount"); this.litReviewsCount = (System.Web.UI.WebControls.Literal) this.FindControl("litReviewsCount"); this.litHasCollected = (System.Web.UI.HtmlControls.HtmlInputHidden) this.FindControl("litHasCollected"); this.hidden_skus = (System.Web.UI.HtmlControls.HtmlInputHidden) this.FindControl("hidden_skus"); this.hidden_BuyCardinality = (System.Web.UI.HtmlControls.HtmlInputHidden) this.FindControl("hidden_BuyCardinality"); this.lbUserProductRefer = (UserProductReferLabel)this.FindControl("lbUserProductRefer"); this.promote = (ProductPromote)this.FindControl("ProductPromote"); this.litCnArea = (System.Web.UI.WebControls.Literal) this.FindControl("litCnArea"); this.imgIcon = (HiImage)this.FindControl("imgIcon"); //this.imgSupplierIcon = (HiImage)this.FindControl("imgSupplierIcon"); ProductBrowseInfo productBrowseInfo = ProductBrowser.GetProductBrowseInfo(this.productId, null, null); if (productBrowseInfo == null) { base.GotoResourceNotFound("此商品已不存在"); } if (productBrowseInfo.Product == null) { base.GotoResourceNotFound("此商品已不存在"); } if (productBrowseInfo.Product.SaleStatus != ProductSaleStatus.OnSale) { base.GotoResourceNotFound("此商品已下架"); } if (!productBrowseInfo.Product.IsApproved) { base.GotoResourceNotFound("此商品未审核"); } System.Collections.IEnumerable value = from item in productBrowseInfo.Product.Skus select item.Value; if (this.hidden_skus != null) { this.hidden_skus.Value = JsonConvert.SerializeObject(value); } if (HiContext.Current.User.UserRole == UserRole.Member && ((Member)HiContext.Current.User).ReferralStatus == 2 && string.IsNullOrEmpty(this.Page.Request.QueryString["ReferralUserId"])) { string text = System.Web.HttpContext.Current.Request.Url.ToString(); if (text.IndexOf("?") > -1) { text = text + "&ReferralUserId=" + HiContext.Current.User.UserId; } else { text = text + "?ReferralUserId=" + HiContext.Current.User.UserId; } base.RegisterShareScript(productBrowseInfo.Product.ImageUrl4, text, productBrowseInfo.Product.ShortDescription, productBrowseInfo.Product.ProductName); } if (this.lbUserProductRefer != null) { this.lbUserProductRefer.product = productBrowseInfo.Product; } ImportSourceTypeInfo imSourceType = ProductBrowser.GetProductImportSourceType(this.productId); if (this.litCnArea != null && imSourceType != null) { this.litCnArea.Text = imSourceType.CnArea; } if (this.imgIcon != null && imSourceType != null) { this.imgIcon.ImageUrl = imSourceType.Icon; } if (this.rptProductImages != null) { string locationUrl = "javascript:;"; SlideImage[] source = new SlideImage[] { new SlideImage(productBrowseInfo.Product.ImageUrl1, locationUrl), new SlideImage(productBrowseInfo.Product.ImageUrl2, locationUrl), new SlideImage(productBrowseInfo.Product.ImageUrl3, locationUrl), new SlideImage(productBrowseInfo.Product.ImageUrl4, locationUrl), new SlideImage(productBrowseInfo.Product.ImageUrl5, locationUrl), }; this.rptProductImages.DataSource = from item in source where !string.IsNullOrWhiteSpace(item.ImageUrl) select item; this.rptProductImages.DataBind(); } this.litProdcutName.Text = productBrowseInfo.Product.ProductName; this.litSalePrice.Text = productBrowseInfo.Product.MinSalePrice.ToString("F2"); if (productBrowseInfo.Product.MarketPrice.HasValue) { this.litMarketPrice.SetWhenIsNotNull(productBrowseInfo.Product.MarketPrice.GetValueOrDefault(0m).ToString("F2")); } this.litShortDescription.Text = productBrowseInfo.Product.ShortDescription; if (this.litDescription != null) { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<script[^>]*?>.*?</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (!string.IsNullOrWhiteSpace(productBrowseInfo.Product.MobblieDescription)) { this.litDescription.Text = regex.Replace(productBrowseInfo.Product.MobblieDescription, ""); } else { if (!string.IsNullOrWhiteSpace(productBrowseInfo.Product.Description)) { this.litDescription.Text = regex.Replace(productBrowseInfo.Product.Description, ""); } } } this.litSoldCount.SetWhenIsNotNull(productBrowseInfo.Product.ShowSaleCounts.ToString()); this.litStock.Text = productBrowseInfo.Product.Stock.ToString(); //this.litTaxRate.Text = (productBrowseInfo.Product.TaxRate * 100).ToString("0"); if (this.litTaxRate != null) { this.litTaxRate.Text = productBrowseInfo.Product.GetExtendTaxRate(); } if (productBrowseInfo.Product.BuyCardinality > 1) { this.litBuyCardinality.Text = "起购数:" + productBrowseInfo.Product.BuyCardinality; } else { this.litBuyCardinality.Visible = false; } this.hidden_BuyCardinality.Value = productBrowseInfo.Product.BuyCardinality.ToString(); //运费模版 ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(Int32.Parse(productBrowseInfo.Product.TemplateId != null ? productBrowseInfo.Product.TemplateId.ToString() : "0")); this.litShipping.Text = shippingMode != null ? shippingMode.TemplateName : "未设置"; this.skuSelector.ProductId = this.productId; if (this.expandAttr != null) { this.expandAttr.ProductId = this.productId; } if (this.linkDescription != null) { this.linkDescription.NavigateUrl = "/Vshop/ProductDescription.aspx?productId=" + this.productId; } this.litConsultationsCount.SetWhenIsNotNull(productBrowseInfo.ConsultationCount.ToString()); this.litReviewsCount.SetWhenIsNotNull(productBrowseInfo.ReviewCount.ToString()); Member member = HiContext.Current.User as Member; int favoriteId = 0; if (member != null) { favoriteId = ProductBrowser.GetFavoriteId(member.UserId, this.productId); } this.litHasCollected.SetWhenIsNotNull(favoriteId.ToString()); if (this.promote != null) { this.promote.ProductId = this.productId; } PageTitle.AddSiteNameTitle(productBrowseInfo.Product.ProductName); //this.litSupplierName.Text = productBrowseInfo.SupplierName; //if (this.imgSupplierIcon != null && productBrowseInfo.SupplierImageUrl != null) //{ // this.imgSupplierIcon.ImageUrl = productBrowseInfo.SupplierImageUrl; //} if (productBrowseInfo.Product.SupplierId == null || productBrowseInfo.Product.SupplierId == 0) { this.litSupplier.Text = ""; } else { this.litSupplier.Text = "<a class=\"shop-link fix\" href=\"/vshop/SupProductList.aspx?SupplierId=" + productBrowseInfo.Product.SupplierId + "\"><span>进入店铺</span><img src=\"" + productBrowseInfo.SupplierLogo + "\"/>" + productBrowseInfo.SupplierName + "</a>"; } this.lblsmalltitle.Text = productBrowseInfo.Product.ProductTitle; //this.litDiscrunt = (System.Web.UI.WebControls.Literal)this.FindControl("litDiscrunt"); //this.litpropricemsg = (System.Web.UI.WebControls.Literal)this.FindControl("litpropricemsg"); //显示促销信息 if (productBrowseInfo.Product.IsPromotion) { this.litpropricemsg.Text = "<span class=\"pro-pricemsg\">促销价</span>"; } decimal tempMinSalePrice = productBrowseInfo.Product.MinSalePrice; //折扣价 decimal tempMarketPrice = productBrowseInfo.Product.MarketPrice.GetValueOrDefault(0m); //会员价 decimal tempDiscrunt = 1M; if (tempMarketPrice > 0) { tempDiscrunt = (tempMinSalePrice / tempMarketPrice) * 10; } //显示折扣信息 if (productBrowseInfo.Product.IsDisplayDiscount) { this.litDiscrunt.Text = "<span class=\"pro-discrunt\">" + tempDiscrunt.ToString("F2") + "折</span>"; } //PromotionInfo promotionInfo; List <OrderPromotionItem> orderpromotionlist = new List <OrderPromotionItem>(); List <ProductPromotionItem> productpromotionlist = new List <ProductPromotionItem>(); if (member != null) { //promotionInfo = ProductBrowser.GetProductPromotionInfo(member, productId); DataTable dtorderpromotion = ProductBrowser.GetOrderPromotionInfo(member); if (dtorderpromotion != null) { OrderPromotionItem item = null; foreach (DataRow row in dtorderpromotion.Rows) { item = new OrderPromotionItem(); if (row["Name"] != DBNull.Value) { item.Name = (string)row["Name"]; } if (row["PromoteType"] != DBNull.Value) { item.PromoteType = (int)row["PromoteType"]; } orderpromotionlist.Add(item); } } DataTable dtproductpromotion = ProductBrowser.GetProductPromotionList(member, productId); if (dtproductpromotion != null) { ProductPromotionItem item = null; foreach (DataRow row in dtproductpromotion.Rows) { item = new ProductPromotionItem(); if (row["Name"] != DBNull.Value) { item.Name = (string)row["Name"]; } if (row["PromoteType"] != DBNull.Value) { item.PromoteType = (int)row["PromoteType"]; } productpromotionlist.Add(item); } } } else { //promotionInfo = ProductBrowser.GetAllProductPromotionInfo(productId); DataTable dtorderpromotion = ProductBrowser.GetAllOrderPromotionInfo(); if (dtorderpromotion != null) { OrderPromotionItem item = null; foreach (DataRow row in dtorderpromotion.Rows) { item = new OrderPromotionItem(); if (row["Name"] != DBNull.Value) { item.Name = (string)row["Name"]; } if (row["PromoteType"] != DBNull.Value) { item.PromoteType = (int)row["PromoteType"]; } orderpromotionlist.Add(item); } } DataTable dtproductpromotion = ProductBrowser.GetAllProductPromotionList(productId); if (dtproductpromotion != null) { ProductPromotionItem item = null; foreach (DataRow row in dtproductpromotion.Rows) { item = new ProductPromotionItem(); if (row["Name"] != DBNull.Value) { item.Name = (string)row["Name"]; } if (row["PromoteType"] != DBNull.Value) { item.PromoteType = (int)row["PromoteType"]; } productpromotionlist.Add(item); } } } //this.litProPromration = (System.Web.UI.WebControls.Literal)this.FindControl("litProPromration"); //this.litOrderPromration = (System.Web.UI.WebControls.Literal)this.FindControl("litOrderPromration"); //包邮 if (orderpromotionlist != null) { for (int i = 0; i < orderpromotionlist.Count; i++) { if (orderpromotionlist[i].PromoteType == 17) { this.litFreeShip.Text = "<div><span style=\"color:#999\">" + orderpromotionlist[i].Name + "</span></div>"; } else { this.litOrderPromration.Text = "<span>" + orderpromotionlist[i].Name + "</span>"; } } } if (productpromotionlist != null) { for (int i = 0; i < productpromotionlist.Count; i++) { this.litProPromration.Text = "<span>" + productpromotionlist[i].Name + "</span>"; break; } } }
/// <summary> /// 程序集是否匹配 /// </summary> private bool Match(Assembly assembly) { return(!Regex.IsMatch(assembly.FullName, SkipAssemblies, RegexOptions.IgnoreCase | RegexOptions.Compiled)); }
/// <summary> /// check an address1 string for "P.O. Box"-like strings. /// </summary> /// <param name="addressOne"></param> /// <returns>boolean</returns> protected bool CheckPOBox(string addressOne) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions .Regex(@"(?i)\b(?:p(?:ost)?\.?\s*[o0](?:ffice)?\.?\s*b(?:[o0]x)?|b[o0]x)"); return(regEx.IsMatch(addressOne)); }
public static string GetExtension(this string value) { var r = new System.Text.RegularExpressions.Regex(@"\.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$"); return(r.Match(value).Value); }
private static bool IsTextNumeric(string str) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]"); return(reg.IsMatch(str)); }
public override string RenderHtml() { int DropDownLimitSize = 100; int.TryParse(ConfigurationManager.AppSettings["CACHE_DURATION"].ToString(), out CacheDuration); CacheIsOn = ConfigurationManager.AppSettings["CACHE_IS_ON"];//false; IsCacheSlidingExpiration = ConfigurationManager.AppSettings["CACHE_SLIDING_EXPIRATION"].ToString(); var html = new StringBuilder(); var inputName = _form.FieldPrefix + _key; string ErrorStyle = string.Empty; // prompt var prompt = new TagBuilder("label"); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(Prompt.Replace(" ", " "), "<br />"); string NewPromp = System.Web.Mvc.MvcHtmlString.Create(newText).ToString(); prompt.InnerHtml = NewPromp; prompt.Attributes.Add("for", inputName); prompt.Attributes.Add("class", "EpiLabel"); prompt.Attributes.Add("Id", "label" + inputName); StringBuilder StyleValues = new StringBuilder(); StyleValues.Append(GetContolStyle(_fontstyle.ToString(), _Prompttop.ToString(), _Promptleft.ToString(), null, Height.ToString(), _IsHidden)); prompt.Attributes.Add("style", StyleValues.ToString()); html.Append(prompt.ToString()); // error label if (!IsValid) { //Add new Error to the error Obj ErrorStyle = ";border-color: red"; } TagBuilder input = null; input = new TagBuilder("input"); input.Attributes.Add("list", inputName + "_DataList"); input.Attributes.Add("data-autofirst", "true"); input.Attributes.Add("value", Value); input.Attributes.Add("id", inputName); input.Attributes.Add("name", inputName); ////////////Check code start////////////////// EnterRule FunctionObjectAfter = (EnterRule)_form.FormCheckCodeObj.GetCommand("level=field&event=after&identifier=" + _key); if (FunctionObjectAfter != null && !FunctionObjectAfter.IsNull()) { input.Attributes.Add("onblur", "return " + _key + "_after();"); //After // select.Attributes.Add("onchange", "return " + _key + "_after();"); //After } EnterRule FunctionObjectBefore = (EnterRule)_form.FormCheckCodeObj.GetCommand("level=field&event=before&identifier=" + _key); if (FunctionObjectBefore != null && !FunctionObjectBefore.IsNull()) { input.Attributes.Add("onfocus", "return " + _key + "_before();"); //Before } EnterRule FunctionObjectClick = (EnterRule)_form.FormCheckCodeObj.GetCommand("level=field&event=click&identifier=" + _key); //if (!string.IsNullOrEmpty(this.RelateCondition)) //{ // input.Attributes.Add("onchange", "SetCodes_Val(this,'" + _form.SurveyInfo.SurveyId + "','" + _key + "'); "); //click //} ////////////Check code end////////////////// int LargestChoiseLength = 0; string measureString = ""; foreach (var choise in _choices) { if (choise.Key.ToString().Length > LargestChoiseLength) { LargestChoiseLength = choise.Key.ToString().Length; measureString = choise.Key.ToString(); } } // LargestChoiseLength = LargestChoiseLength * _ControlFontSize; Font stringFont = new Font(ControlFontStyle, ControlFontSize); SizeF size = new SizeF(); using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { size = g.MeasureString(measureString.ToString(), stringFont); } // stringSize = (int) Graphics.MeasureString(measureString.ToString(), stringFont).Width; if (_IsRequired == true) { //awesomplete if (this._choices.Count() < DropDownLimitSize) { if ((size.Width) > _ControlWidth) { // select.Attributes.Add("class", GetControlClass() + "text-input fix-me"); input.Attributes.Add("class", GetControlClass() + "fix-me"); } else { // select.Attributes.Add("class", GetControlClass() + "text-input"); input.Attributes.Add("class", GetControlClass()); } input.Attributes.Add("data-prompt-position", "topRight:10"); } else { if ((size.Width) > _ControlWidth) { // select.Attributes.Add("class", GetControlClass() + "text-input fix-me"); input.Attributes.Add("class", GetControlClass() + "fix-me awesomplete Search"); } else { // select.Attributes.Add("class", GetControlClass() + "text-input"); input.Attributes.Add("class", GetControlClass() + " awesomplete Search"); } input.Attributes.Add("data-prompt-position", "topRight:10"); } } else { //awesomplete if (this._choices.Count() < DropDownLimitSize) { //select.Attributes.Add("class", GetControlClass() + "text-input fix-me"); if ((size.Width) > _ControlWidth) { input.Attributes.Add("class", GetControlClass() + "fix-me "); } else { input.Attributes.Add("class", GetControlClass()); } input.Attributes.Add("data-prompt-position", "topRight:10"); } else { if ((size.Width) > _ControlWidth) { input.Attributes.Add("class", GetControlClass() + "fix-me awesomplete Search"); } else { input.Attributes.Add("class", GetControlClass() + " awesomplete Search"); } input.Attributes.Add("data-prompt-position", "topRight:10"); } } string IsHiddenStyle = ""; string IsHighlightedStyle = ""; if (_IsHidden) { IsHiddenStyle = "display:none"; } if (_IsHighlighted) { IsHighlightedStyle = "background-color:yellow"; } //if (_IsDisabled) //{ // select.Attributes.Add("disabled", "disabled"); //} string InputFieldStyle = GetInputFieldStyle(_InputFieldfontstyle.ToString(), _InputFieldfontSize, _InputFieldfontfamily.ToString()); input.Attributes.Add("style", "position:absolute;left:" + _left.ToString() + "px;top:" + _top.ToString() + "px" + ";width:" + _ControlWidth.ToString() + "px ; font-size:" + ControlFontSize + "pt;" + ErrorStyle + ";" + IsHiddenStyle + ";" + IsHighlightedStyle + ";" + InputFieldStyle); input.MergeAttributes(_inputHtmlAttributes); html.Append(input.ToString(TagRenderMode.StartTag)); if (ReadOnly || _IsDisabled) { var scriptReadOnlyText = new TagBuilder("script"); //scriptReadOnlyText.InnerHtml = "$(function(){$('#" + inputName + "').attr('disabled','disabled')});"; scriptReadOnlyText.InnerHtml = "$(function(){ var List = new Array();List.push('" + _key + "');CCE_Disable(List, false);});"; html.Append(scriptReadOnlyText.ToString(TagRenderMode.Normal)); } if (this._choices.Count() > DropDownLimitSize) { var scriptReadOnlyText = new TagBuilder("script"); StringBuilder Script = new StringBuilder(); Script.Append("$(window).load(function () { "); Script.Append(" $( '#" + inputName + "' ).next().css( 'position', 'absolute' ); "); Script.Append(" $( '#" + inputName + "' ).next().css( 'left', '" + _left.ToString() + "px' ); "); Script.Append(" $( '#" + inputName + "' ).next().css( 'top', '" + (_top + 29).ToString() + "px' ); "); Script.Append("});"); scriptReadOnlyText.InnerHtml = Script.ToString(); html.Append(scriptReadOnlyText.ToString(TagRenderMode.Normal)); var scriptReadOnlyText1 = new TagBuilder("script"); StringBuilder Script1 = new StringBuilder(); Script1.Append(" $(document).ready(function () {"); Script1.Append("$( '#" + inputName + "').blur(function() { "); Script1.Append("SetCodes_Val(this,'" + _form.SurveyInfo.SurveyId + "','" + _key + "'); "); Script1.Append("});"); Script1.Append("});"); scriptReadOnlyText1.InnerHtml = Script1.ToString(); html.Append(scriptReadOnlyText1.ToString(TagRenderMode.Normal)); } /////////////////////////// var datalist = new TagBuilder("datalist "); datalist.Attributes.Add("id", inputName + "_DataList"); html.Append(datalist.ToString(TagRenderMode.StartTag)); foreach (var choice in _choices) { var opt = new TagBuilder("option"); opt.Attributes.Add("value", choice.Key); opt.SetInnerText(choice.Key); html.Append(opt.ToString()); /////////////////////////// } // close select element html.Append(input.ToString(TagRenderMode.EndTag)); // add hidden tag, so that a value always gets sent for select tags var hidden1 = new TagBuilder("input"); hidden1.Attributes.Add("type", "hidden"); hidden1.Attributes.Add("id", inputName + "_hidden"); hidden1.Attributes.Add("name", inputName); hidden1.Attributes.Add("value", string.Empty); html.Append(hidden1.ToString(TagRenderMode.SelfClosing)); var wrapper = new TagBuilder(_fieldWrapper); wrapper.Attributes["class"] = _fieldWrapperClass; if (_IsHidden) { wrapper.Attributes["style"] = "display:none"; } wrapper.Attributes["id"] = inputName + "_fieldWrapper"; wrapper.InnerHtml = html.ToString(); return(wrapper.ToString()); }
/// <summary> /// Process IDs in the message. /// </summary> /// <param name="Body">The body text to use for merging.</param> /// <param name="dataSource"></param> /// <param name="repeat"></param> /// <returns>The merged message.</returns> private string ProcessIDs(string Body, object dataSource, bool repeat) { //process conditions foreach (Condition condition in this.Conditions) { if (condition.Match) { System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=""" + condition.RegionID + @""")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); System.Text.RegularExpressions.MatchCollection mc; mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, condition.NullText); } } rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=" + condition.RegionID + @")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, condition.NullText); } } } } //process regions foreach (Region region in this.Regions) { System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=""" + region.RegionID + @""")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); System.Text.RegularExpressions.MatchCollection mc; mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, m.Groups["completetag"].Value + this.MergeText(region.Content, dataSource, repeat) + m.Groups["endtag"].Value); } } rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=" + region.RegionID + @")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, m.Groups["completetag"].Value + this.MergeText(region.Content, dataSource, repeat) + m.Groups["endtag"].Value); } } } //remove empty list templates foreach (ListTemplate listTemplate in _listTemplates) { if ((listTemplate.Count == 0) && (listTemplate.RegionID != "")) { System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=""" + listTemplate.RegionID + @""")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); System.Text.RegularExpressions.MatchCollection mc; mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, this.MergeText(listTemplate.NullText, dataSource, repeat)); } } rx = new System.Text.RegularExpressions.Regex(@"(?<completetag><(?<tag>[^\s>]*)[^>]*?(?i:ID=" + listTemplate.RegionID + @")(?<result>.[^>]+>))(?<contents>.*?)(?<endtag></\k<tag>>)", RegexOptions.IgnoreCase | RegexOptions.Singleline); mc = rx.Matches(Body); if (mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { Body = Body.Replace(m.Value, this.MergeText(listTemplate.NullText, dataSource, repeat)); } } } } return(Body); }
public static bool ContainsNoSpaces(this string s) { var regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9]+$"); return(regex.IsMatch(s)); }
/// <summary> /// 判断输入的字符是否为数字 /// </summary> /// <param name="p_strVaule"></param> /// <returns></returns> private bool m_blnIsNUmber(string p_strVaule) { Regex m_regex = new System.Text.RegularExpressions.Regex("^(-?[0-9]*[.]*[0-9]{0,3})$"); return(m_regex.IsMatch(p_strVaule)); }
/// <summary> /// 문자열에서 특정문자 갯수 확인 /// </summary> /// <param name="strTotal"></param> /// <param name="strFind"></param> /// <returns></returns> public int GetStringcount(string strTotal, string strFind) { System.Text.RegularExpressions.Regex cntStr = new System.Text.RegularExpressions.Regex(strFind); return(int.Parse(cntStr.Matches(strTotal, 0).Count.ToString())); }
public static string GetDomain(this string url) { System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^(?:https?:\/\/)?(?:[^@\/\n]+@)?(?:www\.)?([^:\/\n]+)"); return(r.Match(url).Value); }
/// <summary> /// Gets the updated template HTML. /// </summary> /// <param name="templateHtml">The template HTML.</param> /// <param name="binaryFileId">The binary file identifier.</param> /// <param name="lavaFieldsTemplateDictionaryFromControls">The lava fields template dictionary from controls.</param> /// <param name="lavaFieldsDefaultDictionary">The lava fields default dictionary.</param> /// <returns></returns> public static string GetUpdatedTemplateHtml( string templateHtml, int?binaryFileId, Dictionary <string, string> lavaFieldsTemplateDictionaryFromControls, Dictionary <string, string> lavaFieldsDefaultDictionary) { var templateLogoHtmlMatch = new Regex("<img[^>]+id=[',\"]template-logo[',\"].*src=[',\"]([^\">]+)[',\"].*>").Match(templateHtml); string updatedTemplateHtml = templateHtml; if (templateLogoHtmlMatch.Groups.Count == 2) { string originalTemplateLogoHtml = templateLogoHtmlMatch.Groups[0].Value; string originalTemplateLogoSrc = templateLogoHtmlMatch.Groups[1].Value; string newTemplateLogoSrc; // if a template-logo exists in the template, update the src attribute to whatever the uploaded logo is (or set it to the placeholder if it is not set) if (binaryFileId != null && binaryFileId > 0) { string getImagePath; if (HostingEnvironment.IsHosted) { getImagePath = System.Web.VirtualPathUtility.ToAbsolute("~/GetImage.ashx"); } else { getImagePath = "/GetImage.ashx"; } newTemplateLogoSrc = $"{getImagePath}?Id={binaryFileId}"; } else { newTemplateLogoSrc = "/Content/EmailTemplates/placeholder-logo.png"; } string newTemplateLogoHtml = originalTemplateLogoHtml.Replace(originalTemplateLogoSrc, newTemplateLogoSrc); templateHtml = templateHtml.Replace(originalTemplateLogoHtml, newTemplateLogoHtml); } var origHtml = templateHtml; /* We want to update the lava-fields node of template so that the lava-fields tag * is in sync with the lava merge fields in kvlMergeFields (which comes from CommunicationTemplate.LavaFields). * NOTE: We don't want to use a HTML Parser (like HtmlAgilityPack or AngleSharp), * because this is a mix of html and lava, and html parsers will end up corrupting the html+lava * So we'll.. * 1) Use regex to find the lava-fields html and remove it from the code editor text * 2) make a new lava-fields tag with the values from kvlMergeFields (which comes from CommunicationTemplate.LavaFields) * 3) Put thge new lava-fields html back into the code editor text in the head in a noscript tag */ // First, we'll take out the lava-fields tag (could be a div or a noscript, depending on which version of Rock last edited it) var lavaFieldsRegExLegacy = new System.Text.RegularExpressions.Regex(@"<div[\s\S]*lava-fields[\s\S]+?</div>?", RegexOptions.Multiline); var lavaFieldsHtmlLegacy = lavaFieldsRegExLegacy.Match(templateHtml).Value; if (lavaFieldsHtmlLegacy.IsNotNullOrWhiteSpace()) { templateHtml = templateHtml.Replace(lavaFieldsHtmlLegacy, string.Empty); } var lavaFieldsRegEx = new System.Text.RegularExpressions.Regex(@"<noscript[\s\S]*lava-fields[\s\S]+?</noscript>?", RegexOptions.Multiline); var lavaFieldsHtml = lavaFieldsRegEx.Match(templateHtml).Value; if (lavaFieldsHtml.IsNotNullOrWhiteSpace()) { templateHtml = templateHtml.Replace(lavaFieldsHtml, string.Empty); } var templateDocLavaFieldLines = lavaFieldsHtml.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim()).Where(a => a.IsNotNullOrWhiteSpace()).ToList(); // add any new lava fields that were added to the KeyValueList editor foreach (var keyValue in lavaFieldsDefaultDictionary) { string pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key); if (!templateDocLavaFieldLines.Any(a => Regex.IsMatch(a, pattern))) { templateDocLavaFieldLines.Add("{% assign " + keyValue.Key + " = '" + keyValue.Value + "' %}"); } } // remove any lava fields that are not in the KeyValueList editor foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines.ToList()) { var found = false; foreach (var keyValue in lavaFieldsDefaultDictionary) { var pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key); if (!Regex.IsMatch(templateDocLavaFieldLine, pattern)) { continue; } found = true; break; } // if not found, delete it if (!found) { templateDocLavaFieldLines.Remove(templateDocLavaFieldLine); } } // dictionary of keys and values from the lava fields in the 'lava-fields' div var lavaFieldsTemplateDictionary = new Dictionary <string, string>(); foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines) { var match = Regex.Match(templateDocLavaFieldLine, @"{% assign (.*)\=(.*) %}"); if (match.Groups.Count != 3) { continue; } var key = match.Groups[1].Value.Trim().RemoveSpaces(); var value = match.Groups[2].Value.Trim().Trim('\''); // if there are values from Controls that different from the ones in the templateHtml, use the values from the control if (lavaFieldsTemplateDictionaryFromControls.ContainsKey(key)) { var controlValue = lavaFieldsTemplateDictionaryFromControls[key]; if (controlValue != value) { value = controlValue; } } lavaFieldsTemplateDictionary.Add(key, value); } if (!lavaFieldsTemplateDictionary.Any()) { return(templateHtml); } // there are 3 cases of where the <noscript> tag should be // 1) There is a head tag (usually the case) // 2) There is not head tag, but there is a html tag // 3) There isn't a head or html tag var headTagRegex = new Regex("<head(.*?)>"); var htmlTagRegex = new Regex("<html(.*?)>"); var lavaAssignsHtmlBuilder = new StringBuilder(); lavaAssignsHtmlBuilder.Append("<noscript id=\"lava-fields\">\n"); lavaAssignsHtmlBuilder.Append(" {% comment %} Lava Fields: Code-Generated from Template Editor {% endcomment %}\n"); foreach (var lavaFieldsTemplateItem in lavaFieldsTemplateDictionary) { lavaAssignsHtmlBuilder.Append(string.Format(" {{% assign {0} = '{1}' %}}\n", lavaFieldsTemplateItem.Key, lavaFieldsTemplateItem.Value)); } lavaAssignsHtmlBuilder.Append("</noscript>"); var lavaAssignsHtml = lavaAssignsHtmlBuilder.ToString(); if (headTagRegex.Match(templateHtml).Success) { templateHtml = headTagRegex.Replace(templateHtml, (m) => { return(m.Value.TrimEnd() + lavaAssignsHtml); }); } else if (htmlTagRegex.Match(templateHtml).Success) { templateHtml = htmlTagRegex.Replace(templateHtml, (m) => { return(m.Value.TrimEnd() + lavaAssignsHtml); }); } else { templateHtml = lavaAssignsHtml + "\n" + templateHtml.TrimStart(); } return(templateHtml); }
private void btnSave_Click(object sender, System.EventArgs e) { if (this.categoryId == 0) { this.categoryId = (int)this.ViewState["ProductCategoryId"]; } int displaySequence; decimal salePrice; decimal?costPrice; decimal?marketPrice; int stock; int factstock; decimal?num3; decimal?referralDeduct; decimal?subMemberDeduct; decimal?subReferralDeduct; decimal?deductFee; int buyCardinality; decimal?grossweight; if (!this.ValidateConverts(this.chkSkuEnabled.Checked, out displaySequence, out salePrice, out costPrice, out marketPrice, out stock, out factstock, out num3, out referralDeduct, out subMemberDeduct, out subReferralDeduct, out deductFee, out buyCardinality, out grossweight)) { return; } decimal adminFraction = 0m; if (string.IsNullOrWhiteSpace(txtAdminFraction.Text) || !decimal.TryParse(txtAdminFraction.Text, out adminFraction)) { this.ShowMsg("请输入正确的提升权重值", false); return; } int ConversionRelation; if (!int.TryParse(this.txtConversionRelation.Text, out ConversionRelation)) { this.ShowMsg("输入换算关系不正确", false); return; } string text = Globals.StripScriptTags(this.txtProductName.Text.Trim()); text = Globals.StripHtmlXmlTags(text).Replace("\\", "").Replace("'", ""); if (string.IsNullOrEmpty(text) || text == "") { this.ShowMsg("商品名称不能为空,且不能包含脚本标签、HTML标签、XML标签、反斜杠(\\)、单引号(')!", false); return; } if (!this.chkSkuEnabled.Checked) { if (salePrice <= 0m) { this.ShowMsg("商品一口价必须大于0", false); return; } if (costPrice.HasValue && (costPrice.Value > salePrice || costPrice.Value < 0m)) { this.ShowMsg("商品成本价必须大于0且小于商品一口价", false); return; } if (!costPrice.HasValue) //|| !deductFee.HasValue { this.ShowMsg("商品成本价不能为空", false); //与扣点 return; } if (string.IsNullOrEmpty(txtProductStandard.Text)) { this.ShowMsg("未开启多规格时,商品规格必填", false); return; } } //判断是否存在广告关键字 Dictionary <string, string> msg; if (!ValidateKeyWordHelper.ValidateKeyWord(new Dictionary <string, string>() { { "商品名称", this.txtProductName.Text }, { "商品简介", this.txtShortDescription.Text } }, out msg)) { string showM = ""; foreach (string k in msg.Keys) { showM += k + "中不能包含广告词:" + msg[k] + ";"; } this.ShowMsg(showM, false); return; } string text2 = this.fckDescription.Text; string text3 = this.fckmobbileDescription.Text; if (this.ckbIsDownPic.Checked) { text2 = base.DownRemotePic(text2); text3 = base.DownRemotePic(text3); } System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("<script[^>]*?>.*?</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); ProductInfo productInfo = ProductHelper.GetProductDetails(this.productId); if (productInfo.ConversionRelation != ConversionRelation) { if (productInfo.Stock > 0) { this.ShowMsg("销售库存大于0不允许修改换算系数", false); return; } } //ProductInfo productInfo = new ProductInfo //{ productInfo.ProductId = this.productId; productInfo.CategoryId = this.categoryId; productInfo.TypeId = this.dropProductTypes.SelectedValue; productInfo.ProductName = text; productInfo.ProductCode = this.txtProductCode.Text; productInfo.AdminFraction = adminFraction; productInfo.DisplaySequence = displaySequence; productInfo.MarketPrice = marketPrice; productInfo.Unit = this.ddlUnit.SelectedItem.Text; productInfo.ImageUrl1 = this.uploader1.UploadedImageUrl; productInfo.ImageUrl2 = this.uploader2.UploadedImageUrl; productInfo.ImageUrl3 = this.uploader3.UploadedImageUrl; productInfo.ImageUrl4 = this.uploader4.UploadedImageUrl; productInfo.ImageUrl5 = this.uploader5.UploadedImageUrl; productInfo.ThumbnailUrl40 = this.uploader1.ThumbnailUrl40; productInfo.ThumbnailUrl60 = this.uploader1.ThumbnailUrl60; productInfo.ThumbnailUrl100 = this.uploader1.ThumbnailUrl100; productInfo.ThumbnailUrl160 = this.uploader1.ThumbnailUrl160; productInfo.ThumbnailUrl180 = this.uploader1.ThumbnailUrl180; productInfo.ThumbnailUrl220 = this.uploader1.ThumbnailUrl220; productInfo.ThumbnailUrl310 = this.uploader1.ThumbnailUrl310; productInfo.ThumbnailUrl410 = this.uploader1.ThumbnailUrl410; productInfo.ShortDescription = this.txtShortDescription.Text; productInfo.IsfreeShipping = this.ChkisfreeShipping.Checked; productInfo.IsCustomsClearance = this.ChkisCustomsClearance.Checked; productInfo.IsDisplayDiscount = this.ChkisDisplayDiscount.Checked; productInfo.IsPromotion = this.ChkisPromotion.Checked; productInfo.Description = (!string.IsNullOrEmpty(text2) && text2.Length > 0) ? regex.Replace(text2, "") : null; productInfo.MobblieDescription = (!string.IsNullOrEmpty(text3) && text3.Length > 0) ? regex.Replace(text3, "") : null; productInfo.Title = this.txtTitle.Text; productInfo.MetaDescription = this.txtMetaDescription.Text; productInfo.MetaKeywords = this.txtMetaKeywords.Text; productInfo.AddedDate = System.DateTime.Now; productInfo.BrandId = this.dropBrandCategories.SelectedValue; productInfo.ReferralDeduct = referralDeduct; productInfo.SubMemberDeduct = subMemberDeduct; productInfo.SubReferralDeduct = subReferralDeduct; productInfo.TaxRateId = this.dropTaxRate.SelectedValue; productInfo.TemplateId = this.ddlShipping.SelectedValue; productInfo.SupplierId = this.ddlSupplier.SelectedValue; productInfo.ImportSourceId = this.ddlImportSourceType.SelectedValue; productInfo.BuyCardinality = buyCardinality; productInfo.UnitCode = this.ddlUnit.SelectedValue; productInfo.Manufacturer = txtManufacturer.Text; productInfo.ItemNo = txtItemNo.Text; productInfo.BarCode = txtBarCode.Text; productInfo.Ingredient = txtIngredient.Text; productInfo.ProductStandard = txtProductStandard.Text; productInfo.ConversionRelation = ConversionRelation; productInfo.ProductTitle = this.txtProductTitle.Text;//商品副标题 productInfo.SaleType = string.IsNullOrWhiteSpace(this.dropSaleType.SelectedValue) ? 1 : Convert.ToInt32(this.dropSaleType.SelectedValue); productInfo.EnglishName = this.txtEnglishName.Text; productInfo.SysProductName = this.txtsysProductName.Text; productInfo.Purchase = int.Parse(this.Rd_Purchase.SelectedValue); productInfo.SectionDay = int.Parse(this.txtSectionDay.Text); productInfo.PurchaseMaxNum = int.Parse(this.txtMaxCount.Text.ToString()); //}; ProductSaleStatus saleStatus = ProductSaleStatus.OnSale; if (this.radInStock.Checked) { saleStatus = ProductSaleStatus.OnStock; } if (this.radUnSales.Checked) { saleStatus = ProductSaleStatus.UnSale; } if (this.radOnSales.Checked) { saleStatus = ProductSaleStatus.OnSale; if (productInfo.SaleStatus != ProductSaleStatus.OnSale && ProductHelper.IsExitNoClassifyProduct(this.productId.ToString())) { if (productInfo.SaleType != 2) { this.ShowMsg("商品还未完成归类操作,不能出售", false); return; } } } productInfo.SaleStatus = saleStatus; CategoryInfo category = CatalogHelper.GetCategory(this.categoryId); if (category != null) { productInfo.MainCategoryPath = category.Path + "|"; } System.Collections.Generic.Dictionary <int, System.Collections.Generic.IList <int> > attrs = null; System.Collections.Generic.Dictionary <string, SKUItem> dictionary; if (this.chkSkuEnabled.Checked) { productInfo.HasSKU = true; dictionary = base.GetSkus(this.txtSkus.Text); if (!string.IsNullOrEmpty(ArrhidProductRegistrationNumber.Value)) { Dictionary <string, string>[] dic = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string>[]>(ArrhidProductRegistrationNumber.Value); foreach (string item in dictionary.Keys) { foreach (Dictionary <string, string> d in dic) { if (d["SKU"] == dictionary[item].SKU) { dictionary[item].ProductRegistrationNumber = d["ProductRegistrationNumber"]; dictionary[item].LJNo = d["LJNo"]; int wmsstock; int.TryParse(d["WMSStock"], out wmsstock); dictionary[item].WMSStock = wmsstock; //decimal dcgrossweight=0m; //decimal.TryParse(d["GrossWeight"], out dcgrossweight); //dictionary[item].GrossWeight = dcgrossweight; //decimal dcweight = 0m; //decimal.TryParse(d["Weight"], out dcweight); //dictionary[item].Weight = dcweight; break; } } } } } else { AutoCalcCostPriceAndDeductFee(salePrice, ref costPrice, ref deductFee); dictionary = new System.Collections.Generic.Dictionary <string, SKUItem> { { "0", new SKUItem { SkuId = "0", SKU = Globals.HtmlEncode(Globals.StripScriptTags(this.txtSku.Text.Trim()).Replace("\\", "")), SalePrice = salePrice, CostPrice = costPrice.HasValue ? costPrice.Value : 0m, Stock = stock, FactStock = factstock, Weight = num3.HasValue ? num3.Value : 0m, DeductFee = deductFee.HasValue ? deductFee.Value : 0m, ProductRegistrationNumber = hidProductRegistrationNumber.Value, LJNo = hidLJNo.Value, WMSStock = productInfo.DefaultSku.WMSStock, GrossWeight = grossweight.HasValue?grossweight.Value:0m } } }; if (this.txtMemberPrices.Text.Length > 0) { base.GetMemberPrices(dictionary["0"], this.txtMemberPrices.Text); } } if (!string.IsNullOrEmpty(this.txtAttributes.Text) && this.txtAttributes.Text.Length > 0) { attrs = base.GetAttributes(this.txtAttributes.Text); } ValidationResults validationResults = Validation.Validate <ProductInfo>(productInfo); if (!validationResults.IsValid) { this.ShowMsg(validationResults); return; } System.Collections.Generic.IList <int> list = new System.Collections.Generic.List <int>(); if (!string.IsNullOrEmpty(this.txtProductTag.Text.Trim())) { string text4 = this.txtProductTag.Text.Trim(); string[] array; if (text4.Contains(",")) { array = text4.Split(new char[] { ',' }); } else { array = new string[] { text4 }; } string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string value = array2[i]; list.Add(System.Convert.ToInt32(value)); } } #region ==组合商品 List <ProductsCombination> combinations = new List <ProductsCombination>(); string combinationInfos = base.Request.Form["selectProductsinfo"]; string[] curCom = combinationInfos.Split(new char[] { ',' }); string[] curCom2 = curCom; for (int i = 0; i < curCom2.Length; i++) { string combinationInfo = curCom2[i]; ProductsCombination com = new ProductsCombination(); string[] array3 = combinationInfo.Split(new char[] { '|' }); if (array3.Length == 10) { com.SkuId = array3[0]; com.ProductId = array3[1] == "" ? 0 : Convert.ToInt32(array3[1]); com.ProductName = array3[2]; com.ThumbnailsUrl = array3[3]; decimal tempweight; if (decimal.TryParse(array3[4], out tempweight)) { com.Weight = tempweight; } com.SKU = array3[5]; com.SKUContent = array3[6]; com.Quantity = array3[8] == "" ? 0 : Convert.ToInt32(array3[8]); decimal tempprice; if (decimal.TryParse(array3[9], out tempprice)) { com.Price = tempprice; } combinations.Add(com); } } productInfo.CombinationItemInfos = combinations; #endregion if (productInfo.SaleType == 2) { decimal CombinationTotalPrice = 0M; foreach (var item in productInfo.CombinationItemInfos) { CombinationTotalPrice += item.Price * item.Quantity; } if (Math.Round(CombinationTotalPrice, 2) != Math.Round(salePrice, 2)) { this.ShowMsg("添加商品失败,组合商品一口价和组合商品明细总价不一致", false); return; } } ProductActionStatus productActionStatus = ProductHelper.UpdateProduct(productInfo, dictionary, attrs, list, combinations); if (productActionStatus == ProductActionStatus.Success) { this.litralProductTag.SelectedValue = list; this.ShowMsg("修改商品成功", true); base.Response.Redirect(Globals.GetAdminAbsolutePath(string.Format("/product/AddProductComplete.aspx?categoryId={0}&productId={1}&IsEdit=1", this.categoryId, productInfo.ProductId)), true); return; } if (productActionStatus == ProductActionStatus.AttributeError) { this.ShowMsg("修改商品失败,保存商品属性时出错", false); return; } if (productActionStatus == ProductActionStatus.DuplicateName) { this.ShowMsg("修改商品失败,商品名称不能重复", false); return; } if (productActionStatus == ProductActionStatus.DuplicateSKU) { this.ShowMsg("修改商品失败,商家编码不能重复", false); return; } if (productActionStatus == ProductActionStatus.SKUError) { this.ShowMsg("修改商品失败,商家编码不能重复", false); return; } if (productActionStatus == ProductActionStatus.ProductTagEroor) { this.ShowMsg("修改商品失败,保存商品标签时出错", false); return; } this.ShowMsg("修改商品失败,未知错误", false); }
private void OnEntryTextChanged(object sender, TextChangedEventArgs args) { if (!string.IsNullOrWhiteSpace(args.NewTextValue)) { char[] charArray = (sender as Entry).Text.ToCharArray(); Regex reg = null; reg = new System.Text.RegularExpressions.Regex("^[0-9][0-9]*$"); bool isValid = args.NewTextValue.ToCharArray().All(x => char.IsDigit(x)); //Make sure all characters are numbers bool isValidInput = reg.IsMatch(((Entry)sender).Text); if ((sender as Entry).Text.Length == 2 && charArray[0] == '0') { bool firstCharZero = charArray[0].Equals('0'); ((Entry)sender).Text = firstCharZero ? args.NewTextValue.Replace(args.NewTextValue, charArray[1].ToString()): args.NewTextValue; } else { ((Entry)sender).Text = (isValid && isValidInput) ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1); } if (isValid && isValidInput) { Entry text = (Entry)sender; TestSessionModel context = text.BindingContext as TestSessionModel; string subDomain = null; string parentDomainCode = null; int input = 0, range = 0; var entryText = ((Entry)sender).Text; if (entryText != string.Empty) { input = Int32.Parse(entryText); if (context != null) { subDomain = context.Domain.ToString(); parentDomainCode = context.ParentDomainCode.ToString(); } if (subDomain == "Self-Care") { range = 74; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Personal Responsibility" || subDomain == "Peer Interaction" || subDomain == "Perceptual Motor") { range = 48; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Adult Interaction") { range = 54; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Self-Concept and Social Role" || subDomain == "Reasoning and Academic Skills" || subDomain == "Perception and Concepts") { range = 66; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Receptive Communication") { range = 68; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Expressive Communication") { range = 82; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Gross Motor") { range = 90; var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else if (subDomain == "Fluency") { range = 90; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (subDomain == "Fine Motor" || subDomain == "Attention and Memory") { range = 60; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Social-Emotional" || subDomain == "Communication" || subDomain == "Motor" || subDomain == "Cognitive") { range = 40; ((Entry)sender).Text = ValidateRange(range, input); } else if (subDomain == "Print Concepts" || subDomain == "Letter-Sound Correspondence") { range = 12; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (subDomain == "Rhyming" || subDomain == "Syllables" || subDomain == "Onset Rime" || subDomain == "Phoneme Identification" || subDomain == "Phoneme Blending and Segmenting" || subDomain == "Phoneme Manipulation" || subDomain == "Early Decoding" || subDomain == "Sight Words" || subDomain == "Nonsense Words" || subDomain == "Long Vowel Patterns" || subDomain == "Inflectional Endings" || subDomain == "Geometry" || subDomain == "Operations and Algebraic Thinking" || subDomain == "Measurement and Data") { range = 10; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (subDomain == "Letter Identification") { range = 52; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (subDomain == "Listening Comprehension") { range = 14; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (subDomain == "Numbers, Counting, and Sets") { range = 19; if (Device.RuntimePlatform != Device.iOS) { var result = ValidateRange(range, input); if (result != null) { isAcademic = false; ((Entry)sender).Text = result.ToString(); } else { isAcademic = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } else { ((Entry)sender).Text = ValidateRange(range, input); } } else if (parentDomainCode == "ADP") { range = 40; var result = ValidateRange(range, input); if (result != null) { isAdaptive = false; ((Entry)sender).Text = result.ToString(); } else { isAdaptive = true; ((Entry)sender).Unfocus(); ((Entry)sender).Focus(); } } } } } else { return; } }
public PluginApi.Plugins.Playlist GetTorrentPageRuTr(IPluginContext context, string URL) { System.Net.WebRequest RequestGet = System.Net.WebRequest.Create(URL); if (ProxyEnablerRuTr == true) { RequestGet.Proxy = new System.Net.WebProxy(ProxyServr, ProxyPort); } RequestGet.Method = "GET"; RequestGet.Headers.Add("Cookie", Cookies); System.Net.WebResponse Response = RequestGet.GetResponse(); System.IO.Stream dataStream = Response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream, System.Text.Encoding.GetEncoding(1251)); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); Response.Close(); System.Text.RegularExpressions.Regex Regex = new System.Text.RegularExpressions.Regex("(?<=<p><a href=\").*?(?=\")"); string TorrentPath = TrackerServer + "/forum/" + Regex.Matches(responseFromServer)[0].Value; System.Net.WebRequest RequestTorrent = System.Net.WebRequest.Create(TorrentPath); if (ProxyEnablerRuTr == true) { RequestTorrent.Proxy = new System.Net.WebProxy(ProxyServr, ProxyPort); } RequestTorrent.Method = "GET"; RequestTorrent.Headers.Add("Cookie", Cookies); Response = RequestTorrent.GetResponse(); dataStream = Response.GetResponseStream(); reader = new System.IO.StreamReader(dataStream, System.Text.Encoding.GetEncoding(1251)); string FileTorrent = reader.ReadToEnd(); System.IO.File.WriteAllText(System.IO.Path.GetTempPath() + "TorrentTemp.torrent", FileTorrent, System.Text.Encoding.GetEncoding(1251)); reader.Close(); dataStream.Close(); Response.Close(); TorrentPlayList[] PlayListtoTorrent = GetFileListJSON(System.IO.Path.GetTempPath() + "TorrentTemp.torrent", IPAdress); System.Collections.Generic.List <Item> items = new System.Collections.Generic.List <Item>(); string Description = FormatDescriptionFileRuTr(responseFromServer); foreach (TorrentPlayList PlayListItem in PlayListtoTorrent) { Item Item = new Item(); Item.Name = PlayListItem.Name; Item.ImageLink = "http://s1.iconbird.com/ico/1012/AmpolaIcons/w256h2561350597291videofile.png"; Item.Link = PlayListItem.Link; Item.Type = ItemType.FILE; Item.Description = Description; items.Add(Item); } return(PlayListPlugPar(items, context)); }
/// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement evaluator. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> private static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat) { if (evaluator == null) { throw new ArgumentNullException(nameof(evaluator)); } if (count < -1) { throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); } if (startat < 0 || startat > input.Length) { throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); } if (count == 0) { return(input); } Match match = regex.Match(input, startat); if (!match.Success) { return(input); } else { Span <char> charInitSpan = stackalloc char[ReplaceBufferSize]; var vsb = new ValueStringBuilder(charInitSpan); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) { vsb.Append(input.AsSpan(prevat, match.Index - prevat)); } prevat = match.Index + match.Length; string result = evaluator(match); if (!string.IsNullOrEmpty(result)) { vsb.Append(result); } if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) { vsb.Append(input.AsSpan(prevat, input.Length - prevat)); } } else { // In right to left mode append all the inputs in reversed order to avoid an extra dynamic data structure // and to be able to work with Spans. A final reverse of the transformed reversed input string generates // the desired output. Similar to Tower of Hanoi. int prevat = input.Length; do { if (match.Index + match.Length != prevat) { vsb.AppendReversed(input.AsSpan(match.Index + match.Length, prevat - match.Index - match.Length)); } prevat = match.Index; vsb.AppendReversed(evaluator(match)); if (--count == 0) { break; } match = match.NextMatch(); } while (match.Success); if (prevat > 0) { vsb.AppendReversed(input.AsSpan(0, prevat)); } vsb.Reverse(); } return(vsb.ToString()); } }
}// add test event end ///////////////////// SUBMIT BUTTON register student//////////////////////////// private void btnsubmit_Click(object sender, EventArgs e) { //create object of personDTO for taking information fromthe text feilds PersonDTO personInformation = new PersonDTO(); // check either any feild is empty or not and set values if (txtname.Text != "" && txtFathername.Text != "" && txtaddress.Text != "" && txtemail.Text != "" && !comboxgender.SelectedItem.Equals("") && txtphonenumber.Text != "") { try { // validate name if (Regex.IsMatch(txtname.Text, @"^[a-zA-Z]+$")) { personInformation.name = txtname.Text; txtname.Text = ""; } else { MessageBox.Show("Names must be Character"); txtname.Text = ""; return; } }catch (Exception ex) { MessageBox.Show(ex.Message); } try { // validate father name if (Regex.IsMatch(txtFathername.Text, @"^[a-zA-Z]+$")) { personInformation.fatherName = txtFathername.Text; txtFathername.Text = ""; } else { MessageBox.Show("Names must be Character"); txtname.Text = ""; return; } }catch (Exception ex) { MessageBox.Show(ex.Message); } try { //validat ethe phone number if (Regex.IsMatch(txtphonenumber.Text, @"^[0-9]+$")) { personInformation.phoneNumber = int.Parse(txtphonenumber.Text); txtphonenumber.Text = ""; } else { MessageBox.Show("Phone Number must be Digits"); txtname.Text = ""; return; } } catch (Exception ex) { MessageBox.Show(ex.Message); } // set the gender if (comboxgender.SelectedItem.Equals("Male")) { personInformation.gender = true; } else { personInformation.gender = false; } // validate the email of student System.Text.RegularExpressions.Regex expr = new System.Text.RegularExpressions .Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); try { if (!expr.IsMatch(txtemail.Text)) { MessageBox.Show("Invalid Email"); txtemail.Text = ""; // block controll to move onward return; } else { personInformation.email = txtemail.Text; } }catch (Exception ex) { MessageBox.Show(ex.Message); } personInformation.homeAddress = txtaddress.Text; txtaddress.Text = ""; // check either academic record and test record is added then add personal //information completely if (list.Count == 0) { personalStd.addStd(personInformation); //compute ARN key = personInformation.email.GetHashCode(); if (key < 0) { key = key * -1; listOFARN.Add(key); } else { listOFARN.Add(key); } // add record in the table of tabRecord tableRecord.Rows.Add(key, personInformation.name, personInformation.fatherName, personInformation.phoneNumber, personInformation.email); /* * attach email of std to academic records AS ARN KEY */ Education.setARNinacademic(key); personalStd.setARNinperson(key); //show preference form frmPreference frm = new frmPreference(personInformation.email); frm.Show(); } else { MessageBox.Show("Give 3 Degree Records"); } } else { MessageBox.Show("Invalid Input"); } }// submit event call end here
public ActionResult AnaliseExcel() { HttpPostedFileBase file = Request.Files["FileUpload"]; string dados = ""; using (var excel = new ExcelPackage(file.InputStream)) { ExcelWorksheet worksheet = excel.Workbook.Worksheets[1]; var start = worksheet.Dimension.Start; var end = worksheet.Dimension.End; for (int row = start.Row + 1; row <= end.Row; row++) { var rowData = ""; for (int col = start.Column; col < end.Column; col++) { rowData += worksheet.Cells[1, col].Value + " " + worksheet.Cells[row, col].Value + " "; } dados += rowData; } } #region Verificação de cidades var cidades = new Dictionary <String, int>(); var regexCidade = new reg.Regex(@"CIDADE (?<cid>[\w\.\s]+) UF", reg.RegexOptions.IgnoreCase); foreach (reg.Match ocorrencia in regexCidade.Matches(dados)) { var cid = ocorrencia.Groups["cid"].Value; if (!cidades.ContainsKey(cid)) { cidades[cid] = 1; continue; } cidades[cid]++; } List <SelectListItem> topCidades = new List <SelectListItem>(); foreach (var item in cidades.OrderByDescending(d => d.Value).Take(5).ToList()) { topCidades.Add(new SelectListItem { Text = item.Key, Value = item.Value.ToString() }); } #endregion #region Verificação de Períodos var periodos = new Dictionary <String, int>(); var regexPeriodo = new reg.Regex(@"PERIDOOCORRENCIA (?<periodo>[\w\.\s]+) DATACOMUNICACAO", reg.RegexOptions.IgnoreCase); foreach (reg.Match ocorrencia in regexPeriodo.Matches(dados)) { var per = ocorrencia.Groups["periodo"].Value; if (!periodos.ContainsKey(per)) { periodos[per] = 1; continue; } periodos[per]++; } List <SelectListItem> topPeriodos = new List <SelectListItem>(); foreach (var item in periodos.OrderByDescending(d => d.Value).Take(5).ToList()) { topPeriodos.Add(new SelectListItem { Text = item.Key, Value = item.Value.ToString() }); } #endregion #region Verificação de Logradouros var logradouros = new Dictionary <String, int>(); var regexLogradouros = new reg.Regex(@"LOGRADOURO (?<logradouro>[\w\.\s]+) UF", reg.RegexOptions.IgnoreCase); foreach (reg.Match ocorrencia in regexLogradouros.Matches(dados)) { var log = reg.Regex.Replace(ocorrencia.Groups["logradouro"].Value, @"NUMERO (?<logr>[\w\.\s]+) CIDADE", " - "); if (log != " - ") { if (!logradouros.ContainsKey(log)) { logradouros[log] = 1; continue; } logradouros[log]++; } } List <SelectListItem> topLogradouros = new List <SelectListItem>(); foreach (var item in logradouros.OrderByDescending(d => d.Value).Take(5).ToList()) { topLogradouros.Add(new SelectListItem { Text = item.Key, Value = item.Value.ToString() }); } #endregion ViewBag.Periodos = topPeriodos; ViewBag.Cidades = topCidades; ViewBag.Logradouros = topLogradouros; return(PartialView("_AnaliseExcel")); }
/// <summary> /// Draws the main log panel /// </summary> public void DrawLogList(float height) { var oldColor = GUI.backgroundColor; GUI.SetNextControlName(LogListControlName); float buttonY = 0; System.Text.RegularExpressions.Regex filterRegex = null; if (!String.IsNullOrEmpty(FilterRegex)) { filterRegex = new Regex(FilterRegex); } var collapseBadgeStyle = EditorStyles.miniButton; var logLineStyle = EntryStyleBackEven; // If we've been marked dirty, we need to recalculate the elements to be displayed if (Dirty) { if (FilterChanged) { CollapseBadgeMaxWidth = 0; MaxCollapseCount = 0; RenderLogs.Clear(); NextIndexToAdd = 0; CollapsedLines.Clear(); CollapsedLinesList.Clear(); } //When collapsed, count up the unique elements and use those to display if (Collapse) { for (var i = NextIndexToAdd; i < CurrentLogList.Count; i++) { var log = CurrentLogList[i]; if (ShouldShowLog(filterRegex, log)) { var matchString = log.Message + "!$" + log.Severity + "!$" + log.Channel; CountedLog countedLog; if (CollapsedLines.TryGetValue(matchString, out countedLog)) { countedLog.Count++; } else { countedLog = new CountedLog(log, 1); CollapsedLines.Add(matchString, countedLog); CollapsedLinesList.Add(countedLog); RenderLogs.Add(countedLog); } if (MaxCollapseCount < countedLog.Count) { MaxCollapseCount = countedLog.Count; } } } var collapseBadgeContent = new GUIContent(MaxCollapseCount.ToString()); var collapseBadgeSize = collapseBadgeStyle.CalcSize(collapseBadgeContent); CollapseBadgeMaxWidth = Mathf.Max(CollapseBadgeMaxWidth, collapseBadgeSize.x); } //If we're not collapsed, display everything in order else { for (var i = NextIndexToAdd; i < CurrentLogList.Count; i++) { var log = CurrentLogList[i]; if (ShouldShowLog(filterRegex, log)) { RenderLogs.Add(new CountedLog(log, 1)); } } } } var scrollRect = new Rect(DrawPos, new Vector2(position.width, height)); var contentRect = new Rect(0, 0, scrollRect.width, RenderLogs.Count * LogListLineHeight); var viewRect = contentRect; viewRect.width -= 50; Vector2 lastScrollPosition = LogListScrollPosition; LogListScrollPosition = GUI.BeginScrollView(scrollRect, LogListScrollPosition, viewRect, GUIStyle.none, GUI.skin.verticalScrollbar); //If we're following the messages but the user has moved, cancel following if (ScrollFollowMessages) { if (lastScrollPosition.y - LogListScrollPosition.y > LogListLineHeight) { ScrollFollowMessages = false; } } EntryStyleBackEven.padding.left = (int)(CollapseBadgeMaxWidth + LogListLineHeight + 4); EntryStyleBackOdd.padding.left = EntryStyleBackEven.padding.left; //Render all the elements int firstRenderLogIndex = (int)(LogListScrollPosition.y / LogListLineHeight); int lastRenderLogIndex = firstRenderLogIndex + (int)(height / LogListLineHeight); firstRenderLogIndex = Mathf.Clamp(firstRenderLogIndex, 0, RenderLogs.Count); lastRenderLogIndex = Mathf.Clamp(lastRenderLogIndex, 0, RenderLogs.Count); buttonY = firstRenderLogIndex * LogListLineHeight; for (int renderLogIndex = firstRenderLogIndex; renderLogIndex < lastRenderLogIndex; renderLogIndex++) { var countedLog = RenderLogs[renderLogIndex]; var log = countedLog.Log; logLineStyle = (renderLogIndex % 2 == 0) ? EntryStyleBackEven : EntryStyleBackOdd; if (renderLogIndex == SelectedRenderLog) { GUI.backgroundColor = new Color(0.5f, 0.5f, 1); } else { GUI.backgroundColor = Color.white; } //Make all messages single line var content = GetLogLineGUIContent(log, ShowTimes, ShowChannels); var drawRect = new Rect(0, buttonY, contentRect.width, LogListLineHeight); if (GUI.Button(drawRect, content, logLineStyle)) { GUI.FocusControl(LogListControlName); //Select a message, or jump to source if it's double-clicked if (renderLogIndex == SelectedRenderLog) { if (EditorApplication.timeSinceStartup - LastMessageClickTime < DoubleClickInterval) { LastMessageClickTime = 0; // Attempt to display source code associated with messages. Search through all stackframes, // until we find a stackframe that can be displayed in source code view for (int frame = 0; frame < log.Callstack.Count; frame++) { if (JumpToSource(log.Callstack[frame])) { break; } } } else { LastMessageClickTime = EditorApplication.timeSinceStartup; } } else { SelectedRenderLog = renderLogIndex; SelectedCallstackFrame = -1; LastMessageClickTime = EditorApplication.timeSinceStartup; } //Always select the game object that is the source of this message var go = log.Source as GameObject; if (go != null) { Selection.activeGameObject = go; } } var iconRect = drawRect; iconRect.x = CollapseBadgeMaxWidth + 2; iconRect.width = LogListLineHeight; GUI.DrawTexture(iconRect, GetIconForLog(log), ScaleMode.ScaleAndCrop); if (Collapse) { GUI.backgroundColor = Color.white; var collapseBadgeContent = new GUIContent(countedLog.Count.ToString()); var collapseBadgeRect = new Rect(0, buttonY, CollapseBadgeMaxWidth, LogListLineHeight); GUI.Button(collapseBadgeRect, collapseBadgeContent, collapseBadgeStyle); } buttonY += LogListLineHeight; } //If we're following the log, move to the end if (ScrollFollowMessages && RenderLogs.Count > 0) { LogListScrollPosition.y = ((RenderLogs.Count + 1) * LogListLineHeight) - scrollRect.height; } NextIndexToAdd = CurrentLogList.Count; GUI.EndScrollView(); DrawPos.y += height; DrawPos.x = 0; GUI.backgroundColor = oldColor; }
/// <summary> /// 判断是否英文字母或数字的C#正则表达式 /// </summary> /// <param name="c"></param> /// <returns></returns> public static bool IsNatural_Number(char c) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$"); return(reg1.IsMatch(c.ToString())); }
///<summary> ///分析响应流,去掉响应头 ///</summary> ///<param name="buffer"></param> private void GetResponseHeader(byte[] buffer, out int startIndex) { responseHeaders.Clear(); string html = encoding.GetString(buffer); StringReader sr = new StringReader(html); int start = html.IndexOf("\r\n\r\n") + 4; //找到空行位置 strResponseHeaders = html.Substring(0, start); //获取响应头文本 //获取响应状态码 // if (sr.Peek() > -1) { //读第一行字符串 string line = sr.ReadLine(); //分析此行字符串,获取服务器响应状态码 Match M = RE.Match(line, @"\d\d\d"); if (M.Success) { statusCode = int.Parse(M.Value); } } //获取响应头 // while (sr.Peek() > -1) { //读一行字符串 string line = sr.ReadLine(); //若非空行 if (line != "") { //分析此行字符串,获取响应标头 Match M = RE.Match(line, "([^:]+):(.+)"); if (M.Success) { try { //添加响应标头到集合 responseHeaders.Add(M.Groups[1].Value.Trim(), M.Groups[2].Value.Trim()); } catch { } //获取Cookie if (M.Groups[1].Value == "Set-Cookie") { M = RE.Match(M.Groups[2].Value, "[^=]+=[^;]+"); cookie += M.Value.Trim() + ";"; } } } //若是空行,代表响应头结束响应实体开始。(响应头和响应实体间用一空行隔开) else { //如果响应头中没有实体大小标头,尝试读响应实体第一行获取实体大小 if (responseHeaders["Content-Length"] == null && sr.Peek() > -1) { //读响应实体第一行 line = sr.ReadLine(); //分析此行看是否包含实体大小 Match M = RE.Match(line, "~[0-9a-fA-F]{1,15}"); if (M.Success) { //将16进制的实体大小字符串转换为10进制 int length = int.Parse(M.Value, System.Globalization.NumberStyles.AllowHexSpecifier); responseHeaders.Add("Content-Length", length.ToString());//添加响应标头 strResponseHeaders += M.Value + "\r\n"; } } break;//跳出循环 }//End If }//End While sr.Close(); //实体开始索引 startIndex = encoding.GetBytes(strResponseHeaders).Length; }
/// <summary> /// 判断字符是否是中文字符 /// </summary> /// <param name="c">要判断的字符</param> /// <returns>true:是中文字符,false:不是</returns> public static bool IsChinese(char c) { System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("^[\u4e00-\u9fa5]$"); return(rx.IsMatch(c.ToString())); }
void Main(string s) { Regex r; r = new Regex(""); // Compliant, less than 3 characters r = new Regex("**"); // Compliant, less than 3 characters r = new Regex("+*"); // Compliant, less than 3 characters r = new Regex("abcdefghijklmnopqrst"); // Compliant, does not have the special characters r = new Regex("abcdefghijklmnopqrst+"); // Compliant, has only 1 special character r = new Regex("{abc}+defghijklmnopqrst"); // Noncompliant r = new Regex("{abc}+{a}"); // Noncompliant {{Make sure that using a regular expression is safe here.}} // ^^^^^^^^^^^^^^^^^^^^^^ r = new Regex("+++"); // Noncompliant r = new Regex(@"\+\+\+"); // Noncompliant FP (escaped special characters) r = new Regex("{{{"); // Noncompliant r = new Regex(@"\{\{\{"); // Noncompliant FP (escaped special characters) r = new Regex("***"); // Noncompliant r = new Regex(@"\*\*\*"); // Noncompliant FP (escaped special characters) r = new Regex("(a+)+s", RegexOptions.Compiled); // Noncompliant r = new Regex("(a+)+s", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant r = new Regex("{ab}*{ab}+{cd}+foo*"); // Noncompliant Regex.IsMatch("", "(a+)+s"); // Noncompliant // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Regex.IsMatch(s, "(a+)+s", RegexOptions.Compiled); // Noncompliant Regex.IsMatch("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant Regex.Match(s, "{foo}{bar}"); // Noncompliant Regex.Match("", "{foo}{bar}", RegexOptions.Compiled); // Noncompliant Regex.Match("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant Regex.Matches(s, "{foo}{bar}"); // Noncompliant Regex.Matches("", "{foo}{bar}", RegexOptions.Compiled); // Noncompliant Regex.Matches("", "{foo}{bar}", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant Regex.Replace(s, "ab*cd*", match => ""); // Noncompliant Regex.Replace("", "ab*cd*", ""); // Noncompliant Regex.Replace("", "ab*cd*", match => "", RegexOptions.Compiled); // Noncompliant Regex.Replace("", "ab*cd*", s, RegexOptions.Compiled); // Noncompliant Regex.Replace("", "ab*cd*", match => "", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant Regex.Replace("", "ab*cd*", "", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant Regex.Replace("", "ab\\*cd\\*", "", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant FP (escaped special characters) Regex.Split("", "a+a+"); // Noncompliant Regex.Split("", "a+a+", RegexOptions.Compiled); // Noncompliant Regex.Split("", "a+a+", RegexOptions.Compiled, TimeSpan.Zero); // Noncompliant new System.Text.RegularExpressions.Regex("a+a+"); // Noncompliant new RE("a+b+"); // Noncompliant System.Text.RegularExpressions.Regex.IsMatch("", "{}{}"); // Noncompliant RE.IsMatch("", "a**"); // Noncompliant IsMatch("", "b**"); // Noncompliant // Non-static methods are compliant r.IsMatch("a+a+"); r.IsMatch("{ab}*{ab}+{cd}+foo*", 0); r.Match("{ab}*{ab}+{cd}+foo*"); r.Match("{ab}*{ab}+{cd}+foo*", 0); r.Match("{ab}*{ab}+{cd}+foo*", 0, 1); r.Matches("{ab}*{ab}+{cd}+foo*"); r.Matches("{ab}*{ab}+{cd}+foo*", 0); r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*"); r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*"); r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*", 0); r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*", 0); r.Replace("{ab}*{ab}+{cd}+foo*", match => "{ab}*{ab}+{cd}+foo*", 0, 0); r.Replace("{ab}*{ab}+{cd}+foo*", "{ab}*{ab}+{cd}+foo*", 0, 0); r.Split("{ab}*{ab}+{cd}+foo*"); r.Split("{ab}*{ab}+{cd}+foo*", 0); r.Split("{ab}*{ab}+{cd}+foo*", 0, 0); // not hardcoded strings are compliant r = new Regex(s); r = new Regex(s, RegexOptions.Compiled, TimeSpan.Zero); Regex.Replace("{ab}*{ab}+{cd}+foo*", s, "{ab}*{ab}+{cd}+foo*", RegexOptions.Compiled, TimeSpan.Zero); Regex.Split("{ab}*{ab}+{cd}+foo*", s, RegexOptions.Compiled, TimeSpan.Zero); }
public string GetImageDateName(string inputFilePath) { try { string path = inputFilePath.ToString(); string fileName = Path.GetFileNameWithoutExtension(path); if (fileName.Contains("GF")) { Match match = Regex.Match(fileName, @"_(\d{8})_"); if (match.Groups.Count > 1) { return(match.Groups[1].Value); } else { return(string.Empty); } } else if (fileName.ToUpper().Contains("FY2E") || fileName.ToUpper().Contains("FY2F") || fileName.ToUpper().Contains("FY3A") || fileName.ToUpper().Contains("FY3B") || fileName.ToUpper().Contains("FY3C")) { string date = ""; string time = ""; Match match = Regex.Match(fileName, @"_(\d{8})_"); if (match.Groups.Count > 1) { date = match.Groups[1].Value; } else { return(string.Empty); } Match match1 = Regex.Match(fileName, @"_(\d{4})_"); string[] strArr = fileName.Split('_'); foreach (var item in strArr) { System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$"); if (rex.IsMatch(item) && item.Length == 4) { time = item.ToString(); break; } } return(date + time); } else if (fileName.ToUpper().Contains("FY4A")) { Match match = Regex.Match(fileName, @"_(\d{14})_"); if (match.Groups.Count > 1) { return(match.Groups[1].Value); } else { return(string.Empty); } } else if (fileName.ToUpper().Contains("HJ")) { Match match = Regex.Match(fileName, @"-(\d{8})-"); if (match.Groups.Count > 1) { return(match.Groups[1].Value); } else { return(string.Empty); } } else { return(string.Empty); } } catch (Exception ex) { Console.WriteLine( string.Format("RasterSourceManager.GetImageDateName({0})", Path.GetFileName(inputFilePath)), ex); } return(string.Empty); }
public WebPermissionInfo(System.Text.RegularExpressions.Regex regex) { this._type = WebPermissionInfoType.InfoRegex; this._info = regex; }
private async void button1_Click(object sender, EventArgs e) { txt_twsearch.ReadOnly = true; button1.Enabled = false; var keyword = txt_twsearch.Text; string battleid = "00000000"; int cnt = 0; String[] star = { "★", "|", "☆", "|" }; flag = true; try { var tokens = CoreTweet.Tokens.Create(appKey, appSKey, Properties.Settings.Default.usertoken, Properties.Settings.Default.usertokenS); while (flag) { cnt++; var result = new CoreTweet.SearchResult(); try { result = await tokens.Search.TweetsAsync(count => 1, q => keyword); } catch (Exception er) { Console.WriteLine(er.Message); continue; } Console.WriteLine(result.Count); foreach (var tweet in result) { string nowbattleid = ""; Console.WriteLine("{0}: {1}", tweet.CreatedAt, tweet.Text); System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex( @"[a-fA-F0-9]{8,8}", System.Text.RegularExpressions.RegexOptions.IgnoreCase); System.Text.RegularExpressions.Match m = r.Match(tweet.Text); while (m.Success) { nowbattleid = m.Value; // 最初のヒットを利用 break; } if (battleid.Equals(nowbattleid)) { break; } battleid = nowbattleid; var jst = tweet.CreatedAt.LocalDateTime; Clipboard.SetText(battleid); textBox1.Text = jst + "\r\n" + tweet.User.ScreenName + "\r\n" + tweet.Text.Replace("\n", "\r\n").Replace("\r\r", "\r"); notifyIcon1.BalloonTipTitle = battleid; notifyIcon1.BalloonTipText = tweet.Text; notifyIcon1.ShowBalloonTip(1000); } await Task.Delay(Decimal.ToInt32(numericUpDown1.Value) * 250); label3.Text = star[((cnt * 4 + 0) % 4)] + ":" + cnt; await Task.Delay(Decimal.ToInt32(numericUpDown1.Value) * 250); label3.Text = star[((cnt * 4 + 1) % 4)] + ":" + cnt; await Task.Delay(Decimal.ToInt32(numericUpDown1.Value) * 250); label3.Text = star[((cnt * 4 + 2) % 4)] + ":" + cnt; await Task.Delay(Decimal.ToInt32(numericUpDown1.Value) * 250); label3.Text = star[((cnt * 4 + 3) % 4)] + ":" + cnt; } } catch (CoreTweet.TwitterException er) { textBox1.Text = er.Message; } }