Example #1
3
 private static void BaseLine(System.IO.TextReader reader, System.IO.TextWriter writer)
 {
     var x = reader.ReadToEnd();
     var r = new System.Text.RegularExpressions.Regex(@"[^_a-f\s]+");
     for (var k = 0; k < 3; k++)
     {
         var y = new String(x.Reverse().ToArray());
         y = r.Replace(y, "_");
         writer.Write(new string(y.Reverse().ToArray()));
     }
 }
Example #2
0
 /// <summary>
 /// Html到文本
 /// </summary>
 /// <param name="Html"></param>
 /// <param name="html"></param>
 /// <returns></returns>
 public static string Html2String(this HtmlHelper Html, string html)
 {
     System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[/s/S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[/s/S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[/s/S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[/s/S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[/s/S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"/<img[^/>]+/>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     html = regex1.Replace(html, ""); //过滤<script></script>标记
     html = regex1.Replace(html, ""); //过滤<script></script>标记
     html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
     html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
     html = regex4.Replace(html, ""); //过滤iframe
     html = regex5.Replace(html, ""); //过滤frameset
     html = regex6.Replace(html, ""); //过滤frameset
     html = regex7.Replace(html, ""); //过滤frameset
     html = regex8.Replace(html, ""); //过滤frameset
     html = regex9.Replace(html, "");
     html = html.Replace("&nbsp;", " ");
     html = html.Replace("</strong>", "");
     html = html.Replace("<strong>", "");
     return html;
 }
        /// <summary>
        /// Return Error Messages
        /// </summary>
        /// <param name="errors"></param>
        /// <returns></returns>
        public static List<String> ReturnErrorMessages(IEnumerable errors)
        {

            var r = new System.Text.RegularExpressions.Regex(@"
                (?<=[A-Z])(?=[A-Z][a-z]) |
                 (?<=[^A-Z])(?=[A-Z]) |
                 (?<=[A-Za-z])(?=[^A-Za-z])", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);

            List<String> errorMessages = new List<String>();

            foreach (System.Web.Http.ModelBinding.ModelState state in errors)
            {                
                foreach (var error in state.Errors)
                {
                    if (error.Exception != null)
                    {
                        string[] objectProperty = error.Exception.ToString().Split(Convert.ToChar("'"));
                        if (objectProperty.Length > 2)
                        {
                            string errorMessage = r.Replace(objectProperty[1], " ");
                            errorMessages.Add(errorMessage + " is invalid.");
                        }
                        else
                        {
                            errorMessages.Add(error.Exception.ToString());
                        }
                    }
                }

            }
          
            return errorMessages;

        }
		private System.Net.CookieContainer ParseCookieSettings(string line)
		{
			System.Net.CookieContainer container = new System.Net.CookieContainer();

			// クッキー情報の前についているよくわからないヘッダー情報を取り除く
			// 対象:
			//  \\xと2桁の16進数値
			//  \\\\
			//  \がない場合の先頭1文字
			string matchPattern = "^(\\\\x[0-9a-fA-F]{2})|^(\\\\\\\\)|^(.)|[\"()]";
			System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(matchPattern, System.Text.RegularExpressions.RegexOptions.Compiled);

			string[] blocks = line.Split(new string[] { "\\0\\0\\0" }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string block in blocks) {
				if (block.Contains("=") && block.Contains("domain")) {
					string header = reg.Replace(block, "");
					System.Net.Cookie cookie = ParseCookie(header);
					if (cookie != null) {
						try {
							container.Add(cookie);
						} catch(Exception ex) {
							CookieGetter.Exceptions.Enqueue(ex);
						}
					}
				}
			}

			return container;
		}
        /// <summary>
        /// Return Error Messages
        /// </summary>
        /// <param name="errors"></param>
        /// <returns></returns>
        public static List<String> ReturnErrorMessages(IEnumerable errors)
        {
            var r = new System.Text.RegularExpressions.Regex(@"
                (?<=[A-Z])(?=[A-Z][a-z]) |
                 (?<=[^A-Z])(?=[A-Z]) |
                 (?<=[A-Za-z])(?=[^A-Za-z])", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);

            List<String> errorMessages = new List<String>();

            foreach (KeyValuePair<string, string[]> item in errors)
            {
                string errorMessage;

                string keyValue = item.Key;

                string[] objectProperty = keyValue.Split(Convert.ToChar("."));
                if (objectProperty.Length == 0)
                    errorMessage = item.Value[0];
                else
                {
                    errorMessage = objectProperty[1] + ": " + item.Value[0];
                    if (errorMessage.Contains(objectProperty[1]))
                    {
                        errorMessage = errorMessage.Replace(objectProperty[1], "");
                        errorMessage = objectProperty[1] + errorMessage;
                        errorMessage = errorMessage.Replace(" for ", "");
                    }
                }

                errorMessage = r.Replace(errorMessage, " ");
                errorMessage = errorMessage.Replace(" .", ".");
                errorMessages.Add(errorMessage);
            }
            return errorMessages;
        }
Example #6
0
 /// 过滤html,js,css代码
 /// <summary>
 /// 过滤html,js,css代码
 /// </summary>
 /// <param name="html">参数传入</param>
 /// <returns></returns>
 public static string CheckStr(string html)
 {
     System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script. *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script. *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe. *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     html = regex1.Replace(html, ""); //过滤<script></script>标记
     html = regex2.Replace(html, ""); //过滤href=java script. (<A>) 属性
     html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
     html = regex4.Replace(html, ""); //过滤iframe
     html = regex5.Replace(html, ""); //过滤frameset
     html = regex6.Replace(html, ""); //过滤frameset
     html = regex7.Replace(html, ""); //过滤frameset
     html = regex8.Replace(html, ""); //过滤frameset
     html = regex9.Replace(html, "");
     html = html.Replace(" ", "");
     html = html.Replace("</strong>", "");
     html = html.Replace("<strong>", "");
     html = html.Replace("'", "'");
     return html;
 }
 private static string ReplaceSpriteMetaData(string metafileText, string oldPrefix, string newPrefix)
 {
     string spritenamePattern = "(- name: )" + oldPrefix;
     var spritenameRegex = new System.Text.RegularExpressions.Regex(spritenamePattern);
     string replacementText = "$1" + newPrefix;
     return spritenameRegex.Replace(metafileText, replacementText);
 }
 private static string ReplaceFileIDRecycleNames(string metafileText, string oldPrefix, string newPrefix)
 {
     string fileIDPattern = "([\\d]{8}: )" + oldPrefix;
     var fileIDRegex = new System.Text.RegularExpressions.Regex(fileIDPattern);
     string replacementText = "$1" + newPrefix;
     return fileIDRegex.Replace(metafileText, replacementText);
 }
Example #9
0
 /// <summary>
 /// 清除HTML代码
 /// </summary>
 /// <param name="text"></param>
 /// <returns></returns>
 public static string CleanHTML(string text)
 {
     var regex = new System.Text.RegularExpressions.Regex(@"(<[a-zA-Z].*?>)|(<[\/][a-zA-Z].*?>)");
         var content = regex.Replace(text, string.Empty);
         content = content.Replace("&nbsp;", " ");
         return content;
 }
        public string GetDocElement(string elementName)
        {
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[\t\n\r]+");

            htmlDoc.LoadHtml(this._html);
            switch (elementName)
            {
                case "Title":
                    return regex.Replace(htmlDoc.DocumentNode.SelectNodes("div[@id='METADATA']/div[@id='TITLE']")[0].InnerText, " ");
                case "Description":
                    return regex.Replace(HttpUtility.HtmlDecode(htmlDoc.DocumentNode.SelectNodes("div[@id='METADATA']/div[@id='DESCRIPTION']")[0].InnerText), " ");
                default:
                    return "";
            }
        }
Example #11
0
        private string VerifSaisie(string numero)
        {
            Boolean plusEnPremier = false;
            String resultatfinal = "";
            numero = numero.Trim();
            //filtre regex on ne garde que ce qui est chiffre et '+'
            System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex("[^0-9+]");
            string resultat1 = myRegex.Replace(numero, "");

            if (resultat1.Length > 0)//Si le résultat du premier chiffre donne autre chose qu'une chainbe vide on continue
            {
                if (resultat1[0] == '+')//on verifie si le premier élement de la collection de caractére est un "+", si oui on valorise un booleen
                { plusEnPremier = true; }
                myRegex = new System.Text.RegularExpressions.Regex("[^0-9]");//on garde que les chiffres dans la chaine
            }
            //test du boleen si oui on rajoute le caractére '+'
            if (plusEnPremier)
            {
                resultatfinal = "+" + myRegex.Replace(resultat1, "");
            }
            else
            {
                resultatfinal = myRegex.Replace(resultat1, "");
            }

            return resultatfinal; //renvoi la chaine modifiée
        }
 public string ConvertToUnsign3(string str)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\p{IsCombiningDiacriticalMarks}+");
     string temp = str.Normalize(System.Text.NormalizationForm.FormD);
     return regex.Replace(temp, String.Empty)
                 .Replace('\u0111', 'd').Replace('\u0110', 'D');
     //return str;
 }
 public string CleanInvalidXmlChars(string xml)
 {
     string pattern = @"&#x((10?|[2-F])FFF[EF]|FDD[0-9A-F]|[19][0-9A-F]|7F|8[0-46-9A-F]|0?[1-8BCEF]);";
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     if (regex.IsMatch(xml))
         xml = regex.Replace(xml, String.Empty);
     return xml;
 }
Example #14
0
 public string CompressContent(string content)
 {
     string pattern = "(?<!\\\")debugger(?<!\\\");";
     string replacement = "eval(\"debugger;\");";
     var regex = new System.Text.RegularExpressions.Regex(pattern);
     content = regex.Replace(content, replacement);
     return JavaScriptCompressor.Compress(content);
 }
Example #15
0
 public EducationalProgram(string parCycle, string parActivity, string parIndex)
 {
     // System.Text.RegularExpressions.Regex.Replace(edProgram.Cycle, " +", " ") -- удаляет лишние пробелы в строке (к примеру заменяет два подряд на один)
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\W");
     cycle = regex.Replace(parCycle, " ").Trim();
     cycle = System.Text.RegularExpressions.Regex.Replace(cycle, " +", " ");
     activityType= parActivity;
     index = parIndex; 
 }
Example #16
0
        public static string FilterParams(string sql)
        {
            if (sql == null)
                return null;

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(Gateway.Default.Db.DbProvider.ParamPrefix+ @"([\w\d_]+)");

            return r.Replace(sql, "?");
        }
Example #17
0
 /// <summary>
 /// Remove caracteres não numéricos
 /// </summary>
 /// <param name="text"></param>
 /// <returns></returns>
 public static string RemoveNaoNumericos(string text)
 {
     string ret = null;
     if (!string.IsNullOrEmpty(text))
     {
     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[^0-9]");
     ret = reg.Replace(text, string.Empty);
     }
     return ret;
 }
Example #18
0
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            string str = GetText();

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"@[^\s]*");
            str = regex.Replace(str, " ");

            SetText(str);

            base.Run(runChildren);
        }
 public string GetLittleMinfo(object obj)
 {
     string info = obj.ToString();
     System.Text.RegularExpressions.Regex htmlRegex = new System.Text.RegularExpressions.Regex("<[^>]*>");
     string newInfo = htmlRegex.Replace(info, "");	//���˵�html�ַ���
     if (newInfo.Length > 150)
     {
         newInfo = newInfo.Substring(0, 150) + "������������";
     }
     return newInfo;
 }
Example #20
0
 public static string GetDescription2(string content, int num)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"(<)[^>]*(>)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     content = regex.Replace(content, "");
     if (content.Length > num)
     {
         return content.Substring(0, num);
     }
     else
     {
         return content;
     }
 }
Example #21
0
        public static string StripHTML(string strHtml)
        {
            string[] aryReg ={
            @"<script[^>]*?>.*?</script>",

            @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
            @"([\r\n])[\s]+",
            @"&(quot|#34);",
            @"&(amp|#38);",
            @"&(lt|#60);",
            @"&(gt|#62);",
            @"&(nbsp|#160);",
            @"&(iexcl|#161);",
            @"&(cent|#162);",
            @"&(pound|#163);",
            @"&(copy|#169);",
            @"&#(\d+);",
            @"-->",
            @"<!--.*\n"
            };

            string[] aryRep = {
            "",
            "",
            "",
            "\"",
            "&",
            "<",
            ">",
            " ",
            "\xa1",//chr(161),
            "\xa2",//chr(162),
            "\xa3",//chr(163),
            "\xa9",//chr(169),
            "",
            "\r\n",
            ""
            };

            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(aryReg[i], System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }
            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");
            return strOutput;
        }
Example #22
0
		private string StripAllTags(string content)
		{
			string regex = "<(.|\n)+?>";
			System.Text.RegularExpressions.RegexOptions options = System.Text.RegularExpressions.RegexOptions.IgnoreCase;
			System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
			string retVal = content;
			try
			{
				retVal = reg.Replace(content, String.Empty);
			}
			catch
			{ //swallow anything that might go wrong
			}
			return retVal;
		}
Example #23
0
        protected override void Render(HtmlTextWriter writer)
        {
            string appPath       = Request.ApplicationPath;
            string extBasePath   = Config.ExtBasePath;
            string extDomain     = Config.ExtDomain;
            string extBaseUrl    = Config.ExtBaseUrl;
            string xForwardedFor = Request.Headers["X-Forwarded-For"];
            string xForwardedURL = Request.Headers["X-Forwarded-URL"];

            if (!string.IsNullOrEmpty(extBasePath) &&
                Config.TranslateExtUrl &&
                !string.IsNullOrEmpty(xForwardedFor) &&
                (appPath.ToLower() != extBasePath.ToLower()
                )
                )
            {
                System.IO.StringWriter       sw  = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
                base.Render(htw);
                string s = sw.ToString();

                /* only work if application path IS THE SAME LENGTH as external BasePath. i.e. /XX/ => /YY/ but not /ABC/ => /EFGH/
                 * due to partial postback is length sensitive in content */
                /* only do this for partial postback not html content or it would be doubled */
                if (Response.ContentType == "text/plain" && (appPath.Length == extBasePath.Length))
                {
                    // only do this
                    s = s.Replace((Request.ApplicationPath + "/WebResource.axd").Replace("//", "/"), (extBasePath + "/WebResource.axd").Replace("//", "/"))
                        .Replace((Request.ApplicationPath + "/ScriptResource.axd").Replace("//", "/"), (extBasePath + "/ScriptResource.axd").Replace("//", "/"));
                }
                var rx = new System.Text.RegularExpressions.Regex("((src|href)=[\"'])(/" + appPath.Substring(1) + ")");
                s = rx.Replace(s, (m) => { return(m.Groups[1].Value + extBasePath + (appPath == "/" ? "/" : "")); });
                writer.Write(s);
            }
            else
            {
                base.Render(writer);
            }
        }
Example #24
0
        public override string ToString()
        {
            string channelStr = "";

            if (channel > 0)
            {
                channelStr = ",channel=" + channel;
            }
            string txt = Text;

            if (txt != null)
            {
                txt = Regex.Replace(txt, "\n", "\\\\n");
                txt = Regex.Replace(txt, "\r", "\\\\r");
                txt = Regex.Replace(txt, "\t", "\\\\t");
            }
            else
            {
                txt = "<no text>";
            }
            return("[@" + TokenIndex + "," + start + ":" + stop + "='" + txt + "',<" + type + ">" + channelStr + "," + line + ":" + CharPositionInLine + "]");
        }
Example #25
0
        public static void BuildIndex()
        {
            var sDir  = AppDomain.CurrentDomain.BaseDirectory + @"\APKDecompile\apkcode\src";
            var Files = DirSearch(sDir);

            foreach (var file in Files)
            {
                string data = System.IO.File.ReadAllText(file);

                System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]");
                data = rgx.Replace(data, " ");

                Document doc = new Document();
                doc.Add(new Field("FileName", file.Substring(file.LastIndexOf('\\') + 1), Field.Store.YES, Field.Index.UN_TOKENIZED));
                doc.Add(new Field("Data", data, Field.Store.YES, Field.Index.TOKENIZED));
                writer.AddDocument(doc);
            }
            writer.Optimize();
            writer.Flush();
            writer.Close();
            luceneIndexDirectory.Close();
        }
Example #26
0
        static StackObject *Replace_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Text.RegularExpressions.MatchEvaluator @evaluator = (System.Text.RegularExpressions.MatchEvaluator) typeof(System.Text.RegularExpressions.MatchEvaluator).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String @input = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Text.RegularExpressions.Regex instance_of_this_method = (System.Text.RegularExpressions.Regex) typeof(System.Text.RegularExpressions.Regex).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.Replace(@input, @evaluator);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Example #27
0
 public void UpdateSize()
 {
     if (UpdateInProgress == false && Text.Length > 0)
     {
         UpdateInProgress = true;
         int numLines = 0;
         System.Drawing.Size baseSize = new System.Drawing.Size(Width, Int32.MaxValue);
         System.Drawing.Size lineSize = baseSize;      // compiler thinks we need something here...
         // replace CR/LF with single character (paragraph mark '¶')
         string tmpText = rgx.Replace(Text, "\u00B6");
         // split text at paragraph marks
         string[] parts = tmpText.Split(new char[1] {
             '\u00B6'
         });
         numLines = parts.Count();
         foreach (string part in parts)
         {
             // if the width of this line is greater than the width of the text box, add needed lines
             lineSize  = TextRenderer.MeasureText(part, Font, baseSize, TextFormatFlags.TextBoxControl);
             numLines += (int)Math.Floor(((double)lineSize.Width / (double)Width));
         }
         if (numLines > 1)
         {
             Multiline = true;
         }
         else
         {
             Multiline = false;
         }
         int tempHeight = Margin.Top + (lineSize.Height * numLines) + Margin.Bottom;
         if (tempHeight > Height ||                     // need to grow...
             Height - tempHeight > lineSize.Height)     // need to shrink...
         {
             Height = tempHeight;
             VSizeChangedCallback();
         }
         UpdateInProgress = false;
     }
 }
        //Using Regex update the ModuleVersion
        //	ModuleVersion = '1.0.0.0'
        private void RegexVersionModule(string pFileName, Version version)
        {
            string s     = "";
            string regex = @"(?<mod>^\s*ModuleVersion\s*=\s*)(?<ver>('[0-9.]+'))";

            System.Text.Encoding encoding = Helper.GetEncoding(pFileName);
            using (System.IO.StreamReader sr = new System.IO.StreamReader(pFileName))
            {
                s = @sr.ReadToEnd();
            }
            WriteVerbose(string.Format("The encoding used was {0}.", encoding));

            System.Text.RegularExpressions.RegexOptions options = System.Text.RegularExpressions.RegexOptions.Multiline;
            System.Text.RegularExpressions.Regex        re      = new System.Text.RegularExpressions.Regex(regex, options);
            string replacement = String.Format("${{mod}}'{0}'", version.ToString());

            s = re.Replace(@s, replacement);
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(pFileName, false, encoding))
            {
                sw.Write(s);
            }
        }
        public static string TruncateAndStripDisallowed(string value, int?truncateTo = null, System.Text.RegularExpressions.Regex disallowedCharacters = null)
        {
            if (null == value)
            {
                return(null);
            }

            if (null != disallowedCharacters)
            {
                value = disallowedCharacters.Replace(value, String.Empty);
            }

            if (truncateTo.HasValue)
            {
                if (value.Length > truncateTo.Value)
                {
                    value = value.Substring(0, truncateTo.Value);
                }
            }

            return(value);
        }
Example #30
0
        /// <inheritdoc />
        public void Startup(string url, string sessionId, string platformId)
        {
            ServerUri      = new Uri(url, UriKind.Absolute);
            ServerAssetUri = new Uri(Regex.Replace(ServerUri.AbsoluteUri, "^ws(s?):", "http$1:"));

            if (UsePhysicsBridge)
            {
                _actorManager.RigidBodyAdded             += OnRigidBodyAdded;
                _actorManager.RigidBodyRemoved           += OnRigidBodyRemoved;
                _actorManager.RigidBodyKinematicsChanged += OnRigidBodyKinematicsChanged;
                _actorManager.RigidBodyOwnerChanged      += OnRigidBodyOwnerChanged;
            }

            if (_conn == null)
            {
                if (_appState == AppState.Stopped)
                {
                    _appState = AppState.Starting;
                }

                SessionId = sessionId;

                var connection = new WebSocket();

                connection.Url = url;
                connection.Headers.Add(Constants.SessionHeader, sessionId);
                connection.Headers.Add(Constants.PlatformHeader, platformId);
                connection.Headers.Add(Constants.LegacyProtocolVersionHeader, $"{Constants.LegacyProtocolVersion}");
                connection.Headers.Add(Constants.CurrentClientVersionHeader, Constants.CurrentClientVersion);
                connection.Headers.Add(Constants.MinimumSupportedSDKVersionHeader, Constants.MinimumSupportedSDKVersion);
                connection.OnConnecting    += Conn_OnConnecting;
                connection.OnConnectFailed += Conn_OnConnectFailed;
                connection.OnConnected     += Conn_OnConnected;
                connection.OnDisconnected  += Conn_OnDisconnected;
                connection.OnError         += Connection_OnError;
                _conn = connection;
            }
            _conn.Open();
        }
Example #31
0
        public static string UrlDonustur(object Yazi)
        {
            try
            {
                string strSonuc = Yazi.ToString().Trim();

                strSonuc = strSonuc.Replace("-", "+");
                strSonuc = strSonuc.Replace(" ", "+");

                strSonuc = strSonuc.Replace("ç", "c");
                strSonuc = strSonuc.Replace("Ç", "C");

                strSonuc = strSonuc.Replace("ğ", "g");
                strSonuc = strSonuc.Replace("Ğ", "G");

                strSonuc = strSonuc.Replace("ı", "i");
                strSonuc = strSonuc.Replace("İ", "I");

                strSonuc = strSonuc.Replace("ö", "o");
                strSonuc = strSonuc.Replace("Ö", "O");

                strSonuc = strSonuc.Replace("ş", "s");
                strSonuc = strSonuc.Replace("Ş", "S");

                strSonuc = strSonuc.Replace("ü", "u");
                strSonuc = strSonuc.Replace("Ü", "U");

                strSonuc = strSonuc.Trim();
                strSonuc = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9+]").Replace(strSonuc, "");
                strSonuc = strSonuc.Trim();
                strSonuc = strSonuc.Replace("+", "-");
                return(strSonuc.ToLower());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #32
0
        string Content(String html, String appId, Hashtable image)
        {
            var webr  = UMC.Data.WebResource.Instance();
            var regex = new System.Text.RegularExpressions.Regex("(?<key>\\ssrc)=\"(?<src>[^\"]+)\"");

            return(regex.Replace(html, g =>
            {
                var src = g.Groups["src"].Value;

                if (src.StartsWith("http://") || src.StartsWith("https://"))
                {
                    if (image.ContainsKey(src))
                    {
                        src = image["src"] as string;
                    }
                    else
                    {
                        if (src.StartsWith("http://mmbiz.qpic.cn/") == false)
                        {
                            var data = webr.Submit("cgi-bin/media/uploadimg", src, appId);
                            if (data != null)
                            {
                                if (data.ContainsKey("url"))
                                {
                                    image[src] = data["url"];
                                    src = data["url"] as string;
                                }
                            }
                            else
                            {
                                throw new ArgumentException("图片上传到公众号有错误,请联系管理员");
                            }
                        }
                    }
                }
                return String.Format("{0}=\"{1}\"", g.Groups["key"], src);
            }));
        }
Example #33
0
        public static string Final(string xName)
        {
            //var xSB = new StringBuilder(xName);

            // DataMember.FilterStringForIncorrectChars also does some filtering but replacing empties or non _ chars
            // causes issues with legacy hardcoded values. So we have a separate function.
            //
            // For logging possibilities, we generate fuller names, and then strip out spacing/characters.

            /*const string xIllegalChars = "&.,+$<>{}-`\'/\\ ()[]*!=_";
             * foreach (char c in xIllegalChars) {
             * xSB.Replace(c.ToString(), "");
             * }*/
            xName = xName.Replace("[]", "array");
            xName = xName.Replace("<>", "anonymousType");
            xName = xName.Replace("[,]", "array");
            xName = xName.Replace("*", "pointer");
            xName = IllegalCharsReplace.Replace(xName, string.Empty);

            if (xName.Length > MaxLengthWithoutSuffix)
            {
                using (var xHash = MD5.Create())
                {
                    var xValue = xHash.ComputeHash(Encoding.GetEncoding(0).GetBytes(xName));
                    var xSB    = new StringBuilder(xName);
                    // Keep length max same as before.
                    xSB.Length = MaxLengthWithoutSuffix - xValue.Length * 2;
                    foreach (var xByte in xValue)
                    {
                        xSB.Append(xByte.ToString("X2"));
                    }
                    xName = xSB.ToString();
                }
            }

            LabelCount++;
            return(xName);
        }
Example #34
0
        public void SaveFile(string rootpath = null, bool exportImages = false)
        {
            string regexSearch = new string(System.IO.Path.GetInvalidFileNameChars()) + new string(System.IO.Path.GetInvalidPathChars());
            var    r           = new System.Text.RegularExpressions.Regex(string.Format("[{0}]", System.Text.RegularExpressions.Regex.Escape(regexSearch)));

            name = r.Replace(name, "");
            var projectpath = Path;

            if (!string.IsNullOrEmpty(rootpath))
            {
                projectpath = System.IO.Path.Combine(rootpath, name);
            }
            if (!System.IO.Directory.Exists(projectpath))
            {
                System.IO.Directory.CreateDirectory(projectpath);
            }

            if (Workflows == null)
            {
                Workflows = new System.Collections.ObjectModel.ObservableCollection <IWorkflow>();
            }

            var projectfilepath = System.IO.Path.Combine(projectpath, Filename);

            System.IO.File.WriteAllText(projectfilepath, JsonConvert.SerializeObject(this));
            var filenames = new List <string>();

            foreach (var workflow in Workflows)
            {
                if (filenames.Contains(workflow.Filename))
                {
                    workflow.Filename = workflow.UniqueFilename();
                    _ = workflow.Save(false);
                }
                filenames.Add(workflow.Filename);
                workflow.SaveFile(projectpath, exportImages);
            }
        }
Example #35
0
        /// <summary>
        /// html标签格式去除
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public string xxHTML(string html)
        {
            html = html.Replace("(<style)+[^<>]*>[^\0]*(</style>)+", "");
            html = html.Replace(@"\<img[^\>] \>", "");
            html = html.Replace(@"<p>", "");
            html = html.Replace(@"</p>", "");


            System.Text.RegularExpressions.Regex regex0 =
                new System.Text.RegularExpressions.Regex("(<style)+[^<>]*>[^\0]*(</style>)+", System.Text.RegularExpressions.RegexOptions.Multiline);
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S] </script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S] </iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S] </frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>] \>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
            html = regex0.Replace(html, ""); //过滤href=javascript: (<A>) 属性


            //html = regex10.Replace(html, "");
            html = regex3.Replace(html, ""); // _disibledevent="); //过滤其它控件的on...事件
            html = regex4.Replace(html, ""); //过滤iframe
            html = regex5.Replace(html, ""); //过滤frameset
            html = regex6.Replace(html, ""); //过滤frameset
            html = regex7.Replace(html, ""); //过滤frameset
            html = regex8.Replace(html, ""); //过滤frameset
            html = regex9.Replace(html, "");
            //html = html.Replace(" ", "");
            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            html = html.Replace(" ", "");
            return(html);
        }
Example #36
0
 public static string parseSortForDB(string sortOrder, out string sortName, out System.Web.Helpers.SortDirection sortDir)
 {// проверка и разбор параметра для сортировки
     sortName = null;
     sortDir  = System.Web.Helpers.SortDirection.Ascending;
     if (sortOrder != null && sortOrder != string.Empty)
     {// оставляем только буквы/цифры/_
         System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[^\\w]");
         bool a = regex.IsMatch(sortOrder);
         sortOrder = regex.Replace(sortOrder, "");
         // разбиваем на части - название столбца и направление
         string[] sort = sortOrder.Split('_');
         if (sort.Length > 0)
         {
             sortName = sort[0];
         }
         if (sort.Length > 1)
         {
             if (sort[1] == "desc")
             {
                 sortDir = System.Web.Helpers.SortDirection.Descending;
             }
         }
     }
     if (sortName != null && sortName != string.Empty)
     {
         sortOrder = sortName;
         if (sortDir == System.Web.Helpers.SortDirection.Descending)
         {
             sortOrder += " desc";
         }
     }
     else
     {
         sortOrder = "";
         sortDir   = System.Web.Helpers.SortDirection.Ascending;
     }
     return(sortOrder);
 }
Example #37
0
        public static string updateFortunecookieBindNull(string modelString)
        {
            string ret     = "";
            string toCheck = modelString;
            var    regex   = new System.Text.RegularExpressions.Regex("\"[a-zA-Z0-9_]*fortunecookiebind\"");
            var    matches = regex.Matches(modelString);

            foreach (var match in matches)
            {
                string key   = match.ToString();
                int    index = toCheck.IndexOf(key);
                string check = toCheck.Substring(index + key.Length, 5);

                if (check.Equals(":null"))
                {
                    string val = key.Replace("fortunecookiebind", "_value").ToLower();
                    val = val.Insert(1, "_");
                    var regex2 = new System.Text.RegularExpressions.Regex(System.Text.RegularExpressions.Regex.Escape(key));
                    toCheck = regex2.Replace(toCheck, val, 1);
                }
                else
                {
                    ret    += toCheck.Substring(0, index + key.Length);
                    toCheck = toCheck.Substring(index + key.Length);
                }
            }

            ret += toCheck;

            ret = ret.Replace(",\"statecode\":null", "");
            ret = ret.Replace("\"statecode\":null,", "");
            ret = ret.Replace("\"statecode\":null", "");

            ret = ret.Replace(",\"statuscode\":null", "");
            ret = ret.Replace("\"statuscode\":null,", "");
            ret = ret.Replace("\"statuscode\":null", "");
            return(ret);
        }
#pragma warning restore 1591

        CookieCollection ParseCookieSettings(string line)
        {
            var container = new CookieCollection();

            // Cookie情報の前についているよくわからないヘッダー情報を取り除く
            // 対象:
            //  \\xと2桁の16進数値
            //  \\\\
            //  \がない場合の先頭1文字
            var matchPattern = "^(\\\\x[0-9a-fA-F]{2})|^(\\\\\\\\)|^(.)|[\"()]";
            var reg = new System.Text.RegularExpressions.Regex(matchPattern, System.Text.RegularExpressions.RegexOptions.Compiled);
            var blocks = line.Split(new string[] { "\\0\\0\\0" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var block in blocks)
                if (block.Contains("=") && block.Contains("domain"))
                {
                    var header = reg.Replace(block, "");
                    var cookie = ParseCookie(header);
                    if (cookie != null)
                        container.Add(cookie);
                }

            return container;
        }
Example #39
0
        private string FormatFolderString(string text)
        {
            if (text == null)
            {
                return(string.Empty);
            }

            // remove accents
            System.Text.RegularExpressions.Regex nonSpacingMarkRegex = new System.Text.RegularExpressions.Regex(@"\p{Mn}", System.Text.RegularExpressions.RegexOptions.Compiled);
            var normalizedText = text.Normalize(System.Text.NormalizationForm.FormD);

            normalizedText = nonSpacingMarkRegex.Replace(normalizedText, string.Empty);

            // replace spaces for _
            normalizedText = normalizedText.Replace(" ", "_");

            normalizedText = normalizedText.Replace("\"", "");
            normalizedText = normalizedText.Replace("'", "");
            normalizedText = normalizedText.Replace("\\", "");
            normalizedText = normalizedText.Replace("/", "");

            return(normalizedText);
        }
        private bool ValidarCPF(string cpf)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[^0-9]");
            cpf = reg.Replace(cpf, String.Empty);
            if (cpf.Length > 11)
            {
                return(false);
            }

            cpf.PadLeft(11, '0');
            int index = cpf.Length - 1;

            while (cpf[index] == cpf[index - 1] && --index > 0)
            {
                ;
            }
            if (index < 0)
            {
                return(false);
            }

            return(true);
        }
Example #41
0
        private static void LoadDisambiguous()
        {
            lock (disambiguousLocker)
            {
                if (disambiguousDic == null)
                {
                    var dic    = new Dictionary <string, List <string> >();
                    var reader = new LargeFileReader((string)GlobalParameter.Get(DefaultParameter.Field.disambiguous_file));
                    var line   = "";
                    System.Text.RegularExpressions.Regex deleteUnderline = new System.Text.RegularExpressions.Regex(@"_+");

                    while ((line = reader.ReadLine()) != null)
                    {
                        var l     = deleteUnderline.Replace(line, "");
                        var array = line.Split('\t').ToList();
                        dic[array[0]] = array;
                        array.RemoveAt(0);
                    }
                    reader.Close();
                    disambiguousDic = dic;
                }
            }
        }
Example #42
0
        /// <summary>
        /// 生成唯一字符串
        /// </summary>
        /// <returns></returns>
        public static string MakeUniqueKey(Field field)//string prefix,
        {
            //paramPrefixToken
            //return GetRandomNumber().ToString();
            //TODO 此处应该根据数据库类型来附加@、?、:
            //2015-08-10,去掉了第一个"@",
            return(string.Concat("@", field.tableName, "_", field.Name, "_", GetNewParamCount()));

            //如遇Oracle超过30字符Bug,把field.tableName去掉即可
            //return string.Concat("@", field.Name, "_", GetNewParamCount());
            byte[] data = new byte[16];
            new RNGCryptoServiceProvider().GetBytes(data);
            string keystring = keyReg.Replace(Convert.ToBase64String(data).Trim(), string.Empty);

            if (keystring.Length > 16)
            {
                return(keystring.Substring(0, 16).ToLower());
            }

            return(keystring.ToLower());

            //return string.Concat(prefix, Guid.NewGuid().ToString().Replace("-", ""));
        }
Example #43
0
        } // End Function LoadHtml

        // Very good regex
        // http://stackoverflow.com/questions/10576686/c-sharp-regex-pattern-to-extract-urls-from-given-string-not-full-html-urls-but
        public static string Linkify(string text)
        {
            // http://en.wikipedia.org/wiki/URI_scheme

            System.Text.RegularExpressions.Regex linkParser =
                // new System.Text.RegularExpressions.Regex(@"\b(?:https?://|www\.)\S+\b"
                new System.Text.RegularExpressions.Regex(@"\b(?:(https?|ftp|ftps|sftp|chrome|cvs|data|dav|dns|facetime|fax|feed|file|finger|git|gtalk|gopher|imap|irc|irc6|ldaps?|magnet|mailto|mms|news|nfs|rsync|ssh|tftp):(//)?|www\.)\S+\b"
                                                         , System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase
                                                         );

            // foreach (System.Text.RegularExpressions.Match m in linkParser.Matches(text)) System.Console.WriteLine(m.Value);

            text = linkParser.Replace(text, new System.Text.RegularExpressions.MatchEvaluator(
                                          delegate(System.Text.RegularExpressions.Match m)
            {
                return("<a href=\"" + m.Value + "\">" + m.Value + "</a>");
            }
                                          )
                                      );

            System.Console.WriteLine(text);
            return(text);
        } // End Function Linkify
Example #44
0
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (identityLoaded == false)
            {
                Impersonation.ApplicationIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
                identityLoaded = true;
            }

            HttpRequest  request  = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            //Custom 301 Permanent Redirect for requests for the order Atom 0.3 feed
            if (oldAtom.IsMatch(request.Path))
            {
                if (request.RequestType == "GET")
                {
                    response.StatusCode       = 301;
                    response.Status           = "301 Moved Permanently";
                    response.RedirectLocation = oldAtom.Replace(request.Path, "SyndicationService.asmx");
                    response.End();
                }
            }
        }
        private void UpdateTrackBarLabel(TrackBar trackBar)
        {
            Control[] sr = trackBar.Parent.Controls.Find(string.Format("{0}_Label", trackBar.Name), true);
            if (sr == null || sr.Length != 1)
            {
                return;
            }

            Label l = sr[0] as Label;

            if (l == null)
            {
                return;
            }

            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(
                "\\(\\d*%\\)",
                System.Text.RegularExpressions.RegexOptions.CultureInvariant
                | System.Text.RegularExpressions.RegexOptions.Compiled
                );

            l.Text = re.Replace(l.Text, string.Format("({0}%)", trackBar.Value));
        }
Example #46
0
        public static string SendCommand(string command)
        {
            string address = GetEndpointAddress();
            string msg     = "";

            using (WebClient webclient = new WebClient()) {
                webclient.Encoding = System.Text.Encoding.UTF8;
                webclient.Headers[HttpRequestHeader.ContentType] = "application/json";

                if (!address.Contains("#"))
                {
                    msg = webclient.UploadString(address + Uri.EscapeUriString(command), String.Empty);
                }
                else
                {
                    var regex = new System.Text.RegularExpressions.Regex(System.Text.RegularExpressions.Regex.Escape("#"));
                    msg = webclient.UploadString(regex.Replace(address, Uri.EscapeUriString(command), 1), String.Empty);
                }
            }
            dynamic tmp = JsonConvert.DeserializeObject(msg);

            return(tmp.Result);
        }
Example #47
0
        private void _process_items(TreeNode root)
        {
            ItemSet items = _vcs.GetItems(root.FullPath, VersionSpec.Latest, RecursionType.OneLevel, DeletedState.Any, ItemType.Any);

            System.Text.RegularExpressions.Regex root_re =
                new System.Text.RegularExpressions.Regex("\\" + root.FullPath, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            foreach (Item item in items.Items)
            {
                /* need to do a case-insentive replace */
                //string path = item.ServerItem.Replace(root.FullPath, string.Empty);
                string path = root_re.Replace(item.ServerItem, string.Empty);
                if (path.Length > 0)
                {
                    if (path[0] == '/')
                    {
                        path = path.Substring(1);
                    }

                    if (path != string.Empty)
                    {
                        TreeNode node = root.Nodes.Add(path);
                        node.Tag = item;

                        if (item.DeletionId > 0)
                        {
                            node.ImageIndex = 1;
                        }
                        else
                        {
                            node.ImageIndex = 0;
                        }
                        node.Nodes.Add(new fooNode());
                    }
                }
            }
        }
Example #48
0
        /// <summary>
        /// Fix the standard CSS files to replace any fonts listed in badFonts with the defaultFont value.
        /// </summary>
        public static void FixCssReferencesForBadFonts(string cssFolderPath, string defaultFont, HashSet <string> badFonts)
        {
            // Note that the font may be referred to in defaultLangStyles.css, in customCollectionStyles.css, or in a style defined in the HTML.
            // This method handles the .css files.
            var defaultLangStyles = Path.Combine(cssFolderPath, "defaultLangStyles.css");

            if (RobustFile.Exists(defaultLangStyles))
            {
                var cssTextOrig = RobustFile.ReadAllText(defaultLangStyles);
                var cssText     = cssTextOrig;
                foreach (var font in badFonts)
                {
                    var cssRegex = new System.Text.RegularExpressions.Regex($"font-family:\\s*'?{font}'?;");
                    cssText = cssRegex.Replace(cssText, $"font-family: '{defaultFont}';");
                }
                if (cssText != cssTextOrig)
                {
                    RobustFile.WriteAllText(defaultLangStyles, cssText);
                }
            }
            var customCollectionStyles = Path.Combine(cssFolderPath, "customCollectionStyles.css");

            if (RobustFile.Exists(customCollectionStyles))
            {
                var cssTextOrig = RobustFile.ReadAllText(customCollectionStyles);
                var cssText     = cssTextOrig;
                foreach (var font in badFonts)
                {
                    var cssRegex = new System.Text.RegularExpressions.Regex($"font-family:\\s*'?{font}'?;");
                    cssText = cssRegex.Replace(cssText, $"font-family: '{defaultFont}';");
                }
                if (cssText != cssTextOrig)
                {
                    RobustFile.WriteAllText(customCollectionStyles, cssText);
                }
            }
        }
Example #49
0
        public override string RenderHtml()
        {
            if (Wrap)
            {
                var wrapper = new TagBuilder(_fieldWrapper);
                if (string.IsNullOrEmpty(this._cssClass))
                {
                    wrapper.Attributes["class"] = _fieldWrapperClass;
                }
                else
                {
                    //   wrapper.Attributes["class"] = this._cssClass;
                }


                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"(\r\n|\r|\n)+");

                string newText = regex.Replace(Html.Replace("  ", " &nbsp;"), "<br />");

                Html = MvcHtmlString.Create(newText).ToString();

                //wrapper.Attributes["ID"] = "labelmvcdynamicfield_" + Name.ToLower();
                wrapper.Attributes["ID"] = "mvcdynamicfield_" + Name.ToLower() + "_groupbox_fieldWrapper";

                StringBuilder StyleValues = new StringBuilder();

                StyleValues.Append(GetMobileLiteralStyle(_fontstyle.ToString(), null, null, null, null, IsHidden));
                //StyleValues.Append(";word-wrap:break-word;");

                // wrapper.Attributes.Add("data-role", "fieldcontain");
                wrapper.Attributes.Add(new KeyValuePair <string, string>("style", StyleValues.ToString()));

                wrapper.InnerHtml = Html;
                return(wrapper.ToString());
            }
            return(Html);
        }
        /// <summary>
        /// Return Error Messages
        /// </summary>
        /// <param name="errors"></param>
        /// <returns></returns>
        public static List <String> ReturnErrorMessages(IEnumerable errors)
        {
            var r = new System.Text.RegularExpressions.Regex(@"
                (?<=[A-Z])(?=[A-Z][a-z]) |
                 (?<=[^A-Z])(?=[A-Z]) |
                 (?<=[A-Za-z])(?=[^A-Za-z])", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);

            List <String> errorMessages = new List <String>();

            foreach (KeyValuePair <string, string[]> item in errors)
            {
                string errorMessage;

                string keyValue = item.Key;

                string[] objectProperty = keyValue.Split(Convert.ToChar("."));
                if (objectProperty.Length == 0)
                {
                    errorMessage = item.Value[0];
                }
                else
                {
                    errorMessage = objectProperty[1] + ": " + item.Value[0];
                    if (errorMessage.Contains(objectProperty[1]))
                    {
                        errorMessage = errorMessage.Replace(objectProperty[1], "");
                        errorMessage = objectProperty[1] + errorMessage;
                        errorMessage = errorMessage.Replace(" for ", "");
                    }
                }

                errorMessage = r.Replace(errorMessage, " ");
                errorMessage = errorMessage.Replace(" .", ".");
                errorMessages.Add(errorMessage);
            }
            return(errorMessages);
        }
Example #51
0
        /// <summary>
        /// Adds the text to RTB.
        /// </summary>
        /// <param name="richTextBox">The rich text box.</param>
        /// <param name="stackCard">The stack card.</param>
        /// <remarks>Documented by Dev08, 2009-05-12</remarks>
        private void AddTextToRTB(RichTextBox richTextBox, StackCard stackCard)
        {
            richTextBox.SuspendLayout();

            AnswerResult result = stackCard.Promoted ? AnswerResult.Correct : (stackCard.Result == AnswerResult.Almost ? AnswerResult.Almost : AnswerResult.Wrong);

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<[^>]*>");  //to replace html code if any
            bool questionRTL = stackCard.QuestionCulture.TextInfo.IsRightToLeft;
            bool answerRTL   = stackCard.AnswerCulture.TextInfo.IsRightToLeft;

            richTextBox.BackColor = StackCardBackColors.ContainsKey(result) ? StackCardBackColors[result] : SystemColors.Window;
            richTextBox.ForeColor = this.ForeColor;

            string text = Environment.NewLine;

            string questionRLE = (questionRTL ? Convert.ToString(Convert.ToChar(RLE)) : string.Empty);

            text += questionRLE + regex.Replace(stackCard.Question, String.Empty) + Environment.NewLine;
            text += questionRLE + regex.Replace(stackCard.QuestionExample, String.Empty) + Environment.NewLine;

            text += Environment.NewLine;

            string answerRLE = (answerRTL ? Convert.ToString(Convert.ToChar(RLE)) : string.Empty);

            if (stackCard.LearnMode == MLifter.BusinessLayer.LearnModes.Sentence && stackCard.AnswerExample.Length > 0)
            {
                text += answerRLE + regex.Replace(stackCard.AnswerExample, String.Empty) + Environment.NewLine;
                text += answerRLE + regex.Replace(stackCard.Answer, String.Empty) + Environment.NewLine;
            }
            else
            {
                text += answerRLE + regex.Replace(stackCard.Answer, String.Empty) + Environment.NewLine;
                text += answerRLE + regex.Replace(stackCard.AnswerExample, String.Empty) + Environment.NewLine;
            }
            richTextBox.Visible = true;
            richTextBox.Text    = text;
            richTextBox.Font    = this.Font;

            richTextBox.SelectAll();
            richTextBox.SelectionFont = this.Font;
            richTextBox.Select(0, 0);

            richTextBox.ResumeLayout();
        }
Example #52
0
        public void ImageHandler(ItemInfo itemInfo)
        {
            foreach (var item in itemInfo.ItemPropList)
            {
                System.Text.RegularExpressions.MatchCollection matches = null;

                //正则表达式获取<img src=>图片url
                if (item.IsEditor && item.PropertyCodeValue != "")
                {
                    matches = System.Text.RegularExpressions.Regex.Matches(item.PropertyCodeValue, @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                }

                if (matches != null && matches.Count > 0)
                {
                    foreach (System.Text.RegularExpressions.Match match in matches)
                    {
                        string imgTag = match.Value;

                        //去除已有的width
                        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("width=\"\\d+\"");
                        imgTag = r.Replace(imgTag, "", 10);

                        int srcStartIndex = match.Value.ToLower().IndexOf("src=\"");
                        int srcEndIndex   = match.Value.ToLower().IndexOf("\"", srcStartIndex + 5);

                        if (!(imgTag.IndexOf("width=\"100%\"") > 0))
                        {
                            //add width='100%'
                            imgTag = imgTag.Insert(srcEndIndex + 1, " width=\"100%\"");
                        }

                        item.PropertyCodeValue = item.PropertyCodeValue.Replace(match.Value, imgTag);
                    }
                }
            }
        }
Example #53
0
        public async Task <IActionResult> Results(RegisterViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(View("index", vm));
            }

            var searchstring = vm.SearchString?.Trim().ToLower();

            searchstring = string.IsNullOrEmpty(searchstring) ? "" : searchstring;
            var rx = new System.Text.RegularExpressions.Regex("<[^>]*>");

            searchstring = rx.Replace(searchstring, "");
            var searchResults = await _apiClient.SearchOrganisations(searchstring);

            var results           = searchResults ?? new List <AssessmentOrganisationSummary>();
            var registerViewModel = new RegisterViewModel
            {
                Results      = results,
                SearchString = vm.SearchString
            };

            return(View(registerViewModel));
        }
 private static string RemoveHTMLTags(string content)
 {
     var cleaned = string.Empty;
     string textOnly = string.Empty;
     System.Text.RegularExpressions.Regex tagRemove = new System.Text.RegularExpressions.Regex(@"<[^>]*(>|$)");
     System.Text.RegularExpressions.Regex compressSpaces = new System.Text.RegularExpressions.Regex(@"[\s\r\n]+");
     textOnly = tagRemove.Replace(content, " ").Trim();
     textOnly = compressSpaces.Replace(textOnly, " ");
     textOnly = System.Text.RegularExpressions.Regex.Replace(textOnly, @"<[^>]+>|&nbsp;", "").Trim();
     cleaned = textOnly;
     return cleaned;
 }
Example #55
0
        /// <summary>
        /// Processes the payment information.
        /// </summary>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ProcessPaymentInfo( out string errorMessage )
        {
            errorMessage = string.Empty;

            var errorMessages = new List<string>();

            // Validate that an amount was entered
            if ( SelectedAccounts.Sum( a => a.Amount ) <= 0 )
            {
                errorMessages.Add( "Make sure you've entered an amount for at least one account" );
            }

            // Validate that no negative amounts were entered
            if ( SelectedAccounts.Any( a => a.Amount < 0 ) )
            {
                errorMessages.Add( "Make sure the amount you've entered for each account is a positive amount" );
            }

            // Get the payment schedule
            PaymentSchedule schedule = GetSchedule();

            if ( schedule != null )
            {
                // Make sure a repeating payment starts in the future
                if ( schedule.StartDate <= RockDateTime.Today )
                {
                    errorMessages.Add( "When scheduling a repeating payment, make sure the First Gift date is in the future (after today)" );
                }
            }
            else
            {
                if ( dtpStartDate.SelectedDate < RockDateTime.Today )
                {
                    errorMessages.Add( "Make sure the date is not in the past" );
                }
            }

            if ( txtFirstName.Visible == true )
            {
                if ( string.IsNullOrWhiteSpace( txtFirstName.Text ) || string.IsNullOrWhiteSpace( txtLastName.Text ) )
                {
                    errorMessages.Add( "Make sure to enter both a first and last name" );
                }
            }

            bool displayPhone = GetAttributeValue( "DisplayPhone" ).AsBoolean();
            if ( displayPhone && string.IsNullOrWhiteSpace( pnbPhone.Number ) )
            {
                errorMessages.Add( "Make sure to enter a valid phone number.  A phone number is required for us to process this transaction" );
            }

            bool displayEmail = GetAttributeValue( "DisplayEmail" ).AsBoolean();
            if ( displayEmail && string.IsNullOrWhiteSpace( txtEmail.Text ) )
            {
                errorMessages.Add( "Make sure to enter a valid email address.  An email address is required for us to send you a payment confirmation" );
            }

            var location = new Location();
            acAddress.GetValues( location );
            if ( string.IsNullOrWhiteSpace( location.Street1 ) )
            {
                errorMessages.Add( "Make sure to enter a valid address.  An address is required for us to process this transaction" );
            }

            if ( !_using3StepGateway )
            {

                if ( rblSavedAccount.Items.Count <= 0 || ( rblSavedAccount.SelectedValueAsInt() ?? 0 ) <= 0 )
                {
                    bool isACHTxn = hfPaymentTab.Value == "ACH";
                    if ( isACHTxn )
                    {
                        // validate ach options
                        if ( string.IsNullOrWhiteSpace( txtRoutingNumber.Text ) )
                        {
                            errorMessages.Add( "Make sure to enter a valid routing number" );
                        }

                        if ( string.IsNullOrWhiteSpace( txtAccountNumber.Text ) )
                        {
                            errorMessages.Add( "Make sure to enter a valid account number" );
                        }
                    }
                    else
                    {
                        // validate cc options
                        if ( _ccGatewayComponent.PromptForNameOnCard( _ccGateway ) )
                        {
                            if ( _ccGatewayComponent != null && _ccGatewayComponent.SplitNameOnCard )
                            {
                                if ( string.IsNullOrWhiteSpace( txtCardFirstName.Text ) || string.IsNullOrWhiteSpace( txtCardLastName.Text ) )
                                {
                                    errorMessages.Add( "Make sure to enter a valid first and last name as it appears on your credit card" );
                                }
                            }
                            else
                            {
                                if ( string.IsNullOrWhiteSpace( txtCardName.Text ) )
                                {
                                    errorMessages.Add( "Make sure to enter a valid name as it appears on your credit card" );
                                }
                            }
                        }

                        var rgx = new System.Text.RegularExpressions.Regex( @"[^\d]" );
                        string ccNum = rgx.Replace( txtCreditCard.Text, "" );
                        if ( string.IsNullOrWhiteSpace( ccNum ) )
                        {
                            errorMessages.Add( "Make sure to enter a valid credit card number" );
                        }

                        var currentMonth = RockDateTime.Today;
                        currentMonth = new DateTime( currentMonth.Year, currentMonth.Month, 1 );
                        if ( !mypExpiration.SelectedDate.HasValue || mypExpiration.SelectedDate.Value.CompareTo( currentMonth ) < 0 )
                        {
                            errorMessages.Add( "Make sure to enter a valid credit card expiration date" );
                        }

                        if ( string.IsNullOrWhiteSpace( txtCVV.Text ) )
                        {
                            errorMessages.Add( "Make sure to enter a valid credit card security code" );
                        }
                    }
                }
            }

            if ( errorMessages.Any() )
            {
                errorMessage = errorMessages.AsDelimited( "<br/>" );
                return false;
            }

            PaymentInfo paymentInfo = GetPaymentInfo();

            if ( !phGiveAsOption.Visible || tglGiveAsOption.Checked )
            {
                if ( txtCurrentName.Visible )
                {
                    Person person = GetPerson( false );
                    if ( person != null )
                    {
                        paymentInfo.FirstName = person.FirstName;
                        paymentInfo.LastName = person.LastName;
                    }
                }
                else
                {
                    paymentInfo.FirstName = txtFirstName.Text;
                    paymentInfo.LastName = txtLastName.Text;
                }
            }
            else
            {
                paymentInfo.LastName = txtBusinessName.Text;
            }

            tdNameConfirm.Description = paymentInfo.FullName.Trim();
            tdPhoneConfirm.Description = paymentInfo.Phone;
            tdEmailConfirm.Description = paymentInfo.Email;
            tdAddressConfirm.Description = string.Format( "{0} {1}, {2} {3}", paymentInfo.Street1, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode );

            rptAccountListConfirmation.DataSource = SelectedAccounts.Where( a => a.Amount != 0 );
            rptAccountListConfirmation.DataBind();

            tdTotalConfirm.Description = paymentInfo.Amount.ToString( "C" );

            if ( !_using3StepGateway )
            {
                tdPaymentMethodConfirm.Description = paymentInfo.CurrencyTypeValue.Description;

                tdAccountNumberConfirm.Description = paymentInfo.MaskedNumber;
                tdAccountNumberConfirm.Visible = !string.IsNullOrWhiteSpace( paymentInfo.MaskedNumber );
            }

            tdWhenConfirm.Description = schedule != null ? schedule.ToString() : "Today";

            btnConfirmationPrev.Visible = !_using3StepGateway;

            return true;
        }
Example #56
0
 string spacefromname(string name)
 {
     name = name.Replace(DOTEXT,string.Empty);
     System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[.][0-9]+");
     return r.Replace(name, string.Empty);
 }
Example #57
0
 /// <summary>
 /// 清除UTF16的字符,范围 \uD800-\uDFFF
 /// </summary>
 /// <returns></returns>
 public static string RemoveUTF16Char(string text)
 {
     var regex = new System.Text.RegularExpressions.Regex(@"[^\u0000-\uD7FF\uE000-\uFFFF]");
         var content = regex.Replace(text, string.Empty);
         return content;
 }
Example #58
0
        public static string StripHtmlTags(string HTML)
        {
            // Removes tags from passed HTML
            System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex("<[^>]*>");

            return objRegEx.Replace(HTML, "");
        }
        private string FormatFolderString(string text)
        {
            if (text == null)
                return string.Empty;

            // remove accents
            System.Text.RegularExpressions.Regex nonSpacingMarkRegex = new System.Text.RegularExpressions.Regex(@"\p{Mn}", System.Text.RegularExpressions.RegexOptions.Compiled);
            var normalizedText = text.Normalize(System.Text.NormalizationForm.FormD);
            normalizedText = nonSpacingMarkRegex.Replace(normalizedText, string.Empty);

            // replace spaces for _
            normalizedText = normalizedText.Replace(" ", "_");

            normalizedText = normalizedText.Replace("\"", "");
            normalizedText = normalizedText.Replace("'", "");
            normalizedText = normalizedText.Replace("\\", "");
            normalizedText = normalizedText.Replace("/", "");

            return normalizedText;
        }
        internal static string NormalizePath(string path)
        {
            // remove leading single dot slash
            if (path.StartsWith(".\\")) path = path.Substring(2);

            // remove intervening dot-slash
            path = path.Replace("\\.\\", "\\");

            // remove double dot when preceded by a directory name
            var re = new System.Text.RegularExpressions.Regex(@"^(.*\\)?([^\\\.]+\\\.\.\\)(.+)$");
            path = re.Replace(path, "$1$3");
            return path;
        }