Example #1
0
        public static void Refresh()
        {
            _port = 0;
            _portSet = false;
            _instances.Clear();

            ManagementClass mgmtClass = new ManagementClass("Win32_Process");
            foreach (ManagementObject process in mgmtClass.GetInstances())
            {

                string processName = process["Name"].ToString().ToLower();
                if (processName == "msmdsrv.exe")
                {

                    // get the process pid
                    System.UInt32 pid = (System.UInt32)process["ProcessId"];
                    var parentPid = int.Parse(process["ParentProcessId"].ToString());
                    var parentTitle = "";
                    if (parentPid > 0)
                    {
                        parentTitle = Process.GetProcessById(parentPid).MainWindowTitle;
                        if (parentTitle.Length == 0)
                        {
                            // for minimized windows we need to use some Win32 api calls to get the title
                            parentTitle = GetWindowTitle(parentPid);
                        }
                    }
                    // Get the command line - can be null if we don't have permissions
                    // but should have permission for PowerBI msmdsrv as it will have been
                    // launched by the current user.
                    string cmdLine = null;
                    if (process["CommandLine"] != null)
                    {
                        cmdLine = process["CommandLine"].ToString();
                        try
                        {
                            var rex = new System.Text.RegularExpressions.Regex("-s\\s\"(?<path>.*)\"");
                            var m = rex.Matches(cmdLine);
                            if (m.Count == 0) continue;
                            string msmdsrvPath = m[0].Groups["path"].Captures[0].Value;
                            var portFile = string.Format("{0}\\msmdsrv.port.txt", msmdsrvPath);
                            if (System.IO.File.Exists(portFile))
                            {
                                string sPort = System.IO.File.ReadAllText(portFile, Encoding.Unicode);
                                var port = int.Parse(sPort);
                                _port = port;
                                _portSet = true;
                                _instances.Add(new PowerBIInstance(parentTitle, port));
                                Log.Debug("{class} {method} PowerBI found on port: {port}", "PowerBIHelper", "Refresh", _port);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("{class} {Method} {Error}", "PowerBIHelper", "Refresh", ex.Message);
                        }
                    }
                }
            }
        }
Example #2
0
        private string SplitDigit(string algorithm)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\b\d*([.]?\d*)?\b");
            var temp = regex.Matches(algorithm);

            int vIndex = 1;
            string v = "var";
            for (int i = 0; i < temp.Count; i++)
            {
                if (string.IsNullOrEmpty(temp[i].Value))
                    continue;

                while (true)
                {
                    v = "var" + vIndex.ToString();
                    var t = Variable.Keys.Where(p => p.Contains(v)).FirstOrDefault();

                    if (t == null)
                        break;

                    vIndex++;
                }
                var r = new System.Text.RegularExpressions.Regex(@"\b"+temp[i].Value+@"\b");
                algorithm = r.Replace(algorithm, v, 1, temp[i].Index);

                Variable.Add(v, double.Parse(temp[i].Value, new System.Globalization.CultureInfo("en-US")));
            }
            return "(" + algorithm + ")";
        }
Example #3
0
        static void S()
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(?>(0[12])*(?=02e))");
            System.Text.RegularExpressions.MatchCollection matches = regex.Matches("01020102e");

            Console.WriteLine();
            int matchCount = 0;
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                matchCount++;
                Console.WriteLine("Match " + matchCount + ": " + (match.Value == null ? "NULL" : match.Value));
                System.Text.RegularExpressions.GroupCollection groups = match.Groups;
                int groupCount = -1;
                foreach (System.Text.RegularExpressions.Group group in groups)
                {
                    groupCount++;
                    Console.WriteLine("\tGroup " + groupCount + ": " + (group.Value == null ? "NULL" : group.Value));
                    System.Text.RegularExpressions.CaptureCollection captures = group.Captures;
                    int capCount = 0;
                    foreach (System.Text.RegularExpressions.Capture capture in captures)
                    {
                        capCount++;
                        Console.WriteLine("\t\tCapture " + capCount + ": " + (capture.Value == null ? "NULL" : capture.Value));
                    }
                }
            }
        }
Example #4
0
        public override void Create(CommandParser Parser)
        {
            Parser.AddCommand(
                Sequence(
                    RequiredRank(500),
                    KeyWord("KICK"),
                    Or(
                        Object("PLAYER", new ConnectedPlayersObjectSource(), ObjectMatcherSettings.None),
                        SingleWord("MASK"))))
                .Manual("Makes bad people go away.")
                .ProceduralRule((match, actor) =>
                {
                    if (match.ContainsKey("PLAYER"))
                        KickPlayer(match["PLAYER"] as Actor, actor);
                    else
                    {
                        var mask = match["MASK"].ToString();
                        var maskRegex = new System.Text.RegularExpressions.Regex(ProscriptionList.ConvertGlobToRegex(mask), System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                        //Iterate over local copy because kicking modifies ConnectedClients.
                        foreach (var client in new List<Client>(Clients.ConnectedClients))
                        {
                            var netClient = client as NetworkClient;
                            if (netClient != null && netClient.IsLoggedOn && maskRegex.Matches(netClient.IPString).Count > 0)
                            {
                                Core.MarkLocaleForUpdate(client.Player);
                                KickPlayer(client.Player, actor);
                            }
                        }
                    }

                    return PerformResult.Continue;
                });
        }
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("<input [^>]*>");
            System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"(\w)*\s*=\s*"+"\"([^\"]*)\"");

            var p = this.GetAncestorRawler().OfType<Page>();
            if (p.Any() == false)
            {
                ReportManage.ErrReport(this, "上流にPageがありません");
                return;
            }
            var page = p.First();
            List<KeyValue> list = new List<KeyValue>();
            foreach (System.Text.RegularExpressions.Match item in r.Matches(GetText()))
            {
                var dic = GetParameter(item.Value);
                if (dic.ContainsKey("type") && dic["type"] == "hidden")
                {
                    if (dic.ContainsKey("name") && dic.ContainsKey("value"))
                    {
                        page.AddParameter(dic["name"], dic["value"]);
                        list.Add(new KeyValue() { Key = dic["name"], Value = dic["value"] });
                    }
                }

            }
            base.Run(runChildren);
        }
Example #6
0
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"(\w*)\(([^)]*)\)");

            List<string> list = new List<string>();
            foreach (System.Text.RegularExpressions.Match item in r.Matches(GetText()))
            {
                if (string.IsNullOrEmpty(FunctionName))
                {
                    list.Add(item.Groups[0].Value);
                }
                else
                {
                    if (item.Groups[1].Value == FunctionName)
                    {
                        if (parameterOrder > -1)
                        {
                            var para = item.Value.Replace(FunctionName+"(","").Replace(")","").Split(',').ElementAtOrDefault(parameterOrder);
                            list.Add(para.Trim().Trim(new char[]{'\''}));
                        }
                        else
                        {
                            list.Add(item.Groups[2].Value);
                        }
                    }
                }
            }
            this.RunChildrenForArray(runChildren, list);
        }
 /// <summary>
 /// Compare two version strings
 /// </summary>
 /// <returns>1 if the first version is greater than the second version</returns>
 public static int Compare(string Version1, string Version2)
 {
     if (Version1 == null && Version2 == null)
     {
         return 0;
     }
     if (Version1 != null && Version2 == null)
     {
         return 1;
     }
     if (Version1 == null && Version2 != null)
     {
         return -1;
     }
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"([\d]+)");
     System.Text.RegularExpressions.MatchCollection m1 = regex.Matches(Version1);
     System.Text.RegularExpressions.MatchCollection m2 = regex.Matches(Version2);
     int min = Math.Min(m1.Count, m2.Count);
     for (int i = 0; i < min; i++)
     {
         if (Convert.ToInt32(m1[i].Value) > Convert.ToInt32(m2[i].Value))
         {
             return 1;
         }
         if (Convert.ToInt32(m1[i].Value) < Convert.ToInt32(m2[i].Value))
         {
             return -1;
         }
     }
     int max = Math.Max(m1.Count, m2.Count);
     for (int i = min; i < max; i++)
     {
         int v1 = (m1.Count < i ? Convert.ToInt32(m1[i].Value) : 0);
         int v2 = (m2.Count < i ? Convert.ToInt32(m2[i].Value) : 0);
         if (v1 > v2)
         {
             return 1;
         }
         if (v1 < v2)
         {
             return -1;
         }
     }
     return 0;
 }
 private void DigitsOnly_TextChanged(object sender, TextChangedEventArgs e)
 {
     var input = sender as TextBox;
     var regex = new System.Text.RegularExpressions.Regex("[0-9]");
     var value = String.Empty;
     foreach (var item in regex.Matches(input.Text))
         if (value.Length < 4)
             value += item.ToString();
     input.Text = value;
     input.CaretIndex = 99;
 }
 /// <summary>
 /// 获取批量值
 /// </summary>
 /// <param name="str"></param>
 /// <param name="s"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 public static System.Collections.Generic.List<string> GetValue(string str, string s, string e)
 {
     var rg = new System.Text.RegularExpressions.Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))");
     var mc = rg.Matches(str);
     var aStrings = new System.Collections.Generic.List<string>();
     for (var i = 0; i < mc.Count; i++)
     {
         aStrings.Add(mc[i].Value);
     }
     return aStrings.Count <= 0 ? null : aStrings;
 }
Example #10
0
 /// <summary>
 /// このクラスでの実行すること。
 /// </summary>
 /// <param name="runChildren"></param>
 public override void Run(bool runChildren)
 {
     System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern, regexOption);
     StringBuilder sb = new StringBuilder(GetText());
     foreach (System.Text.RegularExpressions.Match match in regex.Matches(GetText()))
     {
         sb.Replace(match.Value, string.Empty);
     }
     this.SetText(sb.ToString());
     base.Run(runChildren);
 }
 private Dictionary<string, string> GetParameter(string input)
 {
     Dictionary<string, string> dic = new Dictionary<string, string>();
     System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"(\w*)\s*=\s*" + "\"([^\"]*)\"");
     foreach (System.Text.RegularExpressions.Match item in r2.Matches(input))
     {
         string key = item.Groups[1].Value;
         string val = item.Groups[2].Value;
         dic.Add(key, val);
     }
     return dic;
 }
Example #12
0
 public static HashSet<string> Parse()
 {
     var client = new System.Net.WebClient();
     string pac = client.DownloadString(PACuri);
     var RegIP = new System.Text.RegularExpressions.Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
     var MatchResult = RegIP.Matches(pac);
     var Hostlist = new HashSet<string>();
     foreach (System.Text.RegularExpressions.Match m in MatchResult)
         if (m.Value != "255.255.255.255" && m.Value != "127.0.0.1")
             Hostlist.Add(m.Value);
     return Hostlist;
 }
Example #13
0
 /// <summary>
 /// 返回页数
 /// </summary>
 /// <param name="pdfPath">PDF文件地址</param>
 private static int GetPageCount(string pdfPath)
 {
     byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);
     int length = buffer.Length;
     if (buffer == null)
         return -1;
     if (buffer.Length <= 0)
         return -1;
     string pdfText = Encoding.Default.GetString(buffer);
     System.Text.RegularExpressions.Regex rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");
     System.Text.RegularExpressions.MatchCollection matches = rx1.Matches(pdfText);
     return matches.Count;
 }
Example #14
0
        public bool EmailAddressPassesValidation(string EmailAddress)
        {
            using (new FunctionLogger(Log))
            {
                string Match = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
                System.Text.RegularExpressions.Regex EmailAddressRegEx = new System.Text.RegularExpressions.Regex(Match);

                if (EmailAddressRegEx.Matches(EmailAddress).Count > 0)
                    return true;

                return false;
            }
        }
Example #15
0
        private void WebPageLoadedSearchCalled(object sender, WebPage.WebPageArguments args)
        {
            string htmlData = webpage.htmlData;
            if (htmlData != null)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(_regexPattern);
                results = regex.Matches(htmlData);

            }
            if(InfoReady != null)
            {
                InfoReady(this, new InfoReadyEventArgs("info ready"));
            }

               // webpage.WebPageLoaded -= WebPageLoadedSearchCalled;
        }
Example #16
0
        private int CountInString(
            string SourceString,
            string CompareString)
        {
            if (SourceString == null) {
                return 0;
            }

            string EscapedCompareString = System.Text.RegularExpressions.Regex.Escape(CompareString);

            System.Text.RegularExpressions.Regex regex;
            regex = new System.Text.RegularExpressions.Regex(
                @"\b" + EscapedCompareString + @"\b",
                System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            System.Text.RegularExpressions.MatchCollection matches;
            matches = regex.Matches(SourceString);
            return matches.Count;
        }
Example #17
0
        public static bool ValidateKey(string apiKey)
        {
            System.Text.RegularExpressions.Regex lower = new System.Text.RegularExpressions.Regex("[a-zA-Z]");
            System.Text.RegularExpressions.Regex number = new System.Text.RegularExpressions.Regex("[0-9]");

            if (apiKey.Length < 32)
                return false;

            if (apiKey.ToCharArray().Distinct().Count() < 10)
                return false;

            if (lower.Matches(apiKey).Count < 10)
                return false;

            if (number.Matches(apiKey).Count < 10)
                return false;

            return true;
        }
        public static List<ElementMolecule> GetElementMoleculeBySymbol(this dcFertilizer dc, string moleculeSymbol)
        {
            List<ElementMolecule> retVal = new List<ElementMolecule>();
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("[A-Z]");
            System.Text.RegularExpressions.MatchCollection mc = r.Matches(moleculeSymbol);
            for (int i = 0; i < mc.Count; i++)
            {
                System.Text.RegularExpressions.Match cElement = mc[i];
                int startIndex = cElement.Index;
                int stopIndex;
                if (mc.Count > i + 1)
                    stopIndex = mc[i + 1].Index;
                else
                    stopIndex = moleculeSymbol.Length;

                System.Text.RegularExpressions.Regex q = new System.Text.RegularExpressions.Regex("[0-9]");

                string elem = moleculeSymbol.Substring(startIndex, stopIndex - startIndex);
                System.Text.RegularExpressions.MatchCollection mcQ = q.Matches(elem);
                ElementMolecule ec = new ElementMolecule();
                string symbol;
                if (mcQ.Count > 0)
                {
                    ec.Quantity = int.Parse(elem.Substring(mcQ[0].Index));
                    symbol = elem.Substring(0, mcQ[0].Index);
                }
                else
                {
                    symbol = elem;
                    ec.Quantity = 1;
                }

                IEnumerable<Element> dbElem = dc.Elements.Where(e => e.Symbol == symbol);
                if (dbElem.Count() > 0)
                    ec.Element = dbElem.First();

                ec.FigureMolecularMass();

                retVal.Add(ec);
            }
            return retVal;
        }
		public override FieldValidationResult ValidateData(object value, Field field)
		{
			var result = base.ValidateData(value, field);
			if (result != FieldValidationResult.Successful)
				return result;

			string stringValue = (string)value ?? "";

			//-- regex
			if (!string.IsNullOrEmpty(this.Regex))
			{
				var r = new System.Text.RegularExpressions.Regex(this.Regex);
				var matches = r.Matches(stringValue);
				if (matches.Count == 0 || matches[0].Length != stringValue.Length)
				{
					return new FieldValidationResult(RegexName);
				}
			}
			return FieldValidationResult.Successful;
		}
        public static String ApplyRegex(String source, SyncDirection direction) {
            String retStr = source;
            if (Settings.Instance.Obfuscation.Enabled && direction == Settings.Instance.Obfuscation.Direction) {
                foreach (DataGridViewRow row in MainForm.Instance.dgObfuscateRegex.Rows) {
                    DataGridViewCellCollection cells = row.Cells;
                    if (cells[Obfuscate.FindCol].Value != null) {
                        System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(
                            cells[Obfuscate.FindCol].Value.ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                        System.Text.RegularExpressions.MatchCollection matches = rgx.Matches(retStr);
                        if (matches.Count > 0) {
                            log.Debug("Regex has matched and altered string: " + cells[Obfuscate.FindCol].Value.ToString());
                            if (cells[Obfuscate.ReplaceCol].Value == null) cells[Obfuscate.ReplaceCol].Value = "";
                            retStr = rgx.Replace(retStr, cells[Obfuscate.ReplaceCol].Value.ToString());
                        }
                    }
                }
            }
            return retStr;
        }
Example #21
0
        static void CompareMatchEngines(string text, string regex)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            System.Text.RegularExpressions.Regex reNet = new System.Text.RegularExpressions.Regex(regex);
            int nMatches = 0;
            foreach (System.Text.RegularExpressions.Match m in reNet.Matches(text)) nMatches++;
            timer.Stop();
            Console.WriteLine("\t.NET library Regex found {0} matches in {1:F3} ms",
                nMatches, timer.Elapsed.TotalMilliseconds);
            double baseline = timer.Elapsed.TotalMilliseconds;

            timer.Restart();
            Regex re = new Regex(regex);
            nMatches = 0;
            foreach (Match m in re.Matches(text)) nMatches++;
            timer.Stop();
            Console.WriteLine("\tBrasswork Regex found {0} matches in {1:F3} ms ({2:F3} of .NET)",
                nMatches, timer.Elapsed.TotalMilliseconds, timer.Elapsed.TotalMilliseconds / baseline);
        }
 public static int GetPageCount(string pdfPath)
 {
     try
     {
         byte[] buffer = System.IO.File.ReadAllBytes(pdfPath);
         int length = buffer.Length;
         if (buffer == null)
             return -1;
         if (buffer.Length <= 0)
             return -1;
         string pdfText = Encoding.Default.GetString(buffer);
         var rx1 = new System.Text.RegularExpressions.Regex(@"/Type\s*/Page[^s]");
         var matches = rx1.Matches(pdfText);
         return matches.Count;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public static DaxStudioClient GetClient()
        {
            var port = 0;

            ManagementClass mgmtClass = new ManagementClass("Win32_Process");
            foreach (ManagementObject process in mgmtClass.GetInstances())
            {

                string processName = process["Name"].ToString().ToLower();
                if (processName == "daxstudio.exe")
                {
                    UInt32 pid32 = (UInt32)process["ProcessId"];
                    int pid = Convert.ToInt32(pid32) ;
                    // Get the command line - can be null if we don't have permissions
                    // but should have permission for DaxStudio as it should have been
                    // launched by the current user.
                    string cmdLine = null;
                    if (process["CommandLine"] != null)
                    {
                        cmdLine = process["CommandLine"].ToString();
                        try
                        {
                            var rex = new System.Text.RegularExpressions.Regex("((?:\\\".*\\\"\\s)(?<port>\\d*))");
                            var m = rex.Matches(cmdLine);
                            if (m.Count == 0) continue;
                            int.TryParse(m[0].Groups["port"].Captures[0].Value, out port);

                            Log.Debug("{class} {method} DaxStudio standalone found listening on port: {port}", "DaxStudioStandalone", "GetPort", port);
                            return new DaxStudioClient(Process.GetProcessById(pid), port);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("{class} {Method} {Error}", "DaxStudioStandalone", "GetPort", ex.Message);
                        }

                    }

                }
            }
            return null;
        }
Example #24
0
        /// <summary>
        /// HTML��̑��΃p�X���΃p�X��
        /// </summary>
        /// <param name="HTML"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ChangeAbsoluteUri(string HTML, string url)
        {
            Uri baseUri = new Uri(url);
            System.Text.RegularExpressions.Regex regexHref = new System.Text.RegularExpressions.Regex(@"HREF\s*=(\s*|\s*[""])([^""\s]+)([""]|\s)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regexSrc = new System.Text.RegularExpressions.Regex(@"SRC\s*=(\s*|\s*[""])([^""\s]+)([""]|\s)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regexHttp = new System.Text.RegularExpressions.Regex("^http", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            Dictionary<string, string> repleceDic = new Dictionary<string, string>();
            foreach (System.Text.RegularExpressions.Match match in regexHref.Matches(HTML))
            {
                string href = match.Groups[2].Value;
                if (regexHttp.IsMatch(href) == false)
                {
                    Uri uri = new Uri(baseUri, href);
                    if (repleceDic.ContainsKey(href) == false)
                    {
                        repleceDic.Add(href, uri.AbsoluteUri);
                    }
                }
            }
            foreach (System.Text.RegularExpressions.Match match in regexSrc.Matches(HTML))
            {
                string href = match.Groups[2].Value;
                if (regexHttp.IsMatch(href) == false)
                {
                    Uri uri = new Uri(baseUri, href);
                    if (repleceDic.ContainsKey(href) == false)
                    {
                        repleceDic.Add(href, uri.AbsoluteUri);
                    }
                }
            }
            StringBuilder strBuilder = new StringBuilder(HTML);
            foreach(string key in repleceDic.Keys)
            {
                strBuilder.Replace("\""+key+"\"","\""+ repleceDic[key]+"\"");

            }
            return strBuilder.ToString();
        }
        public virtual List<string> GetMatches(string input, string pattern)
        {
            var list = new List<string>();

            const string groupName = "capture";
            var capturePattern = String.Format("(?<{0}>{1})", groupName, pattern);
            var regex = new System.Text.RegularExpressions.Regex(capturePattern);
            var matches = regex.Matches(input);
            for (var i = 0; i < matches.Count; i++)
            {
                var match = matches[i];
                var captures = match.Captures;
                for (var c = 0; c < captures.Count; c++)
                {
                    var capture = captures[c];
                    var val = capture.Value;
                    list.Add(val);
                }
            }

            return list;
        }
Example #26
0
        private static object[] _GetParams(Type type, string command, string args, CommandParamParser[] command_param_parsers)
        {
            string pattern = @"[\w\.]+";
            var rgx = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            var matches = rgx.Matches(args);

            var method = type.GetMethod(command, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            if (method != null)
            {
                var parameterInfos = method.GetParameters().ToArray();
                var argments = (from System.Text.RegularExpressions.Match match in matches select match.Value).ToArray();

                object[] retArgs = new object[parameterInfos.Count()];
                for (int i = 0; i < parameterInfos.Count(); ++i)
                {
                    var parser = (from cpp in command_param_parsers where cpp.Type == parameterInfos[i].ParameterType select cpp.Parser).FirstOrDefault();
                    if (parser != null)
                    {
                        try
                        {
                            retArgs[i] = parser.Invoke(argments[i]);
                        }
                        catch(SystemException e)
                        {
                            throw new SystemException("參數解析失敗" + e.ToString());
                        }

                    }
                    else
                    {
                        retArgs[i] = parameterInfos[i].DefaultValue;
                    }
                }

                return retArgs;
            }
            return null;
        }
 private void PriceTxtBox_TextChanged(object sender, TextChangedEventArgs e)
 {
     var caret = PriceTxtBox.CaretIndex;
     var regex = new System.Text.RegularExpressions.Regex(@"[0-9,\.]");
     var value = String.Empty;
     bool separatorIncluded = false;
     foreach (var item in regex.Matches(PriceTxtBox.Text))
     {
         var ch = item.ToString().Replace(".",",");
         if (ch == ",")
         {
             if (separatorIncluded == false)
                 value += ch;
             separatorIncluded = true;
         }
         else
         {
             value += ch;
         }
     }
     PriceTxtBox.Text = value;
     PriceTxtBox.CaretIndex = caret;
 }
Example #28
0
        public override void Run(bool runChildren)
        {
            List<string> list = new List<string>();
            if(DateType == DateType.LongDate)
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\d{4}/\d{1,2}/\d{1,2} \d{2}:\d{2}");

                foreach(System.Text.RegularExpressions.Match item in reg.Matches(GetText()))
                {
                    list.Add(item.Value);
                }
            }
            else if(DateType ==DateType.ShortDate)
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\d{4}/\d{1,2}/\d{1,2}");

                foreach (System.Text.RegularExpressions.Match item in reg.Matches(GetText()))
                {
                    list.Add(item.Value);
                }
            }
            RunChildrenForArray(runChildren, list);
        }
Example #29
0
        public void Send(string command_feedstock)
        {
            string pattern = @"(\w+)\.(\w+)([\w\s\.]*)";
            var rgx = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            var matches = rgx.Matches(command_feedstock);
            var firstGroup = (from System.Text.RegularExpressions.Match m in matches select m.Groups).FirstOrDefault();
            if (firstGroup != null)
            {
                var commandAndArgs = (from System.Text.RegularExpressions.Group value in firstGroup select value.Value).ToArray();
                if (commandAndArgs.Count() > 1)
                {
                    string name = commandAndArgs[1];

                    var first = (from ch in _CommandInvoker where ch.Name == name select new { handler = ch.Handler, type = ch.Type }).FirstOrDefault();

                    if (first != null)
                    {
                        string command = commandAndArgs[2];
                        object[] args = _GetParams(first.type, command, commandAndArgs[3], _CommandParamParsers);
                        try
                        {
                            first.type.InvokeMember(command, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, first.handler, args);

                        }
                        catch (System.Exception e)
                        {
                            throw new SystemException("沒有可呼叫命令 命令類型:" + name + "命令名稱:" + command + "參數:" + args.ToString() + "\n" + e.ToString());
                        }
                    }
                }
                else
                {
                    throw new SystemException("命令解析失敗");
                }

            }
        }
Example #30
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            bool ok = true;
            if (txtRecipient.Text.Length <= 0 || txtSubject.Text.Length <= 0) {
                ok = false;
                Wc3o.Game.Message(Master, "Fill out all necessary fields.", MessageType.Error);
            }

            if (ok) {
                int numberOfRecipients = 0;
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w*");
                foreach (System.Text.RegularExpressions.Match match in regex.Matches(txtRecipient.Text)) {
                    if (match.Length > 0) {
                        Player recipient = Wc3o.Game.GameData.Players[match.Value];
                        if (recipient != null) {
                            string subject = "";
                            if (Request.QueryString["Alliance"] != null && Request.QueryString["Alliance"] == user.Alliance.Name)
                                subject = "<i>[Alliance message] </i>";
                            new Message(recipient, user, subject + Server.HtmlEncode(txtSubject.Text), Server.HtmlEncode(txtText.Text).Replace("\n", "<br />"));
                            if (recipient.IsAlly(user))
                                numberOfRecipients++;

                            if (txtSubject.Text.Length <= 0)
                                txtSubject.Text = "no subject";

                            Wc3o.Game.Message(Master, "Your message was sent to '" + match.Value + "'.", MessageType.Acknowledgement);
                        }
                        else
                            Wc3o.Game.Message(Master, "The Recipient '" + match.Value + "' does not exist.", MessageType.Error);

                        if (numberOfRecipients >= 5)
                            break;
                    }
                }
                txtRecipient.Text = "";
            }
        }
Example #31
0
        public static QueryComposer.Adapters.PCORI.PCORIModelAdapter CreatePCORIModelAdapterAdapter(string connectionString, Lpp.Dns.DataMart.Model.Settings.SQLProvider sqlProvider, string schema = null)
        {
            Dictionary <string, object> adapterSettings;

            if (sqlProvider == Settings.SQLProvider.SQLServer)
            {
                var connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
                adapterSettings = new Dictionary <string, object>()
                {
                    { "Server", connectionStringBuilder.DataSource },
                    { "UserID", connectionStringBuilder.UserID },
                    { "Password", connectionStringBuilder.Password },
                    { "Database", connectionStringBuilder.InitialCatalog },
                    { "DataProvider", sqlProvider.ToString() }
                };
            }
            else if (sqlProvider == Settings.SQLProvider.PostgreSQL)
            {
                var postgresConnectionStringBuilder = new Npgsql.NpgsqlConnectionStringBuilder(connectionString);

                adapterSettings = new Dictionary <string, object>()
                {
                    { "Server", postgresConnectionStringBuilder.Host },
                    { "Port", postgresConnectionStringBuilder.Port.ToString() },
                    { "UserID", postgresConnectionStringBuilder.Username },
                    //{"Password", System.Text.Encoding.UTF8.GetString(postgresConnectionStringBuilder.PasswordAsByteArray) },
                    { "Password", postgresConnectionStringBuilder.Password },
                    { "Database", postgresConnectionStringBuilder.Database },
                    { "ConnectionTimeout", postgresConnectionStringBuilder.Timeout.ToString() },
                    { "CommandTimeout", postgresConnectionStringBuilder.CommandTimeout.ToString() },
                    { "DatabaseSchema", schema },
                    { "DataProvider", sqlProvider.ToString() }
                };
            }
            else if (sqlProvider == Settings.SQLProvider.Oracle)
            {
                var oracleConnectionStringBuilder = new Oracle.ManagedDataAccess.Client.OracleConnectionStringBuilder(connectionString);
                adapterSettings = new Dictionary <string, object>()
                {
                    { "Server", "" },
                    { "Port", "" },
                    { "Database", "" },
                    { "UserID", oracleConnectionStringBuilder.UserID },
                    { "Password", oracleConnectionStringBuilder.Password },
                    { "DataProvider", sqlProvider.ToString() },
                    { "DatabaseSchema", schema }
                };

                //(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={server address})(PORT=1521))(CONNECT_DATA=(SERVICE_NAME={service name})))
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\((?:[\w|\=|\.]+)\)");
                var matches = regex.Matches(oracleConnectionStringBuilder.DataSource);
                foreach (var m in matches)
                {
                    string   capture = m.ToString();
                    string[] split   = capture.Substring(1, capture.Length - 2).Split(new[] { '=' });
                    if (string.Equals("HOST", split[0], StringComparison.OrdinalIgnoreCase))
                    {
                        adapterSettings["Server"] = split[1];
                    }
                    else if (string.Equals("PORT", split[0], StringComparison.OrdinalIgnoreCase))
                    {
                        adapterSettings["Port"] = split[1];
                    }
                    else if (string.Equals("SERVICE_NAME", split[0], StringComparison.OrdinalIgnoreCase))
                    {
                        adapterSettings["Database"] = split[1];
                    }
                }
            }
            else
            {
                throw new NotImplementedException("Support for parsing configuration string into adapter settings not completed yet.");
            }

            var adapter = new QueryComposer.Adapters.PCORI.PCORIModelAdapter(new RequestMetadata
            {
                CreatedOn   = DateTime.UtcNow,
                MSRequestID = "Unit Test Request"
            });

            adapter.Initialize(adapterSettings);
            return(adapter);
        }
Example #32
0
        private void web_browser_ConsoleMessage(object sender, ConsoleMessageEventArgs e)
        {
            Logging.Debug特("JAVASCRIPT CONSOLE MESSAGE: {0}", e.Message);

            try
            {
                if (finished_processing)
                {
                    Logging.Info("Finished processing, so ignoring InCite JavaScript error: {0}", e.Message);
                    return;
                }

                if (e.Message.Contains("Permission denied"))
                {
                    Logging.Info("Skipping known exception: {0}", e.Message);
                    return;
                }

                if (e.Message.Contains("SyntaxError"))
                {
                    finished_processing = true;

                    Logging.Info("Acting on InCite syntax error: {0}", e.Message);

                    System.Text.RegularExpressions.Regex           regex   = new System.Text.RegularExpressions.Regex(@"line:\s+(\d+)\s+column:\s+(\d+)\s+");
                    System.Text.RegularExpressions.MatchCollection matches = regex.Matches(e.Message);
                    if (0 < matches.Count)
                    {
                        int line = Int32.Parse(matches[0].Groups[1].Value);
                        int pos  = Int32.Parse(matches[0].Groups[2].Value);

                        string[] citations_javascript_lines = citations_javascript.Split(new char[] { '\n' });

                        int           min             = (int)Math.Max(0, line - 1 - 15);
                        int           max             = (int)Math.Min(citations_javascript_lines.Length, line - 1 + 5);
                        StringBuilder sb_error_region = new StringBuilder();
                        sb_error_region.AppendFormat("Syntax error ({1},{2}): {0}\n", e.Message, line, pos);
                        for (int i = min; i <= max; ++i)
                        {
                            string indicator = (i == line - 1) ? "?????? " : "       ";
                            sb_error_region.AppendFormat("{0}{1}\n", indicator, citations_javascript_lines[i]);
                        }

                        error_message = sb_error_region.ToString();
                    }
                    else
                    {
                        error_message = e.Message;
                    }

                    Logging.Info("Calling the BibliographyReadyDelegate");
                    success = false;
                    brd(this);
                    Logging.Info("Called the BibliographyReadyDelegate");
                }

                if (e.Message.Contains("INCITE_FINISHED"))
                {
                    finished_processing = true;

                    Logging.Info("Acting on signalling InCite JavaScript error: {0}", e.Message);

                    Logging.Info("Received citeproc results");
                    {
                        string  json_output_encoded = web_browser.DomDocument.GetHtmlElementById("ObjOutput").InnerHtml;
                        string  json_output         = WebUtility.HtmlDecode(json_output_encoded);
                        JObject json = JObject.Parse(json_output);

                        // Pull out the inlines
                        {
                            Logging.Info("Pulling out the inlines");
                            foreach (var inline in json["inlines"])
                            {
                                string key = (string)inline["citation"]["citationID"];
                                int    total_items_affected_by_key = inline["citation_output"].Count();
                                foreach (var citation_output in inline["citation_output"])
                                {
                                    int    position = (int)citation_output[0];
                                    string text     = (string)citation_output[1];

                                    SetInline(key, position, text, total_items_affected_by_key);
                                }
                            }
                        }

                        // Pull out the bibliography
                        {
                            Logging.Info("Pulling out the bibliography settings");

                            // Do these results lack a bibliography?
                            JToken has_bibliography = json["bibliography"] as JToken;
                            if (null != has_bibliography && JTokenType.Boolean == has_bibliography.Type)
                            {
                                Logging.Info("This style has no bibliography: json bibliography node is {0}", has_bibliography);
                            }
                            else
                            {
                                var settings = json["bibliography"][0];
                                SetBibliographySettings(
                                    (int)(settings["maxoffset"] ?? 0),
                                    (int)(settings["entryspacing"] ?? 0),
                                    (int)(settings["linespacing"] ?? 0),
                                    (int)(settings["hangingindent"] ?? 0),
                                    Convert.ToString(settings["second-field-align"] ?? ""),
                                    (string)(settings["bibstart"] ?? ""),
                                    (string)(settings["bibend"] ?? "")
                                    );

                                Logging.Info("Pulling out the bibliography");
                                var bibliography = json["bibliography"][1];
                                foreach (var bib in bibliography)
                                {
                                    SetBibliography((string)bib);
                                }
                            }
                        }

                        Logging.Debug特("Calling the BibliographyReadyDelegate");
                        success = true;
                        brd(this);
                        Logging.Debug特("Called the BibliographyReadyDelegate");
                    }

                    if (finished_processing)
                    {
                        // Clean up
                        if (null != web_browser)
                        {
                            Logging.Debug特("Disposing of web browser for InCite CSL processing");
                            web_browser.Dispose();
                            web_browser = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.Error(ex, "There was a problem in the callback from citeproc");
            }
        }
        /// <summary>
        /// このクラスでの実行すること。
        /// </summary>
        /// <param name="runChildren"></param>
        public override void Run(bool runChildren)
        {
            System.Text.RegularExpressions.Regex r  = new System.Text.RegularExpressions.Regex("<input [^>]*>");
            System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"(\w)*\s*=\s*" + "\"([^\"]*)\"");

            var p = this.GetAncestorRawler().OfType <Page>();

            if (p.Any() == false)
            {
                ReportManage.ErrReport(this, "上流にPageがありません");
                return;
            }
            var page = p.First();

            foreach (System.Text.RegularExpressions.Match item in r.Matches(GetText()))
            {
                var dic = GetParameter(item.Value);
                if (dic.ContainsKey("type") && dic["type"] == "radio")
                {
                    if (dic.ContainsKey("name") && dic.ContainsKey("value") && dic.ContainsKey("checked"))
                    {
                        page.AddParameter(dic["name"], dic["value"]);
                    }
                }
                else if (dic.ContainsKey("type") && dic["type"] == "submit")
                {
                }
                else if (dic.ContainsKey("type") && dic["type"] == "text")
                {
                    if (dic.ContainsKey("name") && dic.ContainsKey("value"))
                    {
                        page.AddParameter(dic["name"], dic["value"]);
                    }
                }
                else if (dic.ContainsKey("type") && dic["type"] == "hidden")
                {
                    if (dic.ContainsKey("name") && dic.ContainsKey("value"))
                    {
                        page.AddParameter(dic["name"], dic["value"]);
                    }
                }
                else
                {
                    //if (dic.ContainsKey("name") && dic.ContainsKey("value"))
                    //{
                    //    page.AddParameter(dic["name"], dic["value"]);
                    //}
                }
            }
            foreach (var item in GetText().ToHtml().GetTag("select"))
            {
                var para    = GetParameter(item.Parameter);
                var seleted = item.Inner.ToHtml().GetTag("option").Where(n => n.Parameter.Contains("selected"));
                if (para.ContainsKey("name"))
                {
                    string val = string.Empty;
                    if (seleted != null && seleted.Any())
                    {
                        val = GetParameter(seleted.First().Parameter).GetValueOrDefault("value", string.Empty);
                    }
                    else
                    {
                        if (para.ContainsKey("value"))
                        {
                            val = para["value"];
                        }
                    }
                    page.AddParameter(para["name"], val);
                }
            }
            foreach (var item in GetText().ToHtml().GetTag("textarea"))
            {
                var para = GetParameter(item.Parameter);
                if (para.ContainsKey("name"))
                {
                    string val = string.Empty;
                    if (para.ContainsKey("value"))
                    {
                        val = para["value"];
                    }
                    page.AddParameter(para["name"], val);
                }
            }

            base.Run(runChildren);
        }
Example #34
0
        public override void Run()
        {
            var webDriver = GetWebDriver(Parameters.WebDriver);

            webDriver.Url = Parameters.ItemUrl;

            try
            {
                // ファイル読み込み
                List <string> lines = System.IO.File.ReadLines(_parameters.JanCodeFileName, Encoding.GetEncoding("shift-jis")).ToList();

                // 情報取得
                List <SearchResul> results = new List <SearchResul>();
                foreach (var line in lines)
                {
                    if (CancelToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var result = new SearchResul();
                    results.Add(result);
                    result.JanCode = line;

                    try
                    {
                        // 検索実行
                        webDriver.FindElementById("q").SendKeys(line);
                        webDriver.FindElementById("UPPER_SEARCH").Click();

                        var productName = webDriver.FindElementsById("DISP_GOODS_NM");
                        if (productName.Count == 0)
                        {
                            result.OnlineStock = "商品登録なし";
                            continue;
                        }
                        else
                        {
                            result.ProductName = productName.First().Text;
                        }
                        var stock = webDriver.FindElementsById("isStock");
                        if (0 < stock.Count)
                        {
                            result.OnlineStock = stock.First().Text;
                        }
                        else
                        {
                            result.OnlineStock = "-";
                        }

                        var currentHandle = webDriver.CurrentWindowHandle;

                        bool   switchSuccess = false;
                        string lastHandle    = "";

                        try
                        {
                            // 店舗在庫取得
                            webDriver.FindElementById("StockSearchButton").Click();

                            lastHandle = webDriver.WindowHandles.Last();
                            webDriver.SwitchTo().Window(lastHandle);
                            switchSuccess = true;

                            int existCount     = _exist.Matches(webDriver.PageSource).Count;
                            int lessExistCount = _lessExist.Matches(webDriver.PageSource).Count;
                            result.StoreStockCount     = existCount;
                            result.StoreLessStockCount = lessExistCount;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            if (switchSuccess)
                            {
                                webDriver.Close();
                            }
                            webDriver.SwitchTo().Window(currentHandle);
                        }
                    }
                    catch (Exception ex)
                    {
                        ReportStatus(EC_SITE, ex.ToString(), ReportState.Warning);
                    }
                }

                // ファイル出力
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("JANコード,商品名,オンライン在庫,店舗在庫あり数,店舗在庫わずか数");
                foreach (var result in results)
                {
                    sb.AppendLine($"{result.JanCode},{result.ProductName},{result.OnlineStock},{result.StoreStockCount},{result.StoreLessStockCount}");
                }
                if (0 < results.Count)
                {
                    System.IO.File.WriteAllText(_parameters.OutputFilePath, sb.ToString());
                }

                ReportStatus(EC_SITE, "終了", ReportState.Information);
            }
            catch (Exception ex)
            {
                ReportStatus(EC_SITE, ex.ToString(), ReportState.Exception);
            }
            finally
            {
                webDriver.Quit();
            }
        }
Example #35
0
        public void LoadDeepSearch(object state)
        {
            if (LocalDatabase.problemList == null)
            {
                return;
            }

            _InDeepSearch = true;

            //clear data
            _deepSearchRes.Clear();
            _DeepSearchProgress = 0;

            //set data
            this.BeginInvoke((MethodInvoker) delegate
            {
                allProbButton.Checked            = false;
                markedButton.Checked             = false;
                plistLabel.Text                  = "Deep Search Result";
                problemListView.AdditionalFilter = null;

                searchBox1.search_text.ReadOnly          = true;
                cancelDeepSearchButton.Visible           = true;
                problemViewSplitContainer.Panel1.Enabled = false;

                _SetObjects(_deepSearchRes);
                problemListView.Sort(priorityProb, SortOrder.Descending);
            });

            //search string
            string src = (string)state;

            if (!src.StartsWith("*"))
            {
                src = "\\b" + src;
            }
            if (!src.EndsWith("*"))
            {
                src += "\\b";
            }
            var regex = new System.Text.RegularExpressions.Regex(src,
                                                                 System.Text.RegularExpressions.RegexOptions.Compiled |
                                                                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            //search
            foreach (ProblemInfo prob in LocalDatabase.problemList)
            {
                if (_CancelSearch)
                {
                    break;
                }
                prob.Priority = 0;

                //search in problem data
                prob.Priority += regex.Matches(prob.ToString()).Count;

                //search in problem description
                try
                {
                    string file = LocalDirectory.GetProblemHtml(prob.pnum);
                    if (LocalDirectory.GetFileSize(file) > 100)
                    {
                        var hdoc = new HtmlAgilityPack.HtmlDocument();
                        hdoc.Load(file);
                        string dat = hdoc.DocumentNode.Element("body").InnerText;
                        //string dat = System.IO.File.ReadAllText(file);
                        prob.Priority += regex.Matches(dat).Count;
                    }
                }
                catch { }

                //add to list
                if (prob.Priority > 0)
                {
                    _deepSearchRes.Add(prob);
                }
                _DeepSearchProgress++;
            }

            //complete
            _InDeepSearch = false;
            this.BeginInvoke((MethodInvoker) delegate
            {
                _SetObjects(_deepSearchRes);

                searchBox1.search_text.ReadOnly          = false;
                cancelDeepSearchButton.Visible           = false;
                problemViewSplitContainer.Panel1.Enabled = true;

                if (_CancelSearch) //if canceled
                {
                    ClearSearch();
                }
            });
        }
Example #36
0
        private async Task <ExecValue> executeNativeRegexFunctionAsync(ExecutionContext ctx, FunctionDefinition func,
                                                                       ObjectData thisValue)
        {
            if (func == ctx.Env.RegexContainsFunction)
            {
                ObjectData arg     = ctx.FunctionArguments.Single();
                ObjectData arg_val = arg.DereferencedOnce();
                string     arg_str = arg_val.NativeString;

                ObjectData pattern_obj = thisValue.GetField(ctx.Env.RegexPatternField);
                ObjectData pattern_val = pattern_obj.DereferencedOnce();
                string     pattern     = pattern_val.NativeString;

                bool val = new System.Text.RegularExpressions.Regex(pattern).IsMatch(arg_str);

                ExecValue result = ExecValue.CreateReturn(await ObjectData.CreateInstanceAsync(ctx,
                                                                                               func.ResultTypeName.Evaluation.Components, val).ConfigureAwait(false));
                return(result);
            }
            else if (func == ctx.Env.RegexMatchFunction)
            {
                ObjectData arg     = ctx.FunctionArguments.Single();
                ObjectData arg_val = arg.DereferencedOnce();
                string     arg_str = arg_val.NativeString;

                ObjectData pattern_obj = thisValue.GetField(ctx.Env.RegexPatternField);
                ObjectData pattern_val = pattern_obj.DereferencedOnce();
                string     pattern     = pattern_val.NativeString;

                System.Text.RegularExpressions.Regex           regex   = new System.Text.RegularExpressions.Regex(pattern);
                System.Text.RegularExpressions.MatchCollection matches = regex.Matches(arg_str);

                var elements = new List <ObjectData>();
                for (int match_idx = 0; match_idx < matches.Count; ++match_idx)
                {
                    System.Text.RegularExpressions.Match match = matches[match_idx];
                    ObjectData match_start_val = await createNat64Async(ctx, (UInt64)match.Index).ConfigureAwait(false);

                    ObjectData match_end_val = await createNat64Async(ctx, (UInt64)(match.Index + match.Length)).ConfigureAwait(false);

                    ObjectData array_captures_ptr;

                    {
                        if (!ctx.Env.DereferencedOnce(ctx.Env.MatchCapturesProperty.TypeName.Evaluation.Components,
                                                      out IEntityInstance array_captures_type, out bool dummy))
                        {
                            throw new Exception($"Internal error {ExceptionCode.SourceInfo()}");
                        }

                        ExecValue ret = await createObject(ctx, true, array_captures_type, ctx.Env.ArrayDefaultConstructor, null)
                                        .ConfigureAwait(false);

                        if (ret.IsThrow)
                        {
                            return(ret);
                        }

                        array_captures_ptr = ret.ExprValue;
                        ctx.Heap.TryInc(ctx, array_captures_ptr, RefCountIncReason.StoringLocalPointer, "");

                        // skipping implicit "everything" group
                        for (int grp_idx = 1; grp_idx < match.Groups.Count; ++grp_idx)
                        {
                            System.Text.RegularExpressions.Group group = match.Groups[grp_idx];
                            string group_name = regex.GroupNameFromNumber(grp_idx);
                            if (group_name == $"{grp_idx}") // hack for anonymous captures
                            {
                                group_name = null;
                            }

                            for (int cap_idx = 0; cap_idx < group.Captures.Count; ++cap_idx)
                            {
                                System.Text.RegularExpressions.Capture cap = group.Captures[cap_idx];

                                ObjectData cap_start_val = await createNat64Async(ctx, (UInt64)cap.Index).ConfigureAwait(false);

                                ObjectData cap_end_val = await createNat64Async(ctx, (UInt64)(cap.Index + cap.Length)).ConfigureAwait(false);

                                ObjectData cap_opt_name_val;
                                {
                                    Option <ObjectData> opt_group_name_obj;
                                    if (group_name != null)
                                    {
                                        ObjectData str_ptr = await createStringAsync(ctx, group_name).ConfigureAwait(false);

                                        opt_group_name_obj = new Option <ObjectData>(str_ptr);
                                    }
                                    else
                                    {
                                        opt_group_name_obj = new Option <ObjectData>();
                                    }

                                    IEntityInstance opt_cap_type = ctx.Env.CaptureConstructor.Parameters.Last().TypeName.Evaluation.Components;
                                    ExecValue       opt_exec     = await createOption(ctx, opt_cap_type, opt_group_name_obj).ConfigureAwait(false);

                                    if (opt_exec.IsThrow)
                                    {
                                        return(opt_exec);
                                    }
                                    cap_opt_name_val = opt_exec.ExprValue;
                                }
                                ExecValue capture_obj_exec = await createObject(ctx, false, ctx.Env.CaptureType.InstanceOf,
                                                                                ctx.Env.CaptureConstructor, null, cap_start_val, cap_end_val, cap_opt_name_val).ConfigureAwait(false);

                                if (capture_obj_exec.IsThrow)
                                {
                                    return(capture_obj_exec);
                                }
                                ObjectData capture_ref = await capture_obj_exec.ExprValue.ReferenceAsync(ctx).ConfigureAwait(false);

                                ExecValue append_exec = await callNonVariadicFunctionDirectly(ctx, ctx.Env.ArrayAppendFunction, null,
                                                                                              array_captures_ptr, capture_ref).ConfigureAwait(false);

                                if (append_exec.IsThrow)
                                {
                                    return(append_exec);
                                }
                            }
                        }
                    }
                    ObjectData match_val;
                    {
                        ExecValue ret = await createObject(ctx, false, ctx.Env.MatchType.InstanceOf,
                                                           ctx.Env.MatchConstructor, null, match_start_val, match_end_val, array_captures_ptr).ConfigureAwait(false);

                        ctx.Heap.TryRelease(ctx, array_captures_ptr, null, false, RefCountDecReason.DroppingLocalPointer, "");

                        if (ret.IsThrow)
                        {
                            return(ret);
                        }

                        match_val = ret.ExprValue;
                    }

                    elements.Add(match_val);
                }

                ObjectData heap_chunk = await createChunkOnHeap(ctx, ctx.Env.MatchType.InstanceOf, elements).ConfigureAwait(false);

                ExecValue result = ExecValue.CreateReturn(heap_chunk);
                return(result);
            }
            else
            {
                throw new NotImplementedException($"{ExceptionCode.SourceInfo()}");
            }
        }