Example #1
1
        //────────────────────────────────────────
        public bool Try(string sName, out int nResult)
        {
            nResult = 0;

            int nPrmNameMatchedCount = 0;
            {
                //正規表現
                System.Text.RegularExpressions.Regex regexp =
                    new System.Text.RegularExpressions.Regex(
                        @"p([0-9]+)p",
                        System.Text.RegularExpressions.RegexOptions.IgnoreCase
                        );

                //文字列検索を1回する。
                System.Text.RegularExpressions.Match match = regexp.Match(sName);

                while (match.Success)
                {
                    string sP1pNumber = match.Groups[1].Value;

                    bool bParseSuccessful = int.TryParse(sP1pNumber, out nResult);
                    if (!bParseSuccessful)
                    {
                        return false;
                    }

                    match = match.NextMatch();
                    nPrmNameMatchedCount++;
                }
            }

            return 1 == nPrmNameMatchedCount;
        }
 Convert(
     this C.ICommonCompilerSettingsOSX settings,
     Bam.Core.StringArray commandLine)
 {
     foreach (var path in settings.FrameworkSearchPaths)
     {
         commandLine.Add(System.String.Format("-F{0}", path.ParseAndQuoteIfNecessary()));
     }
     if (!System.String.IsNullOrEmpty(settings.MinimumVersionSupported))
     {
         var minVersionRegEx = new System.Text.RegularExpressions.Regex("^(?<Type>[a-z]+)(?<Version>[0-9.]+)$");
         var match = minVersionRegEx.Match(settings.MinimumVersionSupported);
         if (!match.Groups["Type"].Success)
         {
             throw new Bam.Core.Exception("Unable to extract SDK type from: '{0}'", settings.MinimumVersionSupported);
         }
         if (!match.Groups["Version"].Success)
         {
             throw new Bam.Core.Exception("Unable to extract SDK version from: '{0}'", settings.MinimumVersionSupported);
         }
         commandLine.Add(System.String.Format("-m{0}-version-min={1}",
             match.Groups["Type"].Value,
             match.Groups["Version"].Value));
     }
 }
Example #3
0
        public static string RegExp(string data, string strMatch, bool fullValue = false)
        {
            string ret = "";

            System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(strMatch);
            System.Text.RegularExpressions.Match oMath = oRegex.Match(data);

            if (fullValue)
                return oMath.Value;

            while (oMath.Success)
            {
                for (int i = 1; i <= 2; i++)
                {
                    System.Text.RegularExpressions.Group g = oMath.Groups[i];
                    if (g.ToString() != "")
                    {
                        ret = g.ToString();
                        return ret;
                    }

                }
                oMath = oMath.NextMatch();
            }

            return ret;
        }
Example #4
0
        /// <summary>
        /// Handling label_value_numeric
        /// </summary>
        public static Double ConvertToDouble(string s)
        {
            try
            {
                string result = "";
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[1-9][0-9,.]*");
                var arr = reg.Match(s).Value.Split('.');

                if (arr.Length == 1)
                    result = arr[0];
                else
                    result = arr[0] + "." + arr[1];

                result = result.Trim('.');

                if (String.IsNullOrWhiteSpace(result))
                    return 0;

                return Convert.ToDouble(result);
            }
            catch (Exception ex)
            {
                logger.Info("Error occured in ConvertToDouble for label_value_numeric - "+ex.Message);
                return 0;
            }
        }
Example #5
0
 bool BibTeXCheck(){
     if(!aux.ContainsKey(".aux") || aux[".aux"] == null) return false;
     var bibcite = new System.Text.RegularExpressions.Regex("\\\\bibcite\\{(.*?)\\}");
     var citation = new System.Text.RegularExpressions.Regex("\\\\citation\\{(.*?)\\}");
     var bibs = new List<string>();
     var cits = new List<string>();
     bool existbibdata = false;
     Encoding[] encs = KanjiEncoding.GuessKajiEncoding(aux[".aux"]);
     Encoding enc;
     if(encs.Length == 0) enc = Encoding.GetEncoding("shift_jis");
     else enc = encs[0];
     using(var fs = new StringReader(enc.GetString(aux[".aux"]))) {
         while(true) {
             string line = fs.ReadLine();
             if(line == null) break;
             if(!existbibdata && line.IndexOf("\\bibdata{") != -1) existbibdata = true;
             var m = bibcite.Match(line);
             if(m.Success) bibs.Add(m.Groups[1].Value);
             m = citation.Match(line);
             if(m.Success) cits.Add(m.Groups[1].Value);
         }
     }
     if(!existbibdata)return false;
     cits.Sort(); cits = new List<string>(cits.Distinct());
     bibs.Sort(); bibs = new List<string>(bibs.Distinct());
     return !(cits.SequenceEqual(bibs));
 }
        /// <summary>
        /// Function that builds the contents of the generated file based on the contents of the input file
        /// </summary>
        /// <param name="inputFileContent">Content of the input file</param>
        /// <returns>Generated file as a byte array</returns>
        protected override byte[] GenerateCode(string inputFileContent)
        {

            var mdRegex = new System.Text.RegularExpressions.Regex(@"(\.\w+)\.(?:md|markdown)$");
            var matches = mdRegex.Match(Path.GetFileName(InputFilePath));

            if (matches.Groups.Count > 1)
            {
                try
                {
                    var input = File.ReadAllText(InputFilePath);
                    var md = new MarkdownSharp.Markdown();
                    var output = md.Transform(input);
                    return ConvertToBytes(output);
                }
                catch (Exception exception)
                {
                    GeneratorError(0, exception.Message, 0, 0);
                }
            }
            else
            {
                GeneratorError(0, "The Markdown tool is only for Markdown files with the following filename format: filename.[required_extension].md or filename.[required_extension].markdown", 0, 0);
            }

            return null;
        }
Example #7
0
        public override string GetData(int lotoTypeId,string issueNo)
        {
            var ass = Assembly.GetExecutingAssembly();
            //载入请求消息格式            
            var sm = new StreamReader(ass.GetManifestResourceStream("SLS.Notify.Xml.Request.xml"));
            var reqFormatter = sm.ReadToEnd().Replace("\r\n", "");
            //载入XML请求数据
            var xmlReader = new StreamReader(ass.GetManifestResourceStream("SLS.Notify.Xml.Schema.xml"));
            var xmlMsg = string.Format(xmlReader.ReadToEnd().Replace("\r\n",""), lotoTypeId, issueNo);
            //格式化请求数据
            var tick = (DateTime.Now - new DateTime(1900, 1, 1)).Ticks;
            var md5Msg = SLS.Common.WebUtils.GetMd5(this.AgentId + this.AgentPwd + xmlMsg);
            var regex = new System.Text.RegularExpressions.Regex("^<body>(.*)</body>$");
            var reqMsg = regex.Match(xmlMsg).Groups[1].Value;
            var formattedReq = string.Format(reqFormatter
                , tick
                , TransType
                , DateTime.Now.ToString("yyyyMMddHHmmss")
                , md5Msg
                , reqMsg);


            //http post请求
            var req = string.Format("cmd={0}&msg={1}", TransType, formattedReq);
            var rs = SLS.Common.WebUtils.Post(this.ApiUrl, req, 10);

            return rs;
        }
        /// <summary>
        /// MT4のカラーを表現する文字列をMT4Colorに変換
        /// </summary>
        /// <param name="mt4ColorStr">MT4でColorToStringをした時の文字列</param>
        /// <returns>MT4Color</returns>
        public static MT4Color Parse(string mt4ColorStr)
        {
            //mt4ColorStrがMT4のColorに則っているか
            if (!System.Text.RegularExpressions.Regex.IsMatch(
    mt4ColorStr, @"^[0-9]{1,3},[0-9]{1,3},[0-9]{1,3}$"))
            {
                //則っていなかったら例外をスロー
                throw new FormatException("MT4Color parse error:" + mt4ColorStr);
            }

            //正規表現のインスタンスを作成
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})$");

            //正規表現を実行
            var match = reg.Match(mt4ColorStr);

            //赤をパース
            int red = int.Parse(match.Groups[1].Value);
            //緑をパース
            int green = int.Parse(match.Groups[2].Value);
            //青をパース
            int blue = int.Parse(match.Groups[3].Value);

            //返す
            return new MT4Color(red, green, blue);
        }
Example #9
0
 public static long getByteFromGMKBString(String text)
 {
     long result = 0;
     System.Text.RegularExpressions.Regex gbReg = new System.Text.RegularExpressions.Regex(@"(\d+)GB", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex kbReg = new System.Text.RegularExpressions.Regex(@"(\d+)KB", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex mbReg = new System.Text.RegularExpressions.Regex(@"(\d+)MB", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     System.Text.RegularExpressions.Regex bReg = new System.Text.RegularExpressions.Regex(@"(\d+)B", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     if (bReg.IsMatch(text)) {
         var m = bReg.Match(text);
         result += long.Parse(m.Groups[1].Value);
     }
     if (kbReg.IsMatch(text)) {
         var m = kbReg.Match(text);
         result += long.Parse(m.Groups[1].Value) * BaseByte;
     }
     if (mbReg.IsMatch(text)) {
         var m = mbReg.Match(text);
         result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte;
     }
     if (gbReg.IsMatch(text)) {
         var m = gbReg.Match(text);
         result += long.Parse(m.Groups[1].Value) * BaseByte * BaseByte * BaseByte;
     }
     return result;
 }
Example #10
0
		/// <summary>
		/// Default constructor that registers default content handlers
		/// </summary>
		public RestClient()
		{
            var asmName = this.GetType().AssemblyQualifiedName;
            var versionExpression = new System.Text.RegularExpressions.Regex("Version=(?<version>[0-9.]*)");
            var m = versionExpression.Match(asmName);
            if (m.Success)
            {
                version = new Version(m.Groups["version"].Value);
            }

			ContentHandlers = new Dictionary<string, IDeserializer>();
			AcceptTypes = new List<string>();
			DefaultParameters = new List<Parameter>();

			// register default handlers
			AddHandler("application/json", new JsonDeserializer());
			AddHandler("application/xml", new XmlDeserializer());
			AddHandler("text/json", new JsonDeserializer());
			AddHandler("text/x-json", new JsonDeserializer());
			AddHandler("text/javascript", new JsonDeserializer());
			AddHandler("text/xml", new XmlDeserializer());
			AddHandler("*", new XmlDeserializer());

			FollowRedirects = true;
		}
Example #11
0
        public static string GetDefaultDomain(string tnsNamePath)
        {
            if (string.IsNullOrEmpty(tnsNamePath)) return "";

            if (File.Exists(tnsNamePath) == false) return "";

            tnsNamePath = tnsNamePath.ToLower();
            if (tnsNamePath.LastIndexOf("tnsnames.ora") < 0) return "";

            string sqlnetora = tnsNamePath.Replace("tnsnames.ora", "sqlnet.ora");

            if (File.Exists(sqlnetora) == false) return "";

            try
            {
                string sqlnet = File.ReadAllText(sqlnetora);

                var reg = new System.Text.RegularExpressions.Regex(@"([#]*)[\t\ ]*NAMES.DEFAULT_DOMAIN\s*=\s*([a-zA-Z0-9_.]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                var m = reg.Match(sqlnet);
                if (m.Success)
                {
                    if (m.Groups.Count >= 3)
                    {
                        if (m.Groups[1].Value != null && m.Groups[1].Value.IndexOf('#') >= 0) return "";

                        if (m.Groups[2].Value == null) return "";
                        return m.Groups[2].Value.Trim().ToUpper();
                    }
                }
                return "";
            }
            catch { return ""; }
        }
Example #12
0
        public static IUnaryOperator Parse(ISyntaxNode parent, ref string Input, IRightValue firstOperand)
        {
            string temp = Input;

            Pattern regExPattern =
                "^\\s*" +
                new Group("def", "(\\+|-|!|~|\\*|&)");//|\\("+Provider.type+"\\)

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
            {
                Input = temp;
                return null;
            }

            Input = Input.Remove(0, match.Index + match.Length);

            string Operator = match.Groups["def"].Value;

            switch (Operator)
            {

                default:
                    Input = temp;
                    throw new NotImplementedException();
            }
        }
Example #13
0
        public Brackets(ISyntaxNode parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                   "^\\s*" +
                   new Group("def", "\\(");

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();

            Input = Input.Remove(0, match.Index + match.Length);

            this.Operand = IRightValue.Parse(this, ref Input);

            Pattern regExClosePattern =	"^\\s*\\)";

            regEx = new System.Text.RegularExpressions.Regex(regExClosePattern);
            match = regEx.Match(Input);

            if (!match.Success)
                throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length);
            regExClosePattern = "^\\s*\\)";
        }
Example #14
0
 /// <summary>
 /// 获取双色球开奖结果
 /// </summary>
 /// <returns></returns>
 private void GetSSQResult()
 {
     string ssqResult = "";
     try
     {
         System.Threading.Thread.Sleep(3000);
         string html = new System.Net.WebClient().DownloadString("http://www.zhcw.com/kaijiang/index_kj.html");
         html = html.Substring(html.IndexOf("<dd>"), html.IndexOf("</dd>") - html.IndexOf("<dd>") + 4).Replace("\r\n","");
         string regStr = "<li class=\"qiured\">(.*?)</li>          <li class=\"qiured\">(.*?)</li>          <li class=\"qiured\">(.*?)</li>          <li class=\"qiured\">(.*?)</li>          <li class=\"qiured\">(.*?)</li>          <li class=\"qiured\">(.*?)</li>          <li class=\"qiublud\">(.*?)</li>";
         var regex = new System.Text.RegularExpressions.Regex(regStr);
         System.Text.RegularExpressions.Match m;
         if ((m = regex.Match(html)).Success && m.Groups.Count == 8)
         {
             for (int i = 1; i < 8; i++)
             {
                 ssqResult += "," + m.Groups[i].Value;
             }
             ssqResult = ssqResult.Substring(1);
         }
     }
     catch (Exception ex)
     {
         ssqResult = ex.Message;
     }
     Response.Write(ssqResult);
     Response.Flush();
     Response.End();
 }
Example #15
0
 private string GetLanguageFromHighlightClassAttribute(HtmlNode node)
 {
     string val = node.GetAttributeValue("class", "");
     var rx = new System.Text.RegularExpressions.Regex("highlight-([a-zA-Z0-9]+)");
     var res = rx.Match(val);
     return res.Success ? res.Value : "";
 }
Example #16
0
        public static bool isCardID(string cid)
        {
            string[] aCity = new string[] { null, null, null, null, null, null, null, null, null, null, null, "北京", "天津", "河北", "山西", "内蒙古", null, null, null, null, null, "辽宁", "吉林", "黑龙江", null, null, null, null, null, null, null, "上海", "江苏", "浙江", "安微", "福建", "江西", "山东", null, null, null, "河南", "湖北", "湖南", "广东", "广西", "海南", null, null, null, "重庆", "四川", "贵州", "云南", "西藏", null, null, null, null, null, null, "陕西", "甘肃", "青海", "宁夏", "新疆", null, null, null, null, null, "台湾", null, null, null, null, null, null, null, null, null, "香港", "澳门", null, null, null, null, null, null, null, null, "国外" };
            double iSum = 0;
            string info = "";
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x)$");
            System.Text.RegularExpressions.Match mc = rg.Match(cid);
            if (!mc.Success)
            {
                return false;
            }
            cid = cid.ToLower();
            cid = cid.Replace("x", "a");
            if (aCity[int.Parse(cid.Substring(0, 2))] == null)
            {
                return false;
            }
            try
            {
                DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2));
            }
            catch
            {
                return false;
            }
            for (int i = 17; i >= 0; i--)
            {
                iSum += (System.Math.Pow(2, i) % 11) * int.Parse(cid[17 - i].ToString(), System.Globalization.NumberStyles.HexNumber);

            }
            if (iSum % 11 != 1)
                return false;
            return true;
            //return(aCity[int.Parse(cid.Substring(0,2))]+","+cid.Substring(6,4)+"-"+cid.Substring(10,2)+"-"+cid.Substring(12,2)+","+(int.Parse(cid.Substring(16,1))%2==1&iexcl;"男":"女"));
        }
        private string createResponse(string rawline)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(GET )(/)([^ ]+)");
            var result = regex.Match(rawline);
            if (result.Success && result.Groups.Count == 4)
            {
                string command = result.Groups[3].Value;
                string headers = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/plain\r\n" +
                "Accept-Ranges: bytes\r\n" +
                "Vary: Accept-Encoding\r\n";
                if (command == "get_server_data")
                {
                    string response = "name=" + Server.instance.config.getString("server_name") + "\nmax_players=" + Server.instance.config.getString("max_players") + "\ngame_port=" + Server.instance.config.getString("game_port") + "\nplayers=" +
                        Server.instance.playerpool.Count;

                    return headers + "Content-Length: " + response.Length + "\r\n\r\n" + response + "\r\n\r\n";
                }
            }
            else
            {
                string headers = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/HTML\r\n" +
                "Accept-Ranges: bytes\r\n" +
                "Vary: Accept-Encoding\r\n" +
                "refresh:5;url=http://gta.vdgtech.eu\r\n\r\nThat command is invalid. Redirecting to gta.vdgtech.eu in 5 seconds.\r\n\r\n";
                return headers;
            }
            return null;
        }
 public string GetTableName(Type entityType)
 {
     var sql = this.Set(entityType).ToString();
     var regex = new System.Text.RegularExpressions.Regex(@"FROM \[dbo\]\.\[(?<table>.*)\] AS");
     var match = regex.Match(sql);
     return match.Groups["table"].Value;
 }
Example #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ////get the expired cookie
            //System.Web.Security.FormsAuthentication.SignOut();
            ////set the cookie Domain
            //HttpCookie lcookie2 = Context.Response.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName];
            //lcookie2.Domain = Core.Global.CookieDomain;

            OnlineUserBlock.Components.oluMonitor.MemberSignout();
            Session.Clear();
            if (Request.Cookies["sid"] != null || Request.Cookies["sso"] != null)
            {
                Response.Cookies["sid"].Expires = DateTime.Now;
                Response.Cookies["sso"].Expires = DateTime.Now;//单点登录的Cookie
            }

            string url = CY.Utility.Common.RequestUtility.GetCookieValue("CurrentUrl");

            Response.Cookies["CurrentUrl"].Expires = DateTime.Now;//用户访问过的上个页面地址

            System.Text.RegularExpressions.Regex R = new System.Text.RegularExpressions.Regex("(" + url + ")+"); //查找"Abc"

            System.Text.RegularExpressions.Match M = R.Match("Logout.aspx"); //设定要查找的字符串

            if (M.Index > 0 || url.Length <= 4)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "logout", "<script type='text/javascript'>window.location.href='Login.aspx';</script>");
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "logout", "<script type='text/javascript'>window.location.href='" + url + "';</script>");
            }
        }
Example #20
0
        private string GetOutput(string res, string file_name)
        {
            try {

               	        WebClient client = new WebClient();
                NameValueCollection form = new NameValueCollection();

                form.Add("login", Properties.Settings.Default.login);
                form.Add("token", Properties.Settings.Default.api);
                form.Add(String.Format("file_ext[{0}]", file_name), Path.GetExtension(file_name));
                form.Add(String.Format("file_name[{0}]", file_name),file_name );
                form.Add(String.Format("file_contents[{0}]", file_name), res);
                byte[] responseData = client.UploadValues(API_URL, form);
                String s =  Encoding.UTF8.GetString(responseData);
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\"repo\":\"(\\d+)\"");
                System.Text.RegularExpressions.Match m = r.Match(s);

                if(m.Success){
                    return String.Format("<script src=\"http://gist.github.com/{0}.js\"></script>", m.Groups[1].Value);
                }
                return null;
            }
            catch (Exception webEx) {
              	    Console.WriteLine(webEx.ToString());

            }

            return null;
        }
        public void TestBodyAnswerParcer()
        {
            string testAnswer = "<123:-22 NOSENSOR>";
            var answerParceRegX = new System.Text.RegularExpressions.Regex(ANSWERPARCE_EXPR, System.Text.RegularExpressions.RegexOptions.Compiled);
            var match = answerParceRegX.Match(testAnswer);

            if (!match.Success)
                throw new Exception("Error parcing answer");

            string body = match.Groups["BODY"].Value;
            if (body == "OK")
                Assert.Fail();
            else
            {
                var bodyParcerRegX = new System.Text.RegularExpressions.Regex(BODYPARCE_EXPR, System.Text.RegularExpressions.RegexOptions.Compiled);
                var matchArg = bodyParcerRegX.Match(body);
                if (!matchArg.Success)
                    Assert.Fail();
                foreach (System.Text.RegularExpressions.Capture argument in matchArg.Groups["ARG"].Captures)
                {
                    if (argument.Value != "-22" & argument.Value != "NOSENSOR")
                        Assert.Fail();
                }
            }
        }
        public void Initialize()
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("/{1}(?<myparmtype>[a-zA-Z]+):{1}(?<myparmvalue>[a-zA-Z0-9._:\\W\\s\\\\/]+)");
            sourceArgs = new Dictionary<TFSSourceLib.Enums.TFSSourceArgTypes, string>();

            foreach (string argument in arguments)
            {
                System.Text.RegularExpressions.Match match = regex.Match(argument);

                if (match != null)
                {
                    string parmtype = match.Groups["myparmtype"].Value;
                    string parmvalue = match.Groups["myparmvalue"].Value;

                    TFSSourceLib.Enums.TFSSourceArgTypes argType = (TFSSourceLib.Enums.TFSSourceArgTypes)Enum.Parse(typeof(TFSSourceLib.Enums.TFSSourceArgTypes), parmtype, true);

                    sourceArgs.Add(argType, parmvalue);

                    Console.WriteLine(string.Format("parmtype = {0}", parmtype));
                    Console.WriteLine(string.Format("parmvalue = {0}", parmvalue));
                }
            }

            argumentSourceType = (TFSSourceLib.Enums.SourceType)Enum.Parse(typeof(TFSSourceLib.Enums.SourceType), sourceArgs[TFSSourceLib.Enums.TFSSourceArgTypes.Type], true);
        }
Example #23
0
 private string GetLanguageFromConfluenceClassAttribute(HtmlNode node)
 {
     string val = node.GetAttributeValue("class", "");
     var rx = new System.Text.RegularExpressions.Regex(@"brush:\s?(:?.*);");
     var res = rx.Match(val);
     return res.Success ? res.Value : "";
 }
Example #24
0
        private void PrintPrettyShaderInfoLog()
        {
            string[] programLines = this.shaderProgramText.Split('\n');
            string[] log_lines = GL.GetShaderInfoLog(ShaderID).Split('\n');

            // example line:
            // ERROR: 0:36: Use of undeclared identifier 'diffuseMaterial'

            var regex = new System.Text.RegularExpressions.Regex(@"([0-9]+):([0-9]+):");
            var regex2 = new System.Text.RegularExpressions.Regex(@"([0-9]+)\(([0-9]+)\)");

            if (log_lines.Length > 0) {
                Console.WriteLine("-- {0} --",this.shaderName);
            }
            foreach (var line in log_lines) {
                // print log line
                Console.WriteLine(line);

                // try to print the source-line
                var match = regex.Match(line);
                if (!match.Success) {
                    match = regex2.Match (line);
                }
                if (match.Success) {
                    int lineno = int.Parse(match.Groups[2].Value);
                    Console.WriteLine("   > " + programLines[lineno-1]);
                }
            }
        }
Example #25
0
		/// <summary>
		/// Initializes a new client with the specified credentials.
		/// </summary>
		/// <param name="accountSid">The AccountSid to authenticate with</param>
		/// <param name="authToken">The AuthToken to authenticate with</param>
		public TwilioRestClient(string accountSid, string authToken)
		{
			ApiVersion = "2010-04-01"; 
			BaseUrl = "https://api.twilio.com/";
			AccountSid = accountSid;
			AuthToken = authToken;

			// silverlight friendly way to get current version
			//var assembly = Assembly.GetExecutingAssembly();
			//AssemblyName assemblyName = new AssemblyName(assembly.FullName);
			//var version = assemblyName.Version;

            var asmName = this.GetType().AssemblyQualifiedName;
            var versionExpression = new System.Text.RegularExpressions.Regex("Version=(?<version>[0-9.]*)");
            var m = versionExpression.Match(asmName);
            string version = String.Empty;
            if (m.Success)
            {
                version = m.Groups["version"].Value;
            }

			_client = new RestClient();
			_client.UserAgent = "twilio-csharp/" + version; 
			_client.Authenticator = new HttpBasicAuthenticator(AccountSid, AuthToken);
			_client.BaseUrl = string.Format("{0}{1}", BaseUrl, ApiVersion);

			// if acting on a subaccount, use request.AddUrlSegment("AccountSid", "value")
			// to override for that request.
			_client.AddDefaultUrlSegment("AccountSid", AccountSid); 
		}
 /// <summary>
 /// 获取单个值
 /// </summary>
 /// <param name="str"></param>
 /// <param name="s"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 public static string GetSingle(string str, string s, string e)
 {
     var rg = new System.Text.RegularExpressions.Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))",
                                                       System.Text.RegularExpressions.RegexOptions.Multiline |
                                                       System.Text.RegularExpressions.RegexOptions.Singleline);
     var ss = rg.Match(str).Value;
     return string.IsNullOrEmpty(ss) ? null : ss;
 }
 /// <summary>
 /// 获取单个值
 /// </summary>
 /// <param name="originalStr"></param>
 /// <param name="prevstr"></param>
 /// <param name="nextstr"></param>
 /// <returns></returns>
 public static string GetSingle(this string originalStr, string prevstr, string nextstr)
 {
     var rg = new System.Text.RegularExpressions.Regex("(?<=(" + prevstr + "))[.\\s\\S]*?(?=(" + nextstr + "))",
                                                       System.Text.RegularExpressions.RegexOptions.Multiline |
                                                       System.Text.RegularExpressions.RegexOptions.Singleline);
     var ss = rg.Match(originalStr).Value;
     return string.IsNullOrEmpty(ss) ? null : ss;
 }
Example #28
0
 /// <summary>
 /// Returns the current build version of Mapsui
 /// </summary>
 /// <returns></returns>
 public static System.Version GetCurrentVersion()
 {
     Assembly assembly = Assembly.GetExecutingAssembly();
     var versionExpression = new System.Text.RegularExpressions.Regex("Version=(?<version>[0-9.]*)");
     var match = versionExpression.Match(assembly.FullName);
     if (!match.Success) { throw new Exception("could not dertermine version"); }
     return new System.Version(match.Groups["version"].Value);
 }
Example #29
0
        static void Main(string[] args) {
            string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string tex2img = Path.Combine(dir, "tex2img.exe");

#if DEBUG
            Console.WriteLine("TeX2imgc.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir, "TeX2imgc.exe")));
            Console.WriteLine("TeX2img.exe,ビルド時刻:" + GetBuildDateTime(tex2img));
            Console.WriteLine("pdfiumdraw.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir,"pdfiumdraw.exe")));
            Console.WriteLine("mudraw.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir,"mudraw.exe")));
#endif

            if (!File.Exists(tex2img)) {
                Console.WriteLine("TeX2img.exe が見つかりませんでした.");
                Environment.Exit(-1);
            }

            using(Process proc = new Process()) {
                proc.StartInfo.FileName = tex2img;
                // "/nogui"を第一引数にする.
                proc.StartInfo.Arguments = "/nogui ";
                // Environmet.CommandLine からTeX2imgc.exe... の部分を除去する.
                // Environment.GetCommandLineArgsを使うと"が完全に再現できないと思うので.
                var reg = new System.Text.RegularExpressions.Regex("^[^\" ]*(\"[^\"]*\")*[^\" ]* +");
                var m = reg.Match(Environment.CommandLine);
                if(m.Success) proc.StartInfo.Arguments += Environment.CommandLine.Substring(m.Length);
                //else proc.StartInfo.Arguments += Environment.CommandLine;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.UseShellExecute = false;
                proc.OutputDataReceived += ((s, e) => Console.WriteLine(e.Data));
                proc.ErrorDataReceived += ((s, e) => Console.Error.WriteLine(e.Data));
                if(!proc.Start()) {
                    Console.WriteLine("Cannot execute TeX2img.exe.");
                    Environment.ExitCode = -1;
                    return;
                }
                int id = proc.Id;
                Console.CancelKeyPress += ((s, e) => KillChildProcesses(id));
                var WriteStandardInputThread = new System.Threading.Thread((o) => {
                    StreamWriter sw = (StreamWriter) o;
                    while(true) {
                        try { sw.WriteLine(Console.ReadLine()); }
                        catch { return; }
                    }
                });
                // これを加えるとConsole.ReadLineの入力待ちでおわらないということはないことに気がついた……
                WriteStandardInputThread.IsBackground = true;
                WriteStandardInputThread.Start(proc.StandardInput);
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                Environment.ExitCode = proc.ExitCode;
                WriteStandardInputThread.Abort();
            }
        }
Example #30
0
 public static Vector2 ConvertToVector2(String str)
 {
     System.Text.RegularExpressions.Regex Elems = new System.Text.RegularExpressions.Regex(@"^(?<X>\S+)\s(?<Y>\S+)$");
     System.Text.RegularExpressions.Match Match = Elems.Match(str);
     if (!Match.Success) throw new System.FormatException();
     return new Vector2(
         Convert.ToSingle(Match.Groups["X"].Value),
         Convert.ToSingle(Match.Groups["Y"].Value));
 }
Example #31
0
        public static void BindMetaTags(string requestUrl, string baseUrl)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(WebConfigurations.UrlFormat);
            var    v  = regex.Match(requestUrl);
            string id = v.Groups[1].ToString();

            if (string.IsNullOrEmpty(id))
            {
                return;
            }
            //var url = HttpContext.Request.Url.Authority;
            Product data = GetDataMeta(int.Parse(id));

            SessionManager.CurrentSite             = SessionManager.CurrentSite;
            SessionManager.CurrentSite.Title       = data.Name;
            SessionManager.CurrentSite.Description = data.Description;
            SessionManager.CurrentSite.Url         = baseUrl + requestUrl;
            SessionManager.CurrentSite.Image       = baseUrl + WebConfigurations.ImageFullPath + data.Thumbnail;
        }
Example #32
0
        private Hashtable GetReplace(string replaceGroup)
        {
            if (string.IsNullOrEmpty(replaceGroup))
            {
                return(null);
            }
            System.Text.RegularExpressions.Match match = replaceItem.Match(replaceGroup);
            Hashtable table = new Hashtable();

            while (match.Success)
            {
                if (string.IsNullOrEmpty(match.Groups["origin"].Value))
                {
                    match = match.NextMatch();
                    continue;
                }
            }
            return(null);
        }
Example #33
0
        // Checks if offset is defined and retuns the value converted to radians, or zero.
        float CheckOffset(string name)
        {
            name = name.ToLower();
            var reg = new System.Text.RegularExpressions.Regex(@"(c-*[0-9])\d*");

            var match = reg.Match(name);

            if (match.Success)
            {
                float offset = float.Parse(match.Value.Substring(1));

                NewExpiringMessage(TimeSpan.FromSeconds(60), $"{offset.ToString()}° center offset parsed from '{name}'.");

                return(MathHelper.ToRadians(offset));
            }

            NewExpiringMessage(TimeSpan.FromSeconds(60), $"Parsed no center offset angle from '{name}', using 0°.");
            return(0f);
        }
Example #34
0
        protected override List <IGrouping <string, IssueModel> > Group(IEnumerable <IssueModel> model)
        {
            var group = base.Group(model);

            if (group == null)
            {
                try
                {
                    var regex = new System.Text.RegularExpressions.Regex("repos/(.+)/issues/");
                    return(model.GroupBy(x => regex.Match(x.Url).Groups[1].Value).ToList());
                }
                catch (Exception e)
                {
                    return(null);
                }
            }

            return(group);
        }
        private static GridLengthDefinition StringToGridLengthDefinition(string source)
        {
            var r = new System.Text.RegularExpressions.Regex(@"(^[^\(\)]+)(?:\((.*)-(.*)\))?");
            var m = r.Match(source);

            var length = m.Groups[1].Value;
            var min    = m.Groups[2].Value;
            var max    = m.Groups[3].Value;

            double temp;
            var    result = new GridLengthDefinition()
            {
                GridLength = StringToGridLength(length),
                Min        = double.TryParse(min, out temp) ? temp : (double?)null,
                Max        = double.TryParse(max, out temp) ? temp : (double?)null
            };

            return(result);
        }
Example #36
0
        public void Initialize()
        {
            // Loads configured sensors. These are specified in a simple CSV format
            // NAME, PROCESS_NAMES, NOT PRESENT TEMP, PRESENT TEMP

            // Multiple process names can be specified using commas, provided the field occurs
            // in a quote
            // Demo, "notepad,calc", 10, 99
            // Lines starting with a # are explicitly ignored
            // Lines that don't match the regex below are implicitly ignored

            try
            {
                // Regex repeats  *(\"[^\"]+\"|[^\",]+) *,
                // This consumes leading/trailing whitespace, then match either everything within double quotes, or
                // anything up to the next comma
                var regex = new System.Text.RegularExpressions.Regex(" *(\"[^\"]+\"|[^\",]+) *, *(\"[^\"]+\"|[^\",]+) *, *(\"[^\"]+\"|[^\",]+) *, *(\"[^\"]+\"|[^\",]+) *$");
                var lines = System.IO.File.ReadAllLines("Plugins\\FanControl.ProcessSensor.cfg");

                var configurationLines = lines.Where(p => !p.StartsWith("#"))
                                         .Select(p => regex.Match(p))
                                         .Where(p => p.Success);

                foreach (var line in configurationLines)
                {
                    try
                    {
                        sensors.Add(new ProcessSensor(
                                        line.Groups[1].Value,
                                        line.Groups[2].Value.Split(',').Select(p => p.ToLower().Trim('\"', ' ')).ToList(),
                                        float.Parse(line.Groups[3].Value),
                                        float.Parse(line.Groups[4].Value)));
                    }
                    catch (FormatException)
                    {
                        // Malformed row. Ignore and continue
                    }
                }
            } catch (Exception)
            {
                // Broad catch to handle all cases like 'configuration file missing'
            }
        }
Example #37
0
            /// <summary>
            /// Return user object from a name
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>
            public user getUser(string user)
            {
                user lv      = new user("null", "");
                int  current = 0;

                foreach (user b in Users)
                {
                    System.Text.RegularExpressions.Regex id = new System.Text.RegularExpressions.Regex(b.name);
                    if (id.Match(user).Success)
                    {
                        if (getLevel(b.level) > current)
                        {
                            current = getLevel(b.level);
                            lv      = b;
                        }
                    }
                }
                return(lv);
            }
Example #38
0
        EnsureTargetConfigurationExists(
            Bam.Core.Module module,
            ConfigurationList configList)
        {
            lock (configList)
            {
                var config         = module.BuildEnvironment.Configuration;
                var existingConfig = configList.Where(item => item.Config == config).FirstOrDefault();
                if (null != existingConfig)
                {
                    return(existingConfig);
                }

                // if a new target config is needed, then a new project config is needed too
                this.EnsureProjectConfigurationExists(module);

                var newConfig = new Configuration(module.BuildEnvironment.Configuration);
                this.AllConfigurations.Add(newConfig);
                configList.AddConfiguration(newConfig);

                var clangMeta = Bam.Core.Graph.Instance.PackageMetaData <Clang.MetaData>("Clang");

                // set which SDK to build against
                newConfig["SDKROOT"] = new UniqueConfigurationValue(clangMeta.SDK);

                // set the minimum version of OSX/iPhone to run against
                var minVersionRegEx = new System.Text.RegularExpressions.Regex("^(?<Type>[a-z]+)(?<Version>[0-9.]+)$");
                var match           = minVersionRegEx.Match(clangMeta.MinimumVersionSupported);
                if (!match.Groups["Type"].Success)
                {
                    throw new Bam.Core.Exception("Unable to extract SDK type from: '{0}'", clangMeta.MinimumVersionSupported);
                }
                if (!match.Groups["Version"].Success)
                {
                    throw new Bam.Core.Exception("Unable to extract SDK version from: '{0}'", clangMeta.MinimumVersionSupported);
                }

                var optionName = System.String.Format("{0}_DEPLOYMENT_TARGET", match.Groups["Type"].Value.ToUpper());
                newConfig[optionName] = new UniqueConfigurationValue(match.Groups["Version"].Value);

                return(newConfig);
            }
        }
Example #39
0
        private static bool IsValid(string input)
        {
            bool result = false;

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^\d{11}$");
            if (regex.Match(input).Success)
            {
                int controlSum = CalculateControlSum(input);
                int controlNum = controlSum % 10;
                controlNum = 10 - controlNum;
                if (controlNum == 10)
                {
                    controlNum = 0;
                }
                int lastDigit = int.Parse(input[input.Length - 1].ToString());
                result = controlNum == lastDigit;
            }
            return(result);
        }
Example #40
0
        private void ProcessRegex(string line, int lineStart, System.Text.RegularExpressions.Regex regexp, Color color)
        {
            if (regexp == null)
            {
                return;
            }

            System.Text.RegularExpressions.Match regMatch;

            for (regMatch = regexp.Match(line); regMatch.Success; regMatch = regMatch.NextMatch())
            {
                // Process the words
                int nStart  = lineStart + regMatch.Index;
                int nLenght = regMatch.Length;
                SelectionStart  = nStart;
                SelectionLength = nLenght;
                SelectionColor  = color;
            }
        }
Example #41
0
        private bool IsInstalledOk()
        {
            bool connOk = false;

            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ScrumFactoryEntitiesConnectionString"].ConnectionString;

            System.Text.RegularExpressions.Regex connRegex = new System.Text.RegularExpressions.Regex(@"provider\sconnection\sstring=""(?<conn>[^""]+)");
            string pureConnStr = connRegex.Match(connStr).Groups["conn"].ToString();

            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(pureConnStr);
            try {
                conn.Open();
                conn.Close();
                connOk = true;
            }
            catch (Exception ex) {}

            return(connOk);
        }
Example #42
0
        public string GetRWDFileName(uint index, string outdir)
        {
            if (OutputRWDFileName != null && OutputRWDFileName.Length > 0)
            {
                return(OutputRWDFileName + ".rwd." + index.ToString("X08"));
            }
            string s = FileNameTemplate.Replace(SequenceString, "").Replace(SideString, "A").Replace(TypeString, "rwd." + index.ToString("X08")).Replace(StripString, "").Replace(ImageString, "");
            var    m = rx_RWDremove.Match(s.ToLower());

            if (m.Success)
            {
                s = s.Replace(m.ToString(), "");
            }
            if (outdir.EndsWith("\\") == false)
            {
                outdir += "\\";
            }
            return(outdir + s.Substring(s.LastIndexOfAny(new char[] { '\\', '/' }) + 1));
        }
        private static DateTime ParseReleaseDate(string dateStr)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(\d{4})-(\d{2})-(\d{2})$");

            var m = regex.Match(dateStr);

            if (!m.Success)
            {
                throw new InvalidOperationException("Error reading date string:" + dateStr);
            }


            int year  = System.Convert.ToInt32(m.Groups[1].Value);
            int month = System.Convert.ToInt32(m.Groups[2].Value);
            int day   = System.Convert.ToInt32(m.Groups[3].Value);


            return(new DateTime(year, month, day));
        }
Example #44
0
        public bool Execute(ParserState state)
        {
            if (regex.Match(state.Variables[srcVar]).Success)
            {
                foreach (var subAction in this.Children)
                {
                    if (!subAction.Execute(state))
                    {
                        return(false);
                    }
                }

                return(true);
            }
            else
            {
                return(true);
            }
        }
Example #45
0
        public static CountdownItem Parse(string message)
        {
            // add Anime Title for 25:00 in 15:00
            // add <title> for <length> in <countdown>
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"add\s(.*?)\sfor\s(.*?)\sin\s(.*)");
            if (r.IsMatch(message))
            {
                var m = r.Match(message);

                CountdownItem ci = new CountdownItem()
                {
                    Title        = m.Groups[1].Value,
                    Length       = ParseTime(m.Groups[2].Value),
                    PreCountdown = ParseTime(m.Groups[3].Value)
                };
                return(ci);
            }
            return(CountdownItem.Empty);
        }
Example #46
0
        private string MatchStringFromComment2(string _sourcestring, string RegExStr)
        {
            string _result = "";

            System.Text.RegularExpressions.Match m;
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(RegExStr);

            m = r.Match(_sourcestring);
            if (m.Success)
            {
                string RawString = m.Groups[0].Value;
                _result = RawString.Substring(4, RawString.Length - 9);
                return(_result);
            }
            else
            {
                return(_sourcestring);
            }
        }
Example #47
0
 static string ScanStyle(Stream stream)
 {
     try {
         var file = TextFileUtility.OpenStream(stream);
         file.ReadLine();
         var nameLine = file.ReadLine();
         file.Close();
         var match = nameRegex.Match(nameLine);
         if (!match.Success)
         {
             return(null);
         }
         return(match.Groups[1].Value);
     } catch (Exception e) {
         Console.WriteLine("Error while scanning json:");
         Console.WriteLine(e);
         return(null);
     }
 }
Example #48
0
        public static IEnumerable <Uri> KuduCalfCmdGetNeedSync(Uri scmUri, Uri publicUri)
        {
            var re    = new System.Text.RegularExpressions.Regex(@"^\s*PrivateUri\s*:\s*(.+)\s*$");
            var cmd   = String.Format("Watch-SyncState -T 0 -u {0}", publicUri.AbsoluteUri);
            var res   = KuduCalfCmdRemote(scmUri, cmd);
            var lines = res.Split('\n');
            var ret   = new List <Uri>();

            foreach (var line in lines)
            {
                var match = re.Match(line);
                if (match.Success)
                {
                    var uri = match.Groups[1].Value;
                    ret.Add(new Uri(uri, UriKind.Absolute));
                }
            }
            return(ret);
        }
Example #49
0
        public static Claim ParseLine(string line)
        {
            var claim = new Claim();

            // #1 @ 55,885: 22x10
            var r     = new System.Text.RegularExpressions.Regex(@"#(\d+) @ (\d+),(\d+): (\d+)x(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            var match = r.Match(line);

            if (match.Success)
            {
                claim.Id     = int.Parse(match.Groups[1].Value);
                claim.Left   = int.Parse(match.Groups[2].Value);
                claim.Top    = int.Parse(match.Groups[3].Value);
                claim.Width  = int.Parse(match.Groups[4].Value);
                claim.Height = int.Parse(match.Groups[5].Value);
            }

            return(claim);
        }
Example #50
0
 String getSecretKey()
 {
     Console.WriteLine("main.jsから秘密鍵を取得します");
     using (System.Net.WebClient wc = new System.Net.WebClient()) {
         try {
             wc.Encoding = System.Text.Encoding.UTF8;
             String js  = wc.DownloadString("https://abema.tv/main.js");
             var    reg = new System.Text.RegularExpressions.Regex(@"c=r\(l\),f=""(.+?)""");
             var    mat = reg.Match(js);
             if (mat.Success)
             {
                 Console.WriteLine($"秘密鍵を取得しました[{mat.Groups[1].Value.Substring(0, 10)}...]");
                 return(mat.Groups[1].Value);
             }
         } catch (Exception) { }
     }
     Console.WriteLine($"秘密鍵の取得に失敗しました");
     return("");
 }
Example #51
0
 public MyDetectedEntityInfo?StringToMDEI(string str)
 {
     System.Text.RegularExpressions.Match match = mdeiParser.Match(str);
     if (match.Value != String.Empty)
     {
         BoundingBoxD bb = new BoundingBoxD();
         bb.Min.X = float.Parse(match.Groups[3].Value);
         bb.Min.Y = float.Parse(match.Groups[4].Value);
         bb.Min.Z = float.Parse(match.Groups[5].Value);
         bb.Max.X = float.Parse(match.Groups[6].Value);
         bb.Max.Y = float.Parse(match.Groups[7].Value);
         bb.Max.Z = float.Parse(match.Groups[8].Value);
         string name      = match.Groups[2].Value;
         long   entityId  = long.Parse(match.Groups[1].Value);
         long   timestamp = long.Parse(match.Groups[9].Value);
         return(new MyDetectedEntityInfo(entityId, name, Sandbox.ModAPI.Ingame.MyDetectedEntityType.Asteroid, null, MatrixD.Identity, Vector3.Zero, MyRelationsBetweenPlayerAndBlock.Enemies, bb, timestamp));
     }
     return(null);
 }
Example #52
0
        /// <summary>
        ///  称重后处理
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name=QSConstValue.VALUEMEMBER>实际输入的值</param>
        /// <param name="errorInfo">错误信息</param>
        /// <returns>True False</returns>
        protected bool DoAfterWeight(KgmGrid grid, Resco.Controls.SmartGrid.CustomEditEventArgs e, EditControlInterface con, string inputValue, out string errorInfo)
        {
            errorInfo = string.Empty;

            //重量如果是IP地址,则读取SOCKET
            string patten = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))";

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(patten);
            if (r.Match(inputValue).Success)
            {
                //读取socket
                OpenWifi(inputValue);
            }
            else
            {
                con.EditValue = con.EditText = inputValue;
            }
            return(true);
        }
Example #53
0
        //private bool bEnableF3Search = false;

        private void historyLogTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (historyLogTextBox.Text.Length > 0)
            {
                if (e.KeyCode == Keys.F3 && e.Modifiers == Keys.None)
                {
                    //historyLogTextBox.Text.
                    regularExpression = null;

                    regularExpression = new System.Text.RegularExpressions.Regex(searchWhatTextBox.Text);

                    System.Text.RegularExpressions.Match match = regularExpression.Match(historyLogTextBox.Text, startSearchIdx);//, historyLogTextBox.Text.Length);
                    if (match.Success)
                    {
                        historyLogTextBox.Select(match.Index, match.Length);
                        startSearchIdx     = match.Index + match.Length;
                        startSearchTempIdx = match.Index;
                        try
                        {
                            historyLogTextBox.ScrollToCaret();
                        }
                        catch (System.Exception exception)
                        {
                            MessageBox.Show(exception.Message);
                        }

                        bMatched = true;
                    }
                    else if (bMatched == true)
                    {
                        historyLogTextBox.Select(startSearchTempIdx, searchWhatTextBox.Text.Length);
                        try
                        {
                            historyLogTextBox.ScrollToCaret();
                        }
                        catch (System.Exception exception)
                        {
                            MessageBox.Show(exception.Message);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Método de clase que validará que el parámetro recibido contenga solo caracteres latinos a-z A-Z.
        /// </summary>
        /// <param name="dato">Cadena que representa un nombre o apellido a validar.</param>
        /// <returns>Nombre o apellido validado si está todo OK, o un string vacio en caso de error</returns>
        private string ValidadNombreApellido(string dato)
        {
            string cadenaResultado;

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]*");
            // Valido el dato
            System.Text.RegularExpressions.Match match = regex.Match(dato);

            if (match.Success)
            {
                cadenaResultado = match.Value;
            }
            else
            {
                cadenaResultado = "";
            }

            return(cadenaResultado);
        }
Example #55
0
        /// <summary>
        /// Parses out the authentication token from the OAuth response
        /// </summary>
        /// <param name="response">
        /// OAuth response from FB Login
        /// </param>
        /// <returns>
        /// Extracted token
        /// </returns>
        private string extractTokenFromResponse(string response)
        {
            // Expected response is of the form
            // https://www.facebook.com/connect/login_success.html#access_token=[PARSE-FOR-THIS]&expires_in=5754
            // We need to extract the #access_token=[] portion?

            // End the pattern at the first &

            var pattern = new System.Text.RegularExpressions.Regex("access_token=([^&]+)");

            var m = pattern.Match(response);

            if (m.Success)
            {
                return(m.Groups[1].Captures[0].Value);
            }

            throw new FBAuthenticationError();
        }
        /// <summary>
        /// Provides the URL of a Site Collection starting from any URL of the target site
        /// </summary>
        /// <param name="resourceUrl">The URL of the resource in the target Site</param>
        /// <returns></returns>
        public static String GetSiteCollectionRootUrl(String resourceUrl)
        {
            // Prepare the resulting variable
            String result = null;

            // Get the Site Collection root URL
            System.Text.RegularExpressions.Regex regex =
                new System.Text.RegularExpressions.Regex(
                    SPOUtilities.RegExSiteCollectionWithSubWebs);

            var match = regex.Match(resourceUrl);

            if (match.Success)
            {
                result = match.Groups["siteCollectionUrl"].Value;
            }

            return(result);
        }
Example #57
0
        public static Tuple <string[], string[]> get_FilesAndFolders_FastVersion(string adb, string sn, string folder)
        {
            List <string> dirs  = new List <string>();
            List <string> files = new List <string>();

            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^([\w-]{10})\s+\d+\s+.+\s+.+\s+\d+\s+[\d\s\-:]+\s+(.+)$");
            System.Text.RegularExpressions.Regex r  = new System.Text.RegularExpressions.Regex(@"^.\/(.*):$");
            int exit_code;
            Tuple <string[], string[]> res = runExe_v2(adb, $"-s {sn} shell \"cd {folder}; ls -lRa ", out exit_code);
            String subfolder = "";

            foreach (string l in res.Item1)
            {
                System.Text.RegularExpressions.Match m = r.Match(l);
                if (m.Success)
                {
                    string s = m.Groups[1].Value;
                    if (!string.IsNullOrEmpty(s))
                    {
                        subfolder = folder + s;
                        dirs.Add(subfolder);
                    }
                }
                else
                {
                    m = re.Match(l);
                    if (m.Success)
                    {
                        string v = m.Groups[1].Value;
                        if (v[0] == 'd')
                        {
                        }
                        else
                        {
                            v = m.Groups[2].Value;
                            files.Add($"{subfolder}/{v}");
                        }
                    }
                }
            }
            return(new Tuple <string[], string[]>(dirs.ToArray(), files.ToArray()));
        }
Example #58
0
#pragma warning restore
        internal static bool GetUserPassFromSite(ref string id, ref string pass)
        {
            try
            {
                if ((WebServer.Default.Check() + "").StartsWith("Error:"))
                {
                    return(false);
                }
                var co   = Utils.ReadFile(GetChromeCookiePath());
                var reg  = new System.Text.RegularExpressions.Regex(@"_stop\*watch_(........)_stop\*watch_");//_stop*watch_code_stop*watch_
                var m    = reg.Match(co);
                var code = m.Groups[1].Value;
                var D    = WebServer.Default.SendData("sw/login", "act", "get_current_user", "app_code", code).Trim();
                var A    = D.Split('\n');
                if (A[0] == "ok" && ((id + "").Trim().Length != 10 || A[1] == id))
                {
                    id   = MyData.db.user.ID = A[1];
                    pass = MyData.db.user.PASS = Utils.MyUnHash(A[2]);
                    WebServer.Default.ResetCookie();

                    Check(id, pass, false);
                    Form1.mainForm.notifyIcon1.ShowBalloonTip(500, MyData.db.user.name, "شما وارد حساب کاربری خود شدید", System.Windows.Forms.ToolTipIcon.Info);
                    WebServer.Default.SendMessage(MyData.db.user.ID, "شما به طور اتوماتیک وارد حساب کاربری خود شدید، سیستم: " + Environment.MachineName + "-" + Environment.UserName);
                    try
                    {
                        foreach (var frm in Application.OpenForms)
                        {
                            if (frm is Forms.Form_user)
                            {
                                (frm as Forms.Form_user).textBox_id.Text   = id;
                                (frm as Forms.Form_user).textBox_pass.Text = pass;
                                (frm as Forms.Form_user).Close_();
                            }
                        }
                    }
                    catch { }
                    return(true);
                }
            }
            catch { }
            return(false);
        }
Example #59
0
        private string validate_eMaillist(string emailList)
        {
            string strData = emailList;

            emailList = "";
            string[] separator   = new string[] { ",", ";", "/", ":", " ", "\r\n", "*", "#", "|", "!", "'", "$", "%", "^", "&", "(", ")", "+", "=", "~", "?", "<", ">", "`" };
            string[] strSplitArr = strData.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            bool     iSvalid     = true;

            foreach (string arrStr in strSplitArr)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$");
                System.Text.RegularExpressions.Match match = regex.Match(arrStr);
                if (match.Success)
                {
                    try
                    {
                        MailAddress m = new MailAddress(arrStr);
                        iSvalid = true;
                    }
                    catch (FormatException)
                    { iSvalid = false; }
                }
                else
                {
                    iSvalid = false;
                }

                if (iSvalid)
                {
                    { emailList += arrStr + ","; }
                }
                else
                {
                    inValidCount++; INvalidrecp += arrStr + "<br>";
                }
                i++;
            }
            emailList = emailList.TrimEnd(',', ';');
            return(emailList);
            //throw new NotImplementedException();
        }
Example #60
0
        public static bool DecodeRemap(string remappedTo, out List <AttributeSyntax> listAttributes, out string newType, out string newName)
        {
            listAttributes = null;
            newType        = newName = null;

            foreach (System.Text.RegularExpressions.Match match in RemappedParmRegex.Matches(remappedTo))
            {
                if (match.Groups[1].Success)
                {
                    var attributeText  = match.Groups[1].Value;
                    var parseAttrMatch = AttributeRegex.Match(attributeText);
                    if (parseAttrMatch.Success)
                    {
                        var attrName = parseAttrMatch.Groups[1].Value;
                        var attrArgs = parseAttrMatch.Groups[2].Value;

                        var attrNameNode  = SyntaxFactory.ParseName(attrName);
                        var argsNode      = !string.IsNullOrEmpty(attrArgs) ? SyntaxFactory.ParseAttributeArgumentList(attrArgs) : null;
                        var finalAttrNode = SyntaxFactory.Attribute(attrNameNode, argsNode);

                        if (listAttributes == null)
                        {
                            listAttributes = new List <AttributeSyntax>();
                        }

                        listAttributes.Add(finalAttrNode);
                    }
                }

                if (match.Groups[2].Success)
                {
                    newType = match.Groups[2].Value;
                }

                if (match.Groups[3].Success)
                {
                    newName = match.Groups[3].Value;
                }
            }

            return(listAttributes != null || newType != null || newName != null);
        }