Beispiel #1
0
		internal Group () : base ("")
		{
			success = false;
			captures = new CaptureCollection (0);
		}
Beispiel #2
0
        public ArgInfo(String a)
        {
            Match m = _exPath.Match(a);

            if (!m.Success)
            {
                throw new ApplicationException(String.Format("Unrecognized path '{0}'.", a));
            }

            _arg = a;

            if (a.EndsWith("\\") || a.EndsWith(":"))
            {
                _pathTarget = TargetType.Dir;
            }
            else if (a.Length > 0)
            {
                _pathTarget = TargetType.FileOrDir;
            }


            if (_pathTarget != TargetType.Empty)
            {
                if (m.Groups["drive"].Success)
                {
                    _drive = m.Groups["drive"].Value.Substring(0, 1);
                }

                CaptureCollection capts = m.Groups["path"].Captures;
                if (capts.Count > 0)
                {
                    Boolean       isRooted = false;
                    List <String> tmpSteps = new List <String>();
                    for (Int32 i = 0; i < capts.Count; ++i)
                    {
                        String c = capts[i].Value;
                        if (i == 0 && c.StartsWith("\\"))
                        {
                            isRooted = true;
                        }

                        c = c.Replace("\\", String.Empty);
                        if (c.Length > 0)
                        {
                            if (!_exPathStep.IsMatch(c))
                            {
                                throw new ApplicationException(String.Format("File or directory doesn't match to the 8.3 pattern: '{0}'.", c));
                            }
                            tmpSteps.Add(c);
                        }
                    }

                    if (tmpSteps.Count > 0)
                    {
                        _locationSteps = tmpSteps.ToArray();
                    }

                    if (isRooted)
                    {
                        _relativity = _drive.Length > 0 ? PathType.RelativeToDriveRoot:PathType.RelativeToRoot;
                    }
                    else
                    {
                        _relativity = _drive.Length > 0 ? PathType.RelativeToDriveDir:PathType.RelativeToDir;
                    }
                }

                if (_locationSteps.Length == 0 && _drive.Length > 0)
                {
                    _relativity = PathType.RelativeToDriveRoot; //correct 'C:' to 'C:\'
                }
            }
        }
            /// <summary>
            /// Converts a stack trace to formatted HTML with styling and linkifiation.
            /// </summary>
            /// <param name="stackTrace">The stack trace to HTMLify.</param>
            /// <param name="settings">The <see cref="StackTraceSettings"/> to use in this render.</param>
            /// <returns>An HTML-pretty version of the stack trace.</returns>
            public static string HtmlPrettify(string stackTrace, StackTraceSettings settings)
            {
                string GetBetween(Capture prev, Capture next) =>
                stackTrace.Substring(prev.Index + prev.Length, next.Index - (prev.Index + prev.Length));

                int pos     = 0;
                var sb      = StringBuilderCache.Get();
                var matches = _regex.Matches(stackTrace);

                for (var mi = 0; mi < matches.Count; mi++)
                {
                    Match m                      = matches[mi];
                    Group leadIn                 = m.Groups[Groups.LeadIn],
                          frame                  = m.Groups[Groups.Frame],
                          type                   = m.Groups[Groups.Type],
                          asyncMethod            = m.Groups[Groups.AsyncMethod],
                          method                 = m.Groups[Groups.Method],
                          allParams              = m.Groups[Groups.Params],
                          sourceInfo             = m.Groups[Groups.SourceInfo],
                          path                   = m.Groups[Groups.Path],
                          linePrefix             = m.Groups[Groups.LinePrefix],
                          line                   = m.Groups[Groups.Line];
                    CaptureCollection paramTypes = m.Groups[Groups.ParamType].Captures,
                                      paramNames = m.Groups[Groups.ParamName].Captures;
                    bool nextIsAsync             = false;
                    if (mi < matches.Count - 1)
                    {
                        Group nextFrame = matches[mi + 1].Groups[Groups.Frame];
                        nextIsAsync = _asyncFrames.Contains(nextFrame.Value);
                    }

                    var isAsync = _asyncFrames.Contains(frame.Value);

                    // The initial message may be above an async frame
                    if (sb.Length == 0 && isAsync && leadIn.Index > pos)
                    {
                        sb.Append("<span class=\"stack stack-row\">")
                        .Append("<span class=\"stack misc\">")
                        .AppendHtmlEncode(stackTrace.Substring(pos, leadIn.Index - pos).Trim(NewLine_CarriageReturn))
                        .Append("</span>")
                        .Append("</span>");
                        pos += sb.Length;
                    }

                    sb.Append(isAsync ? "<span class=\"stack stack-row async\">" : "<span class=\"stack stack-row\">");

                    if (leadIn.Index > pos)
                    {
                        var miscContent = stackTrace.Substring(pos, leadIn.Index - pos);
                        if (miscContent.Contains(EndStack))
                        {
                            // Handle end-of-stack removals and redundant multilines remaining
                            miscContent = miscContent.Replace(EndStack, "")
                                          .Replace("\r\n\r\n", "\r\n")
                                          .Replace("\n\n", "\n\n");
                        }

                        sb.Append("<span class=\"stack misc\">")
                        .AppendHtmlEncode(miscContent)
                        .Append("</span>");
                    }
                    sb.Append("<span class=\"stack leadin\">")
                    .AppendHtmlEncode(leadIn.Value)
                    .Append("</span>");

                    // Check if the next line is the end of an async hand-off
                    var nextEndStack = stackTrace.IndexOf(EndStack, m.Index + m.Length);
                    if ((nextEndStack > -1 && nextEndStack < m.Index + m.Length + 3) || (!isAsync && nextIsAsync))
                    {
                        sb.Append("<span class=\"stack async-tag\">async</span> ");
                    }

                    if (asyncMethod.Success)
                    {
                        sb.Append("<span class=\"stack type\">")
                        .AppendGenerics(GetBetween(leadIn, asyncMethod), settings)
                        .Append("</span>")
                        .Append("<span class=\"stack method\">")
                        .AppendHtmlEncode(asyncMethod.Value)
                        .Append("</span>")
                        .Append("<span class=\"stack type\">")
                        .AppendGenerics(GetBetween(asyncMethod, method), settings);
                        sb.Append("</span>");
                    }
                    else
                    {
                        sb.Append("<span class=\"stack type\">")
                        .AppendGenerics(type.Value, settings)
                        .Append("<span class=\"stack dot\">")
                        .AppendHtmlEncode(GetBetween(type, method))   // "."
                        .Append("</span>")
                        .Append("</span>");
                    }
                    sb.Append("<span class=\"stack method-section\">")
                    .Append("<span class=\"stack method\">")
                    .AppendHtmlEncode(NormalizeMethodName(method.Value))
                    .Append("</span>");

                    if (paramTypes.Count > 0)
                    {
                        sb.Append("<span class=\"stack parens\">")
                        .Append(GetBetween(method, paramTypes[0]))
                        .Append("</span>");
                        for (var i = 0; i < paramTypes.Count; i++)
                        {
                            if (i > 0)
                            {
                                sb.Append("<span class=\"stack misc\">")
                                .AppendHtmlEncode(GetBetween(paramNames[i - 1], paramTypes[i]))   // ", "
                                .Append("</span>");
                            }
                            sb.Append("<span class=\"stack paramType\">")
                            .AppendGenerics(paramTypes[i].Value, settings)
                            .Append("</span>")
                            .AppendHtmlEncode(GetBetween(paramTypes[i], paramNames[i]))   // " "
                            .Append("<span class=\"stack paramName\">")
                            .AppendHtmlEncode(paramNames[i].Value)
                            .Append("</span>");
                        }
                        var last = paramNames[paramTypes.Count - 1];
                        sb.Append("<span class=\"stack parens\">")
                        .AppendHtmlEncode(allParams.Value.Substring(last.Index + last.Length - allParams.Index))
                        .Append("</span>");
                    }
                    else
                    {
                        sb.Append("<span class=\"stack parens\">")
                        .AppendHtmlEncode(allParams.Value)   // "()"
                        .Append("</span>");
                    }
                    sb.Append("</span>"); // method-section for table layout

                    if (sourceInfo.Value.HasValue())
                    {
                        sb.Append("<span class=\"stack source-section\">");

                        var curPath = sourceInfo.Value;
                        if (settings.LinkReplacements.Count > 0)
                        {
                            foreach (var replacement in settings.LinkReplacements)
                            {
                                curPath = replacement.Key.Replace(curPath, replacement.Value);
                            }
                        }

                        if (curPath != sourceInfo.Value)
                        {
                            sb.Append("<span class=\"stack misc\">")
                            .AppendHtmlEncode(GetBetween(allParams, sourceInfo))
                            .Append("</span>")
                            .Append(curPath);
                        }
                        else if (path.Value.HasValue())
                        {
                            var subPath = GetSubPath(path.Value, type.Value);

                            sb.Append("<span class=\"stack misc\">")
                            .AppendHtmlEncode(GetBetween(allParams, path))
                            .Append("</span>")
                            .Append("<span class=\"stack path\">")
                            .AppendHtmlEncode(subPath)
                            .Append("</span>")
                            .AppendHtmlEncode(GetBetween(path, linePrefix))
                            .Append("<span class=\"stack line-prefix\">")
                            .AppendHtmlEncode(linePrefix.Value)
                            .Append("</span>")
                            .Append("<span class=\"stack line\">")
                            .AppendHtmlEncode(line.Value)
                            .Append("</span>");
                        }
                        sb.Append("</span>");
                    }

                    sb.Append("</span>");

                    pos = frame.Index + frame.Length;
                }

                // append anything left
                sb.Append("<span class=\"stack misc\">");
                LinkifyRest(sb, stackTrace, pos, settings.LinkReplacements);
                sb.Append("</span>");

                return(sb.ToStringRecycle());
            }
        private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey)
        {
            Hashtable parsetable = new Hashtable();
            Regex     parser     = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex);

            const int KeyIndex = 1, ValueIndex = 2;

            Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
            Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");

            if (null != connectionString)
            {
                Match match = parser.Match(connectionString);
                if (!match.Success || (match.Length != connectionString.Length))
                {
                    throw ADP.ConnectionStringSyntax(match.Length);
                }
                int indexValue = 0;
                CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
                foreach (Capture keypair in match.Groups[KeyIndex].Captures)
                {
                    string keyname  = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
                    string keyvalue = keyvalues[indexValue++].Value;
                    if (0 < keyvalue.Length)
                    {
                        if (!firstKey)
                        {
                            switch (keyvalue[0])
                            {
                            case '\"':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
                                break;

                            case '\'':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    else
                    {
                        keyvalue = null;
                    }
                    DebugTraceKeyValuePair(keyname, keyvalue, synonyms);

                    string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
                    if (!IsKeyNameValid(realkeyname))
                    {
                        throw ADP.KeywordNotSupported(keyname);
                    }
                    if (!firstKey || !parsetable.ContainsKey(realkeyname))
                    {
                        parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
                    }
                }
            }
            return(parsetable);
        }
Beispiel #5
0
        private string TokenizeValue(XmlAttribute targetAttribute, XmlAttribute transformAttribute, bool fTokenizeParameter, List <Dictionary <string, string> > parameters)
        {
            this.tokenizeValueCurrentXmlAttribute = transformAttribute;
            string xPathToAttribute = this.GetXPathToAttribute(targetAttribute);
            string input            = SubstituteKownValue(transformAttribute.Value, ParentAttributeRegex, "$(", key => this.EscapeDirRegexSpecialCharacter(this.GetAttributeValue(key), true));

            if (fTokenizeParameter && (parameters != null))
            {
                int           startIndex = 0;
                StringBuilder builder    = new StringBuilder(input.Length);
                startIndex = 0;
                List <Match> list = new List <Match>();
                while (true)
                {
                    startIndex = input.IndexOf("{%", startIndex, StringComparison.OrdinalIgnoreCase);
                    if (startIndex > -1)
                    {
                        Match item = DirRegex.Match(input, startIndex);
                        if (!item.Success)
                        {
                            startIndex++;
                        }
                        else
                        {
                            list.Add(item);
                            startIndex = item.Index + item.Length;
                        }
                    }
                    if (startIndex <= -1)
                    {
                        if (list.Count > 0)
                        {
                            builder.Remove(0, builder.Length);
                            startIndex = 0;
                            int num2 = 0;
                            foreach (Match match2 in list)
                            {
                                builder.Append(input.Substring(startIndex, match2.Index - startIndex));
                                CaptureCollection captures = match2.Groups["attrname"].Captures;
                                if ((captures != null) && (captures.Count > 0))
                                {
                                    GetValueCallback            getValueDelegate = null;
                                    CaptureCollection           captures2        = match2.Groups["attrval"].Captures;
                                    Dictionary <string, string> paramDictionary  = new Dictionary <string, string>(4, StringComparer.OrdinalIgnoreCase)
                                    {
                                        [XPathWithIndex] = xPathToAttribute,
                                        [TokenNumber]    = num2.ToString(CultureInfo.InvariantCulture)
                                    };
                                    int num3 = 0;
                                    while (true)
                                    {
                                        if (num3 >= captures.Count)
                                        {
                                            string tokenFormat = null;
                                            if (!paramDictionary.TryGetValue(Token, out tokenFormat))
                                            {
                                                tokenFormat = this.storageDictionary.TokenFormat;
                                            }
                                            if (!string.IsNullOrEmpty(tokenFormat))
                                            {
                                                paramDictionary[Token] = tokenFormat;
                                            }
                                            int      count = paramDictionary.Count;
                                            string[] array = new string[count];
                                            paramDictionary.Keys.CopyTo(array, 0);
                                            int index = 0;
                                            while (true)
                                            {
                                                if (index >= count)
                                                {
                                                    string str9;
                                                    if (paramDictionary.TryGetValue(Token, out tokenFormat))
                                                    {
                                                        builder.Append(tokenFormat);
                                                    }
                                                    if (paramDictionary.TryGetValue(XpathLocator, out str9) && !string.IsNullOrEmpty(str9))
                                                    {
                                                        IList <string> locators = XmlArgumentUtility.SplitArguments(str9);
                                                        string         str10    = this.GetXPathToAttribute(targetAttribute, locators);
                                                        if (!string.IsNullOrEmpty(str10))
                                                        {
                                                            paramDictionary[XPathWithLocator] = str10;
                                                        }
                                                    }
                                                    parameters.Add(paramDictionary);
                                                    break;
                                                }
                                                string str6           = array[index];
                                                string transformValue = paramDictionary[str6];
                                                if (getValueDelegate == null)
                                                {
                                                    getValueDelegate = key => paramDictionary.ContainsKey(key) ? paramDictionary[key] : null;
                                                }
                                                paramDictionary[str6] = SubstituteKownValue(transformValue, TokenFormatRegex, "#(", getValueDelegate);
                                                index++;
                                            }
                                            break;
                                        }
                                        string str3 = captures[num3].Value;
                                        string str4 = null;
                                        if ((captures2 != null) && (num3 < captures2.Count))
                                        {
                                            str4 = this.EscapeDirRegexSpecialCharacter(captures2[num3].Value, false);
                                        }
                                        paramDictionary[str3] = str4;
                                        num3++;
                                    }
                                }
                                startIndex = match2.Index + match2.Length;
                                num2++;
                            }
                            builder.Append(input.Substring(startIndex));
                            input = builder.ToString();
                        }
                        break;
                    }
                }
            }
            return(input);
        }
Beispiel #6
0
 // internal
 internal Group(string text, int index, int length, int n_caps) : base(text, index, length)
 {
     success  = true;
     captures = new CaptureCollection(n_caps);
     captures.SetValue(this, n_caps - 1);
 }
Beispiel #7
0
 /// <summary>
 /// Gets the first match capture from the specified match.
 /// </summary>
 /// <param name="c">The g.</param>
 /// <returns></returns>
 public static Capture SingleOrDefault(this CaptureCollection c)
 {
     return(c.SingleOrDefault(x => true));
 }
Beispiel #8
0
        /// <summary>
        /// 演示 多次匹配,并取得匹配数据的 例子.
        /// </summary>
        public void DemoRegexUse6()
        {
            string text = "One car red car blue car";

            // (1个到多个)单词 (1个到多个)空白 car
            string pat = @"(\w+)\s+(car)";


            Console.WriteLine("[06]字符串={0}", text);
            Console.WriteLine("[06]正则表达式={0}", pat);


            // 初始化 正则表达式  忽略大小写
            Regex r = new Regex(pat, RegexOptions.IgnoreCase);

            // 指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。
            Match m = r.Match(text);

            // 匹配的 计数.
            int matchCount = 0;


            // Match类 表示单个正则表达式匹配的结果。
            // Success 属性表示:匹配是否成功
            while (m.Success)
            {
                Console.WriteLine("[06]第{0}次匹配!", (++matchCount));

                for (int i = 1; i <= 2; i++)
                {
                    // Groups 为 获取由正则表达式匹配的组的集合。
                    Group g = m.Groups[i];
                    Console.WriteLine("==Group[{0}]={1}", i, g);

                    // Captures 为 按从里到外、从左到右的顺序获取由捕获组匹配的所有捕获的集合
                    // 该集合可以有零个或更多的项。
                    CaptureCollection cc = g.Captures;
                    for (int j = 0; j < cc.Count; j++)
                    {
                        // Capture 表示来自单个子表达式捕获的结果。
                        //     属性 Index 原始字符串中发现捕获的子字符串的第一个字符的位置。
                        //     属性 Length 捕获的子字符串的长度。
                        //     属性 Value 从输入字符串中获取捕获的子字符串。
                        Capture c = cc[j];
                        Console.WriteLine("====Capture[{0}] = {1}, Position={2}", j, c, c.Index);
                    }
                }
                m = m.NextMatch();
            }


            // 电子邮件地址
            string emailPat = @"^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$";

            string[] emailValueArray =
            {
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "@sina.com",
                "zhang3@",
                "zhang3@com",
            };

            foreach (string value in emailValueArray)
            {
                Console.WriteLine("[06]使用正则表达式静态方法IsMatch({0}, {1})的结果为:{2}", value, emailPat, Regex.IsMatch(value, emailPat));
            }



            // 网页地址匹配.
            String[] testArray =
            {
                "http://*****:*****@"([^/]+).htm";
            // 初始化 正则表达式  忽略大小写
            Regex rWeb = new Regex(patWeb, RegexOptions.IgnoreCase);

            foreach (string str in testArray)
            {
                // 指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一个匹配项。
                Match mWeb = rWeb.Match(str);
                if (mWeb.Success)
                {
                    Group g = mWeb.Groups[0];
                    Console.WriteLine("[06] 原始数据:{0}, 解析后的结果:{1} ", str, g.Value);
                }
            }



            // HTML 匹配.
            string htmlText = "<a href=\"/xqzx/mrxq/538244.shtml\" class=\"load_list\"><span class=\"fr\">2016-05-17</span><i>上海黄金交易所2016年5月17日交易行情</i></a>";

            string patHtml = "<a href=\"([^ ]+)\" class=\"load_list\"><span class=\"fr\">([^/]+)</span><i>([^/]+)</i></a>";

            // 初始化 正则表达式  忽略大小写
            Regex rHtml = new Regex(patHtml, RegexOptions.IgnoreCase);

            Match mHtml = rHtml.Match(htmlText);

            if (mHtml.Success)
            {
                Console.WriteLine(@"[06] 原始数据:{0},
解析后的结果:{1}
{2}
{3}", htmlText, mHtml.Groups[1].Value, mHtml.Groups[2].Value, mHtml.Groups[3].Value);
            }



            string htmlText2 = @"
据汇金网(www.gold678.com)周三(9月16日)监测的黄金ETFs数据显示,截止周二(9月15日)黄金ETF-SPDR Gold Trust的黄金持仓量约为678.18吨或2180.4252万盎司,较上一交易日持平。
<img[b]src=http://upload.fx678.com/upload/ht/20150916/nsy_2015091610562484.jpg[b]onload=imgresize(this);[b]style=cursor:pointer;[b]alt=图片点击可在新窗口打开查看[b]onclick=javascript:window.open(this.src);[b]/>
(SPDR Gold Trust黄金持仓历史走势)
<B>具体数据见下表:</B>
<img[b]src=http://upload.fx678.com/upload/ht/20150916/nsy_2015091610565776.png[b]onload=imgresize(this);[b]style=cursor:pointer;[b]alt=图片点击可在新窗口打开查看[b]onclick=javascript:window.open(this.src);[b]/>
";



            string patHtml2 = @"<img\[b\]src=([^ \[]+)";


            // 初始化 正则表达式  忽略大小写
            Regex rHtml2 = new Regex(patHtml2, RegexOptions.IgnoreCase);

            Match mHtml2 = rHtml2.Match(htmlText2);


            while (mHtml2.Success)
            {
                Group g2 = mHtml2.Groups[1];

                Console.WriteLine("[06] 分析 HTML 字符串,获取 <img 的 src = {0}", g2.Value);

                mHtml2 = mHtml2.NextMatch();
            }
        }
 //todo: (nheskew) look for multiple class names on the element and deal with the edges of the class name a _lot_ better
 private static string constructNodeClassPattern(CaptureCollection classNameCaptureCollection)
 {
     return(string.Format("\\s+class=[\"'](?:[^\"']*\\s+)?{0}(?:\\s+[^\"']*)?[\"']", classNameCaptureCollection[0].Value));
 }
Beispiel #10
0
 /// <summary>
 /// Gets the first match capture from the specified match.
 /// </summary>
 /// <param name="c">The capture collection.</param>
 /// <returns></returns>
 public static Capture FirstOrDefault(this CaptureCollection c)
 {
     return(c.FirstOrDefault(x => true));
 }
 private static string constructNodeIdPattern(CaptureCollection idCaptureCollection)
 {
     return(string.Format("\\s+id=[\"'](?:{0})[\"']", idCaptureCollection[0].Value));
 }
Beispiel #12
0
        /// <summary>
        /// This program is to implement linux "tail" program
        /// vUserInput will read command line and will print last 10 lines of file/files mentioned
        /// user can use option -n <nooflines> to mention how many lines to be printed to console
        /// usage tail [options] <nooflines> <filename1> <filename2>......
        /// </summary>
        /// <param name="vUserinput"></param>
        public static void tail(string vUserinput)
        {
            string myPattern = @"(tail)\s+(-n)\s+(\d+)\s+|(tail)\s+";

            int vFileNamepos = 0;
            int vNoofLines   = 0;

            // Instantiate the regular expression object.
            Regex r = new Regex(myPattern, RegexOptions.IgnoreCase);

            // Match the regular expression pattern against a text string.
            Match m = r.Match(vUserinput);

            //int matchCount = 0;
            while (m.Success)
            {
                //Console.WriteLine("Match" + (++matchCount));
                if (m.Groups[0].Value.TrimEnd() == "tail")
                {
                    vNoofLines   = 10;
                    vFileNamepos = 5;
                }
                else
                {
                    for (int i = 1; i <= 3; i++)
                    {
                        Group g = m.Groups[i];
                        //Console.WriteLine("Group" + i + "='" + g + "'");

                        CaptureCollection cc = g.Captures;
                        for (int j = 0; j < cc.Count; j++)
                        {
                            Capture c = cc[j];
                            //System.Console.WriteLine("Capture" + j + "='" + c + "', Position=" + c.Index);
                            if (i == 3)// start position of file names
                            {
                                //to get nooflines from user
                                Int32.TryParse(c.ToString(), out vNoofLines);
                                //file names array
                                vFileNamepos = c.Index + vNoofLines.ToString().Length;
                            }
                        }
                    }
                }
                m = m.NextMatch();
            }


            if (vFileNamepos > 0)
            {
                string[] filenames = vUserinput.Substring(vFileNamepos).TrimStart().Split(' ');
                for (int i = 0; i < filenames.Length; i++)
                {
                    try
                    {
                        // to read no of lines
                        int vTotalLines = System.IO.File.ReadLines(@filenames[i]).Count();
                        //to get last 10 or user defined no of lines
                        var lines = System.IO.File.ReadLines(@filenames[i]).Skip(vTotalLines - vNoofLines).Take(vNoofLines).ToArray();
                        // Display the file contents by using a foreach loop.
                        System.Console.WriteLine("Contents of " + filenames[i]);
                        foreach (string line in lines)
                        {
                            // Use a tab to indent each line of the file.
                            Console.WriteLine("\t" + line);
                        }
                    }
                    catch (System.IO.IOException e)
                    {
                        Console.WriteLine("Error reading from " + filenames[i]);
                    }
                    catch
                    {
                        Console.WriteLine("Some error occoured while reading " + filenames[i]);
                    }
                }
            }
            else
            {
                Console.WriteLine("Correct Usage. tail [options] <nooflines> <filename1> <filename2>");
            }
        }
        public static void parseData(String geLogFileName, String performanceFilePath)
        {
            try
            {
                StreamReader reader = File.OpenText(geLogFileName);

                StreamWriter trialInfo = File.AppendText(performanceFilePath);

                //get all the text in the file
                String fileStr = reader.ReadToEnd();

                // Write each trial's info on a new line
                trialInfo.WriteLine();

                // Start parsing the text, extract info and append to the performance file.
                // trial number:
                String trialName   = Regex.Match(fileStr, @"TrialName\s(.*)\r\n").ToString();
                String trialNumber = Regex.Match(Regex.Match(trialName, "Tr([0-9])+").ToString(),
                                                 "([0-9])+").ToString();

                trialInfo.Write(trialNumber + " ");

                // condition number:
                String conditionNo = Regex.Match(Regex.Match(fileStr, @"Condition\s(\d*)").ToString(),
                                                 "([0-9])+").ToString();
                trialInfo.Write(conditionNo + " ");

                // total number of objects:
                String totalNumObj = Regex.Match(Regex.Match(fileStr, @"NumObjects\s(\d*)").ToString(),
                                                 "([0-9])+").ToString();
                trialInfo.Write(totalNumObj + " ");

                // total number of targets:
                String totalNumTargets = Regex.Match(Regex.Match(fileStr, @"NumTargets\s(\d*)").ToString(),
                                                     "([0-9])+").ToString();
                trialInfo.Write(totalNumTargets + " ");

                // target objects:
                String          targetObjRegex = @"ObjStart.*\r\nObjName\s(.*)\r\nObjectFilePath\s(.*)\r\nIsTargetObject\s(\d)";
                MatchCollection targetMatches  = Regex.Matches(fileStr, targetObjRegex, RegexOptions.Multiline);
                int             targetCount    = 0;
                //Iterate through the matches, appending each to the performance file.
                foreach (Match SingleMatch in targetMatches)
                {
                    GroupCollection gc             = SingleMatch.Groups;
                    String          isTargetObject = gc[3].Captures[0].Value.Trim();
                    if (isTargetObject.Equals("1"))
                    {
                        String targetObj = gc[1].Captures[0].Value.Trim();
                        targetObj = Regex.Replace(targetObj, "Obj", "");

                        if (targetCount > 0)
                        {
                            trialInfo.Write("," + targetObj);
                        }
                        else
                        {
                            trialInfo.Write(targetObj);
                        }
                        targetCount++;
                    }
                }

                // Subject's selection of targets:
                String          subjTargetRegex      = @"SubjectTargetStart((.*)\r\n)*SubjectTargetEnd";
                MatchCollection subjSelectionMatches = Regex.Matches(fileStr, subjTargetRegex, RegexOptions.Multiline);
                int             selectionCount       = 0;
                foreach (Match SingleMatch in subjSelectionMatches)
                {
                    //Iterate through the matches, appending each to the performance file.
                    GroupCollection   gc = SingleMatch.Groups;
                    CaptureCollection cc = gc[1].Captures;
                    for (int k = 1; k < cc.Count; k++)
                    {
                        String subjSelection = cc[k].Value.Trim();
                        subjSelection = Regex.Replace(subjSelection, "Obj", "");

                        if (selectionCount > 0)
                        {
                            trialInfo.Write("," + subjSelection);
                        }
                        else
                        {
                            trialInfo.Write(" " + subjSelection);
                        }
                        selectionCount++;
                    }
                }

                //dismiss the file handle
                reader.Close();
                trialInfo.Close();
            }
            catch (Exception e)
            {
                throw new ATLogicException(" Error populating the Performance File. ");
            }
        }
        private static Dictionary <string, string> SplitConnectionString(string connectionString, Dictionary <string, string> synonyms)
        {
            var   parsetable = new Dictionary <string, string>();
            Regex parser     = s_connectionStringRegex;

            const int KeyIndex = 1, ValueIndex = 2;

            Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
            Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");

            if (null != connectionString)
            {
                Match match = parser.Match(connectionString);
                if (!match.Success || (match.Length != connectionString.Length))
                {
                    throw ADP.ConnectionStringSyntax(match.Length);
                }
                int indexValue = 0;
                CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
                foreach (Capture keypair in match.Groups[KeyIndex].Captures)
                {
                    string keyname  = keypair.Value.Replace("==", "=").ToLowerInvariant();
                    string keyvalue = keyvalues[indexValue++].Value;
                    if (0 < keyvalue.Length)
                    {
                        {
                            switch (keyvalue[0])
                            {
                            case '\"':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
                                break;

                            case '\'':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    else
                    {
                        keyvalue = null;
                    }
                    DebugTraceKeyValuePair(keyname, keyvalue, synonyms);

                    string synonym;
                    string realkeyname = null != synonyms ?
                                         (synonyms.TryGetValue(keyname, out synonym) ? synonym : null) :
                                         keyname;

                    if (!IsKeyNameValid(realkeyname))
                    {
                        throw ADP.KeywordNotSupported(keyname);
                    }
                    else
                    {
                        parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
                    }
                }
            }
            return(parsetable);
        }
Beispiel #15
0
 /// <summary>
 /// Converts the capture collection to an array of capture items.
 /// </summary>
 /// <param name="captures">The captures.</param>
 /// <returns></returns>
 public static Capture[] ToArray(this CaptureCollection captures)
 {
     return(captures.ToList().ToArray());
 }
Beispiel #16
0
        static string ExtractDirectiveAttribute(string baseDirectory, string name, CaptureCollection names, CaptureCollection values, bool isPath)
        {
            if (names.Count == 0)
            {
                return(String.Empty);
            }

            int index       = 0;
            int valuesCount = values.Count;

            foreach (Capture c in names)
            {
                if (String.Compare(c.Value, name, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    index++;
                    continue;
                }

                if (index > valuesCount)
                {
                    return(String.Empty);
                }

                if (isPath)
                {
                    string value = values [index].Value.Trim(directiveValueTrimChars);
                    if (String.IsNullOrEmpty(value))
                    {
                        return(String.Empty);
                    }

                    return(new VirtualPath(value, baseDirectory).Absolute);
                }
                else
                {
                    return(values [index].Value.Trim());
                }
            }

            return(String.Empty);
        }
Beispiel #17
0
 /// <summary>
 /// Enumerate through each Capture.
 /// </summary>
 /// <param name="captures">The Captures.</param>
 /// <param name="action">The action.</param>
 public static void ForEach(this CaptureCollection captures, Action <Capture> action)
 {
     captures.ForEach(x => true, x => action(x));
 }
Beispiel #18
0
        public void start()
        {
            btn_Report_HTML.Enabled = btn_Report_Txt.Enabled = true;

            times = new obj_Times();

            TimeSpan addTime = new TimeSpan();
            TimeSpan remTime = new TimeSpan();

            if (num_CorrH.Value + num_CorrM.Value > 0)
            {
                addTime += new TimeSpan((int)num_CorrH.Value, (int)num_CorrM.Value, 0);
                remTime += new TimeSpan((int)num_CorrH.Value * -1, (int)num_CorrM.Value * -1, 0);
            }

            lv_Results_01.Items.Clear();
            lv_Results_02.Items.Clear();

            DateTime arr = new DateTime();
            DateTime dep = new DateTime();
            DateTime n   = DateTime.Now;

            TimeSpan time  = new TimeSpan();
            TimeSpan dif   = new TimeSpan();
            TimeSpan tDiff = new TimeSpan(0, 0, 0);
            TimeSpan tWork = new TimeSpan(0, 0, 0);

            int numOfDays = 0;

            List <String> lines = new List <string>();

            if (rtb_Report_01.Text != "" && rtb_Report_02.Text == rtb_Report_01.Text)
            {
                tc1.SelectedIndex = 1;

                foreach (String s in rtb_Report_01.Lines)
                {
                    foreach (String ss in Properties.Settings.Default.s_dayNames.Split(','))
                    {
                        if (s.ToLower().StartsWith(ss.ToLower()))
                        {
                            lines.Add(s);
                        }
                    }
                }
            }

            Regex             r_proper  = new Regex(regx_proper);
            Regex             r_daysOff = new Regex(regx_daysoff);
            Regex             r_vacsic  = new Regex(regx_vacsic);
            Regex             r_nothing = new Regex(regx_nothing);
            MatchCollection   mc        = null;
            CaptureCollection cc        = null;

            try
            {
                assumedUserName = rtb_Report_01.Lines[Properties.Settings.Default.s_UseLine];
            }
            catch {
                assumedUserName = "******";
            }

            if (forceUserName && userName != "")
            {
                Text = "WolfPaw WorkTime Calculator 2 - " + userName;
            }
            else if (forceUserName && userName == "")
            {
                Text = "WolfPaw WorkTime Calculator 2 - Unknown user";
            }
            else
            {
                Text = "WolfPaw WorkTime Calculator 2 - " + assumedUserName;
            }

            foreach (String s in lines)
            {
                ListViewItem lvi = new ListViewItem();

                ListViewItem.ListViewSubItem lvsi1 = new ListViewItem.ListViewSubItem();
                ListViewItem.ListViewSubItem lvsi2 = new ListViewItem.ListViewSubItem();
                ListViewItem.ListViewSubItem lvsi3 = new ListViewItem.ListViewSubItem();
                ListViewItem.ListViewSubItem lvsi4 = new ListViewItem.ListViewSubItem();
                ListViewItem.ListViewSubItem lvsi5 = new ListViewItem.ListViewSubItem();
                ListViewItem.ListViewSubItem lvsi6 = new ListViewItem.ListViewSubItem();


                if (r_daysOff.IsMatch(s))
                {
                    mc            = r_daysOff.Matches(s);
                    cc            = mc[0].Captures;
                    lvi.Text      = mc[0].Groups[2].Value;
                    lvsi1.Text    = mc[0].Groups[1].Value;
                    lvsi6.Text    = "Munkaszüneti Nap";
                    lvi.BackColor = Color.LightGray;
                }
                else if (r_vacsic.IsMatch(s))
                {
                    mc            = r_vacsic.Matches(s);
                    cc            = mc[0].Captures;
                    lvi.Text      = mc[0].Groups[2].Value;
                    lvsi1.Text    = mc[0].Groups[1].Value;
                    lvsi6.Text    = "Szabadság / Betegség";
                    lvi.BackColor = Color.LightGreen;
                }
                else if (r_nothing.IsMatch(s))
                {
                    mc            = r_nothing.Matches(s);
                    cc            = mc[0].Captures;
                    lvi.Text      = mc[0].Groups[2].Value;
                    lvsi1.Text    = mc[0].Groups[1].Value;
                    lvsi6.Text    = " - ";
                    lvi.BackColor = Color.LightYellow;
                }
                else if (r_proper.IsMatch(s))
                {
                    lvi.UseItemStyleForSubItems = false;

                    lvsi1.BackColor                     =
                        lvsi2.BackColor                 =
                            lvsi3.BackColor             =
                                lvsi4.BackColor         =
                                    lvsi5.BackColor     =
                                        lvsi6.BackColor = Color.LightYellow;

                    lvsi1.Font                     =
                        lvsi2.Font                 =
                            lvsi3.Font             =
                                lvsi4.Font         =
                                    lvsi5.Font     =
                                        lvsi6.Font = Properties.Settings.Default.s_lvFont;

                    numOfDays++;

                    int ah = 0, am = 0, dh = 0, dm = 0;

                    mc         = r_proper.Matches(s);
                    cc         = mc[0].Captures;
                    lvi.Text   = mc[0].Groups[2].Value;
                    lvsi1.Text = mc[0].Groups[1].Value;
                    lvsi2.Text = mc[0].Groups[3].Value;
                    lvsi3.Text = mc[0].Groups[4].Value;

                    ah = Convert.ToInt32(lvsi2.Text.Split(':')[0]);
                    am = Convert.ToInt32(lvsi2.Text.Split(':')[1]);

                    //lvsi4.Text = mc[0].Groups[5].Value;

                    dh = Convert.ToInt32(lvsi3.Text.Split(':')[0]);
                    dm = Convert.ToInt32(lvsi3.Text.Split(':')[1]);

                    arr = new DateTime(n.Year, n.Month, n.Day, ah, am, 0);
                    dep = new DateTime(n.Year, n.Month, n.Day, dh, dm, 0);

                    time = dep.TimeOfDay - arr.TimeOfDay;

                    lvsi4.Text = time.Hours.ToString().PadLeft(2, '0') + ":" + time.Minutes.ToString().PadLeft(2, '0');

                    dif = time - daily;

                    String tme = "";

                    tme = dif.ToString().Substring(0, dif.ToString().Length - 3);

                    lvsi5.Text = tme;

                    if (dif.TotalMinutes > 0)
                    {
                        lvsi5.Text      = " " + lvsi5.Text;
                        lvsi5.Text     += " ↑";
                        lvsi5.BackColor = Color.Green;
                    }
                    else if (dif.TotalMinutes < 0)
                    {
                        lvsi5.Text += " ↓";

                        lvsi5.BackColor = Color.LightPink;

                        if (dif.TotalMinutes <= -30)
                        {
                            lvsi5.BackColor = Color.OrangeRed;
                        }
                        if (dif.TotalMinutes <= -60)
                        {
                            lvsi5.BackColor = Color.Red;
                        }
                    }
                    else
                    {
                        lvsi5.Text += " =";
                    }

                    lvsi6.Text    = "";
                    lvi.BackColor = Color.LightYellow;

                    tDiff += dif;
                    tWork += time;


                    times.addItem(numOfDays, Convert.ToDateTime(mc[0].Groups[2].Value), Convert.ToDateTime(mc[0].Groups[3].Value), Convert.ToDateTime(mc[0].Groups[4].Value), time);
                }

                if (lvsi1.Text.ToLower() == "hétfo")
                {
                    lvsi1.Text = lvsi1.Text.Replace("o", "ő");
                }

                lvi.SubItems.Add(lvsi1);
                lvi.SubItems.Add(lvsi2);
                lvi.SubItems.Add(lvsi3);
                lvi.SubItems.Add(lvsi4);
                lvi.SubItems.Add(lvsi5);
                lvi.SubItems.Add(lvsi6);

                if (!lockView)
                {
                    lv_Results_02.Items.Add(lvi);
                }

                ListViewItem lvi2 = (ListViewItem)lvi.Clone();

                lvi2.Font = Properties.Settings.Default.s_lvFont;

                lv_Results_01.Items.Add(lvi2);
            }

            if (!lockView)
            {
                ch_Arrival_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_AtWork_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_Date_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_DayOfWeek_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_DayType_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_Departure_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                ch_Diff_02.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            }

            ch_Arrival_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_AtWork_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_Date_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_DayOfWeek_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_DayType_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_Departure_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
            ch_Diff_01.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);

            lv_Results_01.Font = Properties.Settings.Default.s_lvFont;
            lv_Results_02.Font = Properties.Settings.Default.s_lvFont;


            if (num_CorrH.Value + num_CorrM.Value > 0)
            {
                if (pm_minus)
                {
                    tDiff += remTime;
                    tWork += remTime;
                }
                else
                {
                    tDiff += addTime;
                    tWork += addTime;
                }
            }

            try
            {
                tb_Diff.Text = tDiff.ToString().Substring(0, tDiff.ToString().Length - 3);
                tb_Mean.Text = new TimeSpan(0, ((int)tWork.TotalMinutes / numOfDays), 0).ToString();
                tb_Days.Text = numOfDays + "";
            }
            catch { }

            if (tDiff.TotalMinutes < 0)
            {
                tb_Diff.BackColor = Color.LightPink;
                tb_Diff.Text     += " ↓";
            }
            else if (tDiff.TotalMinutes > 0)
            {
                tb_Diff.BackColor = Color.LightGreen;
                tb_Diff.Text     += " ↑";
            }
            else
            {
                tb_Diff.BackColor = Color.LightYellow;
                tb_Diff.Text     += " =";
            }
        }
Beispiel #19
0
 /// <summary>
 /// Gets the first match Capture from the specified match.
 /// </summary>
 /// <param name="g">The Capture collection.</param>
 /// <returns></returns>
 /// <exception cref="InvalidOperationException"></exception>
 public static Capture First(this CaptureCollection g)
 {
     return(g.First(x => true));
 }
 public void FixtureSetUp()
 {
     coll = Match.Empty.Captures;
 }
Beispiel #21
0
        internal static string SearchForLink(Stream stream)
        {
            string text = null;

            text = ReadEntireStream(new StreamReader(stream));

            int textpos = 0;

            Match match;

            if ((match = doctypeDirectiveRegex.Match(text, textpos)).Success)
            {
                textpos += match.Length;
            }

            bool oneMatch;

            for (;;)
            {
                // Reset match flag
                oneMatch = false;

                // 1: scan for text up to the next tag.

                // First case: check for whitespace going all the way to the next tag

                if ((match = whitespaceRegex.Match(text, textpos)).Success)
                {
                    oneMatch = true;
                }

                // Second case: there may be some nonwhitespace; scan it

                else if ((match = textRegex.Match(text, textpos)).Success)
                {
                    oneMatch = true;
                }

                // we might be done now

                textpos += match.Length;
                if (textpos == text.Length)
                {
                    break;
                }

                // 2: handle constructs that start with <

                // First, check to see if it's a tag

                if ((match = tagRegex.Match(text, textpos)).Success)
                {
                    oneMatch = true;
                    string tag = match.Groups["tagname"].Value;

                    if (String.Compare(tag, "link", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        CaptureCollection attrnames  = match.Groups["attrname"].Captures;
                        CaptureCollection attrvalues = match.Groups["attrval"].Captures;

                        int    count     = attrnames.Count;
                        bool   rightType = false;
                        bool   rightRel  = false;
                        string href      = null;
                        for (int i = 0; i < count; i++)
                        {
                            string attrName  = attrnames[i].ToString();
                            string attrValue = attrvalues[i].ToString();
                            if (String.Compare(attrName, "type", StringComparison.OrdinalIgnoreCase) == 0 &&
                                ContentType.MatchesBase(attrValue, ContentType.TextXml))
                            {
                                rightType = true;
                            }
                            else if (String.Compare(attrName, "rel", StringComparison.OrdinalIgnoreCase) == 0 &&
                                     String.Compare(attrValue, "alternate", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                rightRel = true;
                            }
                            else if (String.Compare(attrName, "href", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                href = attrValue;
                            }

                            if (rightType && rightRel && href != null)
                            {
                                // Got a link to a disco file!
                                return(href);
                            }
                        }
                    }
                    else if (tag == "body")
                    {
                        // If body begins, get out, since link tags should only be defined in the head
                        break;
                    }
                }

                // check to see if it's an end tag

                else if ((match = endtagRegex.Match(text, textpos)).Success)
                {
                    oneMatch = true;
                }

                // check to see if it's a comment

                else if ((match = commentRegex.Match(text, textpos)).Success)
                {
                    oneMatch = true;
                }

                // we might be done now

                textpos += match.Length;

                if (textpos == text.Length)
                {
                    break;
                }

                // If we couldn't get one single match, it means that it's probably not HTML, so bail
                if (!oneMatch)
                {
                    break;
                }
            }

            return(null);
        }
Beispiel #22
0
 internal Group() : base("")
 {
     success  = false;
     captures = new CaptureCollection(0);
 }
Beispiel #23
0
 internal Group()
     : base(string.Empty)
 {
     success  = false;
     captures = new CaptureCollection(0);
 }
Beispiel #24
0
        public void ReadAttributeParser(string attrStr, Match objMatch)
        {
            // Get object value
            string objName      = objMatch.Groups ["OBJ_NAME"].Value;
            string objTableName = objMatch.Groups ["OBJ_TABLE_NAME"].Value;

            objTableName = string.IsNullOrEmpty(objTableName) ? objName : objTableName;

            // Parser Attribute
            Match attrMatch = Regex.Match(attrStr, DBPatternHelper.GetQueryAttrPattern());

            if (attrMatch.Success == true)
            {
                string attrName   = attrMatch.Groups ["ATTR_NAME"].Value;
                string colDeclare = attrMatch.Groups ["COL_NAME"].Value;
                colDeclare = string.IsNullOrEmpty(colDeclare) ? attrName : colDeclare;
                string colName   = colDeclare;
                bool   mustGroup = true;

                if (!string.IsNullOrEmpty(attrName))
                {
                    // 1. Anotaion parser
                    CaptureCollection anoCaps = attrMatch.Groups ["ANOTATIONS"].Captures;
                    foreach (Capture anoCap in anoCaps)
                    {
                        Match anoMatch = Regex.Match(anoCap.Value, DBPatternHelper.GetQueryAttrAnotationPattern());
                        if (anoMatch.Success == true)
                        {
                            string anoName = anoMatch.Groups ["ANOTATION_NAME"].Value.ToUpper();
                            string anoMeta = anoMatch.Groups ["ANOTATION_META"].Value.ToUpper();

                            switch (anoName)
                            {
                            case "COUNT":
                            case "SUM":
                            case "MIN":
                            case "MAX":
                            case "AVG":
                                colName = anoName + "(" + objName + "." + colName + ")";
                                if (!string.IsNullOrEmpty(anoMeta))
                                {
                                    anoMeta = $"{colName}{anoMeta}";
                                    if (string.IsNullOrEmpty(this.Having))
                                    {
                                        this.Having = $"HAVING {anoMeta}";
                                    }
                                    else
                                    {
                                        this.Having += $" AND {anoMeta}";
                                    }
                                }
                                // Calculator Funcs don't GROUP BY
                                mustGroup = false;
                                break;

                            case "DISTINCT":
                                colName = anoName + " " + objName + "." + colName;
                                break;

                            case "ORDER":
                                string orderVal = attrName;
                                switch (anoMeta)
                                {
                                case "DESC":
                                    orderVal += $" {anoMeta}";
                                    break;

                                default:
                                    break;
                                }

                                if (string.IsNullOrEmpty(this.OrderBy))
                                {
                                    this.OrderBy = $"ORDER BY {orderVal}";
                                }
                                else
                                {
                                    this.OrderBy += $", {orderVal}";
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    //check must GROUP
                    if (mustGroup)
                    {
                        if (string.IsNullOrEmpty(this.GroupBy))
                        {
                            this.GroupBy = $"GROUP BY {objName}.{colDeclare}";
                        }
                        else
                        {
                            this.GroupBy += $", {objName}.{colDeclare}";
                        }
                    }

                    // 2. Name Parser
                    attrName = (colName != colDeclare ? colName : objName + "." + colName) + " AS " + (this.IsJoinView ? colDeclare : attrName);
                    if (string.IsNullOrEmpty(this.Select))
                    {
                        this.Select = $"SELECT {attrName}";
                    }
                    else
                    {
                        this.Select += $", {attrName}";
                    }
                }
            }
            else
            {
                Console.WriteLine("Attributes not match!");
            }
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: VisualParamGenerator.exe [template.cs] [_VisualParams_.cs]");
                return;
            }
            else if (!File.Exists(args[0]))
            {
                Console.WriteLine("Couldn't find file " + args[0]);
                return;
            }

            XmlNodeList list;
            TextWriter  writer;

            try
            {
                writer = new StreamWriter(args[1]);
            }
            catch (Exception)
            {
                Console.WriteLine("Couldn't open " + args[1] + " for writing");
                return;
            }

            try
            {
                // Read in the template.cs file and write it to our output
                TextReader reader = new StreamReader(args[0]);
                writer.WriteLine(reader.ReadToEnd());
                reader.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("Couldn't read from file " + args[0]);
                return;
            }

            try
            {
                // Read in avatar_lad.xml
                Stream stream = OpenMetaverse.Helpers.GetResourceStream("avatar_lad.xml");

                if (stream != null)
                {
                    StreamReader reader = new StreamReader(stream);
                    XmlDocument  doc    = new XmlDocument();
                    doc.LoadXml(reader.ReadToEnd());
                    list = doc.GetElementsByTagName("param");
                }
                else
                {
                    Console.WriteLine("Failed to load resource avatar_lad.xml. Are you missing a data folder?");
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return;
            }

            SortedList <int, string> IDs    = new SortedList <int, string>();
            Dictionary <int, string> Alphas = new Dictionary <int, string>();
            Dictionary <int, string> Colors = new Dictionary <int, string>();

            StringWriter output = new StringWriter();

            // Make sure we end up with 251 Group-0 VisualParams as a sanity check
            int count = 0;

            foreach (XmlNode node in list)
            {
                if (node.Attributes["group"] == null)
                {
                    // Sanity check that a group is assigned
                    Console.WriteLine("Encountered a param with no group set!");
                    continue;
                }
                if ((node.Attributes["shared"] != null) && (node.Attributes["shared"].Value.Equals("1")))
                {
                    // This param will have been already been defined
                    continue;
                }
                if ((node.Attributes["edit_group"] == null))
                {
                    // This param is calculated by the client based on other params
                    continue;
                }

                // Confirm this is a valid VisualParam
                if (node.Attributes["id"] != null &&
                    node.Attributes["name"] != null)
                {
                    try
                    {
                        int id = Int32.Parse(node.Attributes["id"].Value);

                        string bumpAttrib = "false";
                        bool   skipColor  = false;

                        if (node.ParentNode.Name == "layer")
                        {
                            if (node.ParentNode.Attributes["render_pass"] != null && node.ParentNode.Attributes["render_pass"].Value == "bump")
                            {
                                bumpAttrib = "true";
                            }

                            for (int nodeNr = 0; nodeNr < node.ParentNode.ChildNodes.Count; nodeNr++)
                            {
                                XmlNode lnode = node.ParentNode.ChildNodes[nodeNr];

                                if (lnode.Name == "texture")
                                {
                                    if (lnode.Attributes["local_texture_alpha_only"] != null && lnode.Attributes["local_texture_alpha_only"].Value.ToLower() == "true")
                                    {
                                        skipColor = true;
                                    }
                                }
                            }
                        }


                        if (node.HasChildNodes)
                        {
                            for (int nodeNr = 0; nodeNr < node.ChildNodes.Count; nodeNr++)
                            {
                                #region Alpha mask and bumps
                                if (node.ChildNodes[nodeNr].Name == "param_alpha")
                                {
                                    XmlNode anode          = node.ChildNodes[nodeNr];
                                    string  tga_file       = "string.Empty";
                                    string  skip_if_zero   = "false";
                                    string  multiply_blend = "false";
                                    string  domain         = "0";

                                    if (anode.Attributes["domain"] != null)
                                    {
                                        domain = anode.Attributes["domain"].Value;
                                    }

                                    if (anode.Attributes["tga_file"] != null)
                                    {
                                        tga_file = string.Format("\"{0}\"", anode.Attributes["tga_file"].Value);
                                    }
                                    ;

                                    if (anode.Attributes["skip_if_zero"] != null && anode.Attributes["skip_if_zero"].Value.ToLower() == "true")
                                    {
                                        skip_if_zero = "true";
                                    }

                                    if (anode.Attributes["multiply_blend"] != null && anode.Attributes["multiply_blend"].Value.ToLower() == "true")
                                    {
                                        multiply_blend = "true";
                                    }

                                    Alphas.Add(id, string.Format("new VisualAlphaParam({0}f, {1}, {2}, {3})", domain, tga_file, skip_if_zero, multiply_blend));
                                }
                                #endregion
                                #region Colors
                                else if (node.ChildNodes[nodeNr].Name == "param_color" && node.ChildNodes[nodeNr].HasChildNodes)
                                {
                                    XmlNode       cnode     = node.ChildNodes[nodeNr];
                                    string        operation = "VisualColorOperation.Add";
                                    List <string> colors    = new List <string>();

                                    if (cnode.Attributes["operation"] != null)
                                    {
                                        switch (cnode.Attributes["operation"].Value)
                                        {
                                        case "blend":
                                            operation = "VisualColorOperation.Blend";
                                            break;

                                        case "multiply":
                                            operation = "VisualColorOperation.Blend";
                                            break;
                                        }
                                    }

                                    foreach (XmlNode cvalue in cnode.ChildNodes)
                                    {
                                        if (cvalue.Name == "value" && cvalue.Attributes["color"] != null)
                                        {
                                            Match m = Regex.Match(cvalue.Attributes["color"].Value, @"((?<val>\d+)(?:, *)?){4}");
                                            if (!m.Success)
                                            {
                                                continue;
                                            }
                                            CaptureCollection val = m.Groups["val"].Captures;
                                            colors.Add(string.Format("new Color4({0}, {1}, {2}, {3})", val[0], val[1], val[2], val[3]));
                                        }
                                    }

                                    if (colors.Count > 0 && !skipColor)
                                    {
                                        string colorsStr = string.Join(", ", colors.ToArray());
                                        Colors.Add(id, string.Format("new VisualColorParam({0}, new Color4[] {{ {1} }})", operation, colorsStr));
                                    }
                                }
                                #endregion
                            }
                        }

                        // Check for duplicates
                        if (IDs.ContainsKey(id))
                        {
                            continue;
                        }

                        string name  = node.Attributes["name"].Value;
                        int    group = Int32.Parse(node.Attributes["group"].Value);

                        string wearable = "null";
                        if (node.Attributes["wearable"] != null)
                        {
                            wearable = "\"" + node.Attributes["wearable"].Value + "\"";
                        }

                        string label = "String.Empty";
                        if (node.Attributes["label"] != null)
                        {
                            label = "\"" + node.Attributes["label"].Value + "\"";
                        }

                        string label_min = "String.Empty";
                        if (node.Attributes["label_min"] != null)
                        {
                            label_min = "\"" + node.Attributes["label_min"].Value + "\"";
                        }

                        string label_max = "String.Empty";
                        if (node.Attributes["label_max"] != null)
                        {
                            label_max = "\"" + node.Attributes["label_max"].Value + "\"";
                        }

                        float min = Single.Parse(node.Attributes["value_min"].Value,
                                                 System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat);
                        float max = Single.Parse(node.Attributes["value_max"].Value,
                                                 System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat);

                        float def;
                        if (node.Attributes["value_default"] != null)
                        {
                            def = Single.Parse(node.Attributes["value_default"].Value,
                                               System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat);
                        }
                        else
                        {
                            def = min;
                        }

                        string drivers = "null";
                        if (node.HasChildNodes)
                        {
                            for (int nodeNr = 0; nodeNr < node.ChildNodes.Count; nodeNr++)
                            {
                                XmlNode cnode = node.ChildNodes[nodeNr];

                                if (cnode.Name == "param_driver" && cnode.HasChildNodes)
                                {
                                    List <string> driverIDs = new List <string>();
                                    foreach (XmlNode dnode in cnode.ChildNodes)
                                    {
                                        if (dnode.Name == "driven" && dnode.Attributes["id"] != null)
                                        {
                                            driverIDs.Add(dnode.Attributes["id"].Value);
                                        }
                                    }

                                    if (driverIDs.Count > 0)
                                    {
                                        drivers = string.Format("new int[] {{ {0} }}", string.Join(", ", driverIDs.ToArray()));
                                    }
                                }
                            }
                        }

                        IDs.Add(id,
                                String.Format("            Params[{0}] = new VisualParam({0}, \"{1}\", {2}, {3}, {4}, {5}, {6}, {7}f, {8}f, {9}f, {10}, {11}, ",
                                              id, name, group, wearable, label, label_min, label_max, def, min, max, bumpAttrib, drivers));

                        if (group == 0)
                        {
                            ++count;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            }

            if (count != 251)
            {
                Console.WriteLine("Ended up with the wrong number of Group-0 VisualParams! Exiting...");
                return;
            }

            // Now that we've collected all the entries and sorted them, add them to our output buffer
            foreach (KeyValuePair <int, string> line in IDs)
            {
                output.Write(line.Value);

                if (Alphas.ContainsKey(line.Key))
                {
                    output.Write(Alphas[line.Key] + ", ");
                }
                else
                {
                    output.Write("null, ");
                }

                if (Colors.ContainsKey(line.Key))
                {
                    output.Write(Colors[line.Key]);
                }
                else
                {
                    output.Write("null");
                }


                output.WriteLine(");");
            }

            output.Write("        }" + Environment.NewLine);
            output.Write("    }" + Environment.NewLine);
            output.Write("}" + Environment.NewLine);

            try
            {
                writer.Write(output.ToString());
                writer.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Beispiel #26
0
		// internal
		internal Group (string text, int index, int length, int n_caps) : base (text, index, length)
		{
			success = true;
			captures = new CaptureCollection (n_caps);
			captures.SetValue (this, n_caps - 1);
		}
Beispiel #27
0
        /// <summary>
        /// Create a directive object from string.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException"/>
        /// <param name="cc">String, like &lt;%@ Register Assembly="Name" Namespace="Field" TagPrefix="Pref" %&gt;.</param>
        /// <param name="host">Reference to host.</param>
        /// <returns>Directive object, or throws an exception if format is invalid.</returns>
        internal static Directive GetDirectiveFromString(CaptureCollection cc, IDesignerHost host)
        {
            if (cc.Count > 0)
            {
                string assembly = "";
                string namspace = "";
                string tgprefix = "";
                string tagname  = "";
                string src      = "";
                foreach (Capture c in cc)
                {
                    string[] pairs = c.Value.Split(new String[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    if (pairs.Length != 2)
                    {
                        continue;
                    }
                    string val = pairs[1];
                    if (val.StartsWith(@""""))
                    {
                        val = val.Substring(1);
                    }
                    if (val.EndsWith(@""""))
                    {
                        val = val.Substring(0, val.Length - 1);
                    }
                    val = val.Trim();
                    switch (pairs[0].Trim().ToLower())
                    {
                    case "assembly":
                        assembly = val;
                        break;

                    case "namespace":
                        namspace = val;
                        break;

                    case "src":
                        src = val;
                        break;

                    case "tagprefix":
                        tgprefix = val;
                        break;

                    case "tagname":
                        tagname = val;
                        break;
                    }
                }
                if (!String.IsNullOrEmpty(src))
                {
                    return(new RegisterDirective(tgprefix, tagname, src, true));
                }
                else
                {
                    return(new RegisterDirective(tgprefix, namspace, assembly));
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException("text", "Register Directive String has not the expected format.");
            }
        }
Beispiel #28
0
            /// <summary>
            /// Converts a stack trace to formatted HTML with styling and linkifiation.
            /// </summary>
            /// <param name="stackTrace">The stack trace to HTMLify.</param>
            /// <returns>An HTML-pretty version of the stack trace.</returns>
            public static string HtmlPrettify(string stackTrace)
            {
                string GetBetween(Capture prev, Capture next) =>
                stackTrace.Substring(prev.Index + prev.Length, next.Index - (prev.Index + prev.Length));

                int pos = 0;
                var sb  = StringBuilderCache.Get();

                foreach (Match m in _regex.Matches(stackTrace))
                {
                    Group leadIn                 = m.Groups[Groups.LeadIn],
                               frame             = m.Groups[Groups.Frame],
                               type              = m.Groups[Groups.Type],
                               asyncMethod       = m.Groups[Groups.AsyncMethod],
                               method            = m.Groups[Groups.Method],
                               allParams         = m.Groups[Groups.Params],
                               path              = m.Groups[Groups.Path], // TODO: URLs
                               linePrefix        = m.Groups[Groups.LinePrefix],
                               line              = m.Groups[Groups.Line];
                    CaptureCollection paramTypes = m.Groups[Groups.ParamType].Captures,
                                      paramNames = m.Groups[Groups.ParamName].Captures;

                    var isAsync = _asyncFrames.Contains(frame.Value);
                    sb.Append(isAsync ? "<span class=\"stack row async\">" : "<span class=\"stack row\">");

                    sb.Append("<span class=\"stack misc\">")
                    .AppendHtmlEncode(stackTrace.Substring(pos, leadIn.Index - pos))
                    .Append("</span>")
                    .Append("<span class=\"stack leadin\">")
                    .AppendHtmlEncode(leadIn.Value)
                    .Append("</span>");

                    // Check if the next line is the end of an async hand-off
                    var nextEndStack = stackTrace.IndexOf(EndStack, m.Index + m.Length);
                    if (nextEndStack > -1 && nextEndStack < m.Index + m.Length + 3)
                    {
                        sb.Append("<span class=\"stack async-tag\">async</span> ");
                    }

                    if (asyncMethod.Success)
                    {
                        sb.Append("<span class=\"stack type\">")
                        .AppendGenerics(GetBetween(leadIn, asyncMethod))
                        .Append("</span>")
                        .Append("<span class=\"stack method\">")
                        .AppendHtmlEncode(asyncMethod.Value)
                        .Append("</span>")
                        .Append("<span class=\"stack type\">")
                        .AppendGenerics(GetBetween(asyncMethod, method));
                        sb.Append("</span>");
                    }
                    else
                    {
                        sb.Append("<span class=\"stack type\">")
                        .AppendGenerics(type.Value)
                        .Append("<span class=\"stack dot\">")
                        .AppendHtmlEncode(GetBetween(type, method))   // "."
                        .Append("</span>")
                        .Append("</span>");
                    }
                    sb.Append("<span class=\"stack method-section\">")
                    .Append("<span class=\"stack method\">")
                    .AppendHtmlEncode(method.Value)
                    .Append("</span>");

                    if (paramTypes.Count > 0)
                    {
                        sb.Append("<span class=\"stack parens\">")
                        .Append(GetBetween(method, paramTypes[0]))
                        .Append("</span>");
                        for (var i = 0; i < paramTypes.Count; i++)
                        {
                            if (i > 0)
                            {
                                sb.Append("<span class=\"stack misc\">")
                                .AppendHtmlEncode(GetBetween(paramNames[i - 1], paramTypes[i]))   // ", "
                                .Append("</span>");
                            }
                            sb.Append("<span class=\"stack paramType\">")
                            .AppendGenerics(paramTypes[i].Value)
                            .Append("</span>")
                            .AppendHtmlEncode(GetBetween(paramTypes[i], paramNames[i]))   // " "
                            .Append("<span class=\"stack paramName\">")
                            .AppendHtmlEncode(paramNames[i].Value)
                            .Append("</span>");
                        }
                        var last = paramNames[paramTypes.Count - 1];
                        sb.Append("<span class=\"stack parens\">")
                        .AppendHtmlEncode(allParams.Value.Substring(last.Index + last.Length - allParams.Index))
                        .Append("</span>");
                    }
                    else
                    {
                        sb.Append("<span class=\"stack parens\">")
                        .AppendHtmlEncode(allParams.Value)   // "()"
                        .Append("</span>");
                    }
                    sb.Append("</span>"); // method-section for table layout

                    // TODO: regular expression replacement for SourceLink
                    if (path.Value.HasValue())
                    {
                        var subPath = GetSubPath(path.Value, type.Value);

                        sb.Append("<span class=\"stack source-section\">")
                        .Append("<span class=\"stack misc\">")
                        .AppendHtmlEncode(GetBetween(allParams, path))
                        .Append("</span>")
                        .Append("<span class=\"stack path\">")
                        .AppendHtmlEncode(subPath)
                        .Append("</span>")
                        .AppendHtmlEncode(GetBetween(path, linePrefix))
                        .Append("<span class=\"stack line-prefix\">")
                        .AppendHtmlEncode(linePrefix.Value)
                        .Append("</span>")
                        .Append("<span class=\"stack line\">")
                        .AppendHtmlEncode(line.Value)
                        .Append("</span>")
                        .Append("</span>");
                    }

                    sb.Append("</span>");

                    pos = frame.Index + frame.Length;
                }
                // append anything left
                sb.Append("<span class=\"stack misc\">")
                .AppendHtmlEncode(stackTrace.Substring(pos))
                .Append("</span>");

                return(sb.ToStringRecycle());
            }
Beispiel #29
0
        private static void SetPropertyParameters(CalendarProperty property, CaptureCollection paramNames, CaptureCollection paramValues)
        {
            var paramValueIndex = 0;

            for (var paramNameIndex = 0; paramNameIndex < paramNames.Count; paramNameIndex++)
            {
                var paramName      = paramNames[paramNameIndex].Value;
                var parameter      = new CalendarParameter(paramName);
                var nextParamIndex = paramNameIndex + 1 < paramNames.Count ? paramNames[paramNameIndex + 1].Index : int.MaxValue;
                while (paramValueIndex < paramValues.Count && paramValues[paramValueIndex].Index < nextParamIndex)
                {
                    var paramValue = paramValues[paramValueIndex].Value;
                    parameter.AddValue(paramValue);
                    paramValueIndex++;
                }
                property.AddParameter(parameter);
            }
        }
Beispiel #30
0
        public static IRCCommand fromLine(string line)
        {
            MatchCollection matches = REGEX.Matches(line);

            if (matches.Count > 0)
            {
                Match           match  = matches[0];
                GroupCollection groups = match.Groups;
                string          prefix = groups["prefix"].Value;
                if (prefix == "")
                {
                    prefix = null;
                }
                else
                {
                    prefix = prefix.Substring(1);
                }
                string        command    = groups["command"].Value.ToUpper();
                List <string> parameters = new List <string>();

                CaptureCollection captures = groups["param"].Captures;
                for (int ix = 0; ix < captures.Count; ix++)
                {
                    Capture capture = captures[ix];

                    string parameter = capture.Value;
                    if (parameter != "")
                    {
                        parameters.Add(parameter);
                    }
                }
                string trailing = groups["trailing"].Value;
                if (trailing != "")
                {
                    parameters.Add(trailing.Substring(1));
                }

                if ((command == "PRIVMSG") && (parameters.Count() >= 2))
                {
                    string lastParam = parameters.Last();
                    if (lastParam.StartsWith("\u0001") && lastParam.EndsWith("\u0001"))
                    {
                        lastParam = lastParam.Substring(1, lastParam.Length - 2);
                        int pos = lastParam.IndexOf(' ');
                        if (pos >= 0)
                        {
                            return(new CTCPCommand(prefix, parameters[0], lastParam.Substring(0, pos), lastParam.Substring(pos + 1)));
                        }
                        else
                        {
                            return(new CTCPCommand(prefix, parameters[0], lastParam, null));
                        }
                    }
                }

                return(new IRCCommand(prefix, command, parameters.ToArray()));
            }
            else
            {
                throw new ArgumentException("could not parse line: " + line);
            }
        }
Beispiel #31
0
        public static MiniSQLQuery Parse(string miniSQLQuery)
        {
            const string selectPattern = "SELECT ([\\w,\\*\\s]+) FROM (\\w+)[\\sWHERE\\s]*(.+)?\\s?;";
            //const string insertPattern = "INSERT INTO (\\w+) VALUES \\(([\\w,\\s]+)\\)\\s?;";
            const string insertPattern = "INSERT INTO (\\w+) VALUES \\((.+)\\);";
            const string deletePattern = "DELETE FROM (\\w+) WHERE (.+);";
            const string dropPattern   = "DROP TABLE (\\w+);";
            const string updatePattern = "UPDATE (\\w+) SET (\\w+)\\s?=\\s?(['\\w\\s]+) WHERE (\\w+\\s?[=<>]\\s?['\\w\\s]+);";
            //const string createPattern = "CREATE TABLE (\\w+)\\s+\\((\\w+)\\s+(INT|DOUBLE|TEXT)(\\,\\s+(\\w+)\\s+(INT|DOUBLE|TEXT))+\\);";
            //const string createPattern2 = "CREATE TABLE (\\w) \\((\\w) \\((INT|DOUBLE|TEXT)));";
            const string createPattern        = "CREATE TABLE (\\w+) \\(((\\w+) (\\w+),?\\s?)+\\);";
            const string createProfilePattern = "CREATE SECURITY PROFILE (\\w+);";
            const string dropProfilePattern   = "DROP SECURITY PROFILE (\\w+);";
            const string addUserPattern       = "ADD USER \\('(\\w+)',(.+),(.+)\\);";
            const string deleteUserPattern    = "DELETE USER (.+);";
            const string grantPattern         = "GRANT (DELETE|INSERT|UPDATE|SELECT) ON (\\w+) TO (\\w+);";
            const string revokePattern        = "REVOKE (DELETE|INSERT|UPDATE|SELECT) ON (\\w+) TO (\\w+);";

            //Select
            Match match = Regex.Match(miniSQLQuery, selectPattern);

            if (match.Success)
            {
                List <string> columnNames = CommaSeparatedNames(match.Groups[1].Value);
                string        table       = match.Groups[2].Value;
                string        condition   = RemoveQuotesCondition(match.Groups[3].Value);
                return(new Select(table, columnNames, condition));
            }

            //Insert
            match = Regex.Match(miniSQLQuery, insertPattern);
            if (match.Success)
            {
                string table = match.Groups[1].Value;

                List <string> columnNames = CommaSeparatedNames(match.Groups[2].Value);
                return(new Insert(table, columnNames));
            }

            //Update
            match = Regex.Match(miniSQLQuery, updatePattern);
            if (match.Success)
            {
                string table        = match.Groups[1].Value;
                string targetColumn = match.Groups[2].Value;
                string update       = RemoveQuotesCondition(match.Groups[3].Value);
                string condition    = RemoveQuotesCondition(match.Groups[4].Value);
                return(new Update(table, condition, update, targetColumn));
            }

            //Delete
            match = Regex.Match(miniSQLQuery, deletePattern);
            if (match.Success)
            {
                string table     = match.Groups[1].Value;
                string condition = RemoveQuotesCondition(match.Groups[2].Value);
                return(new Delete(table, condition));
            }

            //Drop
            match = Regex.Match(miniSQLQuery, dropPattern);
            if (match.Success)
            {
                string table = match.Groups[1].Value;


                return(new DropTable(table));
            }


            //CreateTable
            match = Regex.Match(miniSQLQuery, createPattern);
            if (match.Success)
            {
                string            table       = match.Groups[1].Value;
                List <string>     columnNames = new List <string>();
                List <string>     columnTypes = new List <string>();
                CaptureCollection ccNames     = match.Groups[3].Captures;
                CaptureCollection ccTypes     = match.Groups[4].Captures;
                for (int i = 0; i < ccNames.Count; i++)
                {
                    columnNames.Add(ccNames[i].Value);
                    columnTypes.Add(ccTypes[i].Value);
                }
                return(new CreateTable(table, columnNames, columnTypes));
            }
            //CreateProfile
            match = Regex.Match(miniSQLQuery, createProfilePattern);
            if (match.Success)
            {
                string profile = match.Groups[1].Value;


                return(new CreateProfile(profile));
            }
            //DropProfile
            match = Regex.Match(miniSQLQuery, dropProfilePattern);
            if (match.Success)
            {
                string profile = match.Groups[1].Value;


                return(new DropProfile(profile));
            }
            //AddUser
            match = Regex.Match(miniSQLQuery, addUserPattern);
            if (match.Success)
            {
                string user     = match.Groups[1].Value;
                string password = match.Groups[2].Value;
                string profile  = match.Groups[3].Value;


                return(new AddUser(user, password, profile));
            }
            //DeleteUser
            match = Regex.Match(miniSQLQuery, deleteUserPattern);
            if (match.Success)
            {
                string user = match.Groups[1].Value;



                return(new DeleteUser(user));
            }
            //Grant
            match = Regex.Match(miniSQLQuery, grantPattern);
            if (match.Success)
            {
                string privilege = match.Groups[1].Value;
                string table     = match.Groups[2].Value;
                string profile   = match.Groups[3].Value;


                return(new Grant(privilege, table, profile));
            }

            //Revoke
            match = Regex.Match(miniSQLQuery, revokePattern);
            if (match.Success)
            {
                string privilege = match.Groups[1].Value;
                string table     = match.Groups[2].Value;
                string profile   = match.Groups[3].Value;


                return(new Revoke(privilege, table, profile));
            }
            return(null);
        }
Beispiel #32
0
        public RespuestaHTTP Escucha()
        {
            try{
                client = listener.AcceptTcpClient();
                DDebug.WriteLine("Conexion establecida");

                stream             = client.GetStream();
                reader             = new StreamReader(stream);
                writer             = new StreamWriter(stream);
                stream.ReadTimeout = 30000;

                // limpiar stream
                string entrada = "";
                while (entrada.Length < 4 || entrada.Substring(entrada.Length - 4, 4) != "\r\n\r\n")
                {
                    entrada += (char)reader.Read();
                }
                DDebug.WriteLine(entrada);
                stream.Flush();

                string GETurl = entrada.Substring(0, entrada.IndexOf("\r\n"));

                if (GETurl != null)
                {
                    string          pattern = " (.*?) HTTP";
                    MatchCollection matches = Regex.Matches(GETurl, pattern);

                    string url = "";

                    if (matches.Count > 0)
                    {
                        GroupCollection   gc = matches[0].Groups;
                        CaptureCollection cc = gc[1].Captures;
                        url = cc[0].Value;
                    }
                    DDebug.WriteLine(url);


                    pattern = "\\?(&?([^=^&]+?)=([^&]*))*";
                    matches = Regex.Matches(url, pattern);
                    //Utilidades.print_r_regex(matches);
                    if (matches.Count > 0)
                    {
                        GroupCollection   gc        = matches[0].Groups;
                        CaptureCollection variables = gc[2].Captures;
                        CaptureCollection valores   = gc[3].Captures;

                        ParametroGet[] parametros = new ParametroGet[variables.Count];
                        for (int i = 0; i < variables.Count; i++)
                        {
                            parametros[i] = new ParametroGet(
                                Uri.UnescapeDataString(variables[i].Value).Replace("+", " "),
                                Uri.UnescapeDataString(valores[i].Value).Replace("+", " "));
                        }
                        return(new RespuestaHTTP(url, parametros));
                    }
                    return(new RespuestaHTTP(url));
                }
                return(new RespuestaHTTP(false));
            }
            catch (Exception e) {
                Console.WriteLine("h1");
                Console.WriteLine(e);
                CierraCliente();
                return(new RespuestaHTTP(false));
            }
        }
Beispiel #33
0
 internal Group(string text, int start, int end)
     :base(text, start, end)
 {
     captures = new CaptureCollection();
     if (start != -1) captures.Add(this);
 }