Ejemplo n.º 1
0
    public static void Main()
    {
        RegexCompilationInfo        expr;
        List <RegexCompilationInfo> compilationList = new List <RegexCompilationInfo>();

        // Define regular expression to detect duplicate words
        expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b",
                                        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
                                        "DuplicatedString",
                                        "Utilities.RegularExpressions",
                                        true);
        // Add info object to list of objects
        compilationList.Add(expr);

        // Define regular expression to validate format of email address
        expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" +
                                        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$",
                                        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
                                        "EmailAddress",
                                        "Utilities.RegularExpressions",
                                        true);
        // Add info object to list of objects
        compilationList.Add(expr);

        // Generate assembly with compiled regular expressions
        RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
        AssemblyName           assemName        = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

        compilationList.CopyTo(compilationArray);
        Regex.CompileToAssembly(compilationArray, assemName);
    }
Ejemplo n.º 2
0
        public override RegexCompilationInfo CreateRegexCompilationInfo()
        {
            StringBuilder patternBuilder = new StringBuilder();

            patternBuilder.Append(@"(?<format>(Dialogue|Comment|Picture|Sound|Movie|Command)):\s");
            patternBuilder.Append(@"(?<layer>\d+),");//(?<layer>\d+?),
            patternBuilder.Append(@"(?<start>\d{1,2}:\d{2}:\d{2}\.\d{2}),");
            patternBuilder.Append(@"(?<end>\d{1,2}:\d{2}:\d{2}\.\d{2}),");
            patternBuilder.Append(@"(?<style>.*),"); //(?<style>.*?),
            patternBuilder.Append(@"(?<name>.*),");  //(?<name>.*?),
            patternBuilder.Append(@"(?<marginL>\d{1,4}),");
            patternBuilder.Append(@"(?<marginR>\d{1,4}),");
            patternBuilder.Append(@"(?<marginV>\d{1,4}),");
            patternBuilder.Append(@"(?<effect>.*),");           //(?<effect>.*?),
            patternBuilder.Append(@"(?<text>.*(\r\n|\r|\n)?)"); //(?<text>.*(?>\r\n?|\r|\n))     ----------> ? czy to działać będzie?

            String regexName = "AssEventEntryRegex";

            String regexNamespace = "SubeditorRegexLib";

            RegexCompilationInfo info = new RegexCompilationInfo(
                patternBuilder.ToString(),
                RegexOptions.None,
                regexName,
                regexNamespace,
                true);

            return(info);
        }
Ejemplo n.º 3
0
    public static void Main(string[] args)
    {
        string name;
        string rxname;
        string rxtext;
        var    rcilist = new List <RegexCompilationInfo>();

        if (args.Length > 1)
        {
            name = args[0];
            for (var i = 1; i < args.Length; i++)
            {
                rxtext = args[i];
                rxname = string.Format("rx{0}", i);
                var rci = new RegexCompilationInfo(
                    rxtext,
                    RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
                    rxname,
                    "Utilities.RegularExpressions",
                    true
                    );
                rcilist.Add(rci);
                Console.WriteLine("added '{0}'", rxname);
            }
            Console.WriteLine("now compiling to assembly '{0}' ...", name);
            RegexToAssembly(rcilist, name);
            Console.WriteLine("done");
        }
        else
        {
            Console.WriteLine("usage: <name-of-assembly> <regex> [<another-regex ...>]");
        }
    }
    private void TestReflectionEmitIsNotPropagated()
    {
        ReflectionPermission perm = new ReflectionPermission(ReflectionPermissionFlag.ReflectionEmit);

        perm.Deny();
        RegexCompilationInfo[] compiles;
        AssemblyName           asmName;

        compiles     = new RegexCompilationInfo[1];
        compiles[0]  = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
        asmName      = new AssemblyName();
        asmName.Name = "RegexPatAsm2";
        Regex.CompileToAssembly(compiles, asmName);
        if (File.Exists("RegexPatAsm2.dll"))
        {
            File.Delete("RegexPatAsm2.dll");
        }
        Debug.WriteLine(String.Format("Finished with regex"));
        String       g       = "tempfile" + Guid.NewGuid().ToString();
        AssemblyName asmname = new AssemblyName();

        asmname.Name = g;
        AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain().
                                   DefineDynamicAssembly(asmname, AssemblyBuilderAccess.RunAndSave);

        Debug.WriteLine(String.Format("AssemblyBuilder created, {0}", asmbuild));
        ModuleBuilder mod = asmbuild.DefineDynamicModule("Mod1", asmname.Name + ".exe");

        Debug.WriteLine(String.Format("Module created, {0}", mod));
        throw new Exception("We shouldn't have gotten this far");
    }
Ejemplo n.º 5
0
        public void CompileToAssembly_Deny_FileIOPermission()
        {
            RegexCompilationInfo info = new RegexCompilationInfo(String.Empty, RegexOptions.None, "name", String.Empty, false);

            Regex.CompileToAssembly(new RegexCompilationInfo[1] {
                info
            }, aname, null, null);
        }
Ejemplo n.º 6
0
    public static void RegexToAssembly(List <RegexCompilationInfo> rcilist, string name)
    {
        var comparr = new RegexCompilationInfo[rcilist.Count];
        var asmname = new AssemblyName(string.Format("{0}, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null", name));

        rcilist.CopyTo(comparr);
        Regex.CompileToAssembly(comparr, asmname);
    }
Ejemplo n.º 7
0
        public void CompileToAssembly_PermitOnly_ControlEvidence()
        {
            RegexCompilationInfo info = new RegexCompilationInfo(String.Empty, RegexOptions.None, "name", String.Empty, false);

            Regex.CompileToAssembly(new RegexCompilationInfo[1] {
                info
            }, aname, null, null);
        }
Ejemplo n.º 8
0
        private void CompileAssembly(string asmFileNm, string Nmspc, string classNm, string protLvl, bool allDocs)
        {
            char[] invalidClassChars = new char[] { '*', ' ', '#', '$', '%', '(', ')', '@', '!', '[', ']', '{', '}', '<', '>', ',', ';', '.' };

            try
            {
                if (this.dockPanel.DocumentsCount < 1)
                {
                    throw new Exception("No open documents.");
                }

                List <RegexCompilationInfo> lstRgxInfos = new List <RegexCompilationInfo>();

                if (allDocs)
                {
                    foreach (WeifenLuo.WinFormsUI.Docking.IDockContent iRgxDoc in this.dockPanel.Documents)
                    {
                        frmRgxDoc doc = (iRgxDoc as frmRgxDoc);

                        if (doc == null)
                        {
                            continue;
                        }

                        string rgxText = doc.RegExText;
                        string rgxName = System.IO.Path.GetFileNameWithoutExtension(RainstormStudios.rsString.RemoveChars(doc.Text, invalidClassChars));
                        System.Text.RegularExpressions.RegexCompilationInfo compInfo = new RegexCompilationInfo(rgxText, this.GetRegExOpts(), rgxName, Nmspc, (protLvl.ToLower() == "public"));
                        lstRgxInfos.Add(compInfo);
                    }
                }
                else
                {
                    frmRgxDoc doc = (this.dockPanel.ActiveDocument as frmRgxDoc);
                    if (doc == null)
                    {
                        throw new Exception("No active document.");
                    }

                    string rgxText = doc.RegExText;
                    string rgxName = RainstormStudios.rsString.RemoveChars(doc.Text, invalidClassChars);
                    System.Text.RegularExpressions.RegexCompilationInfo compInfo = new RegexCompilationInfo(rgxText, this.GetRegExOpts(), rgxName, Nmspc, (protLvl.ToLower() == "public"));
                }

                System.Reflection.AssemblyName asmName = new System.Reflection.AssemblyName();
                asmName.CultureInfo          = System.Globalization.CultureInfo.CurrentCulture;
                asmName.Name                 = System.IO.Path.GetFileNameWithoutExtension(asmFileNm);
                asmName.Version              = new Version(1, 0);
                asmName.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameProcess;

                Regex.CompileToAssembly(lstRgxInfos.ToArray(), asmName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "An unexpected error has occured while trying to create the regular expression assembly:\n\n" + ex.Message + "\n\nApplication Version: " + Application.ProductVersion, "Unexpected Error");
            }
        }
Ejemplo n.º 9
0
        /// <summary>Creates the regular expressions that are used by the IbanValidator.</summary>
        /// <returns>The constructed regular expressions.</returns>
        private static IEnumerable <RegexCompilationInfo> CreateIbanExpressions()
        {
            RegexCompilationInfo ibanRegex = new RegexCompilationInfo(@"^(?<countrycode>[A-Z]{2})(?<check_digits>\d{2})(?<accountid>[A-Z0-9]{1,30})$",
                                                                      RegexOptions.Singleline,
                                                                      "IbanValidatorRegex",
                                                                      "Enkoni.Framework.Validation.RegularExpressions",
                                                                      true);

            return(new RegexCompilationInfo[] { ibanRegex });
        }
Ejemplo n.º 10
0
        public void Constructor()
        {
            RegexCompilationInfo info = new RegexCompilationInfo(String.Empty, RegexOptions.None, "name", String.Empty, false);

            Assert.AreEqual(String.Empty, info.Pattern, "Pattern");
            Assert.AreEqual(RegexOptions.None, info.Options, "Options");
            Assert.AreEqual("name", info.Name, "Name");
            Assert.AreEqual(String.Empty, info.Namespace, "Namespace");
            Assert.IsFalse(info.IsPublic, "IsPublic");
        }
Ejemplo n.º 11
0
        public Assembly Compile(string assemblyname)
        {
            var compilationList = this.patterns.Select(pattern => new RegexCompilationInfo(pattern.Value, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, pattern.Key, assemblyname + ".RegularExpressions", true)).ToList();
            // Generate assembly with compiled regular expressions
            var compilationArray = new RegexCompilationInfo[compilationList.Count];
            var assemName        = new AssemblyName(assemblyname + ", Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

            compilationList.CopyTo(compilationArray);
            Regex.CompileToAssembly(compilationArray, assemName);
            return(Assembly.Load(assemName));
        }
Ejemplo n.º 12
0
        public void Constructor_InvalidRegexOptions()
        {
            RegexOptions         options = (RegexOptions)Int32.MinValue;
            RegexCompilationInfo info    = new RegexCompilationInfo("pattern", options, "name", "fullnamespace", true);

            Assert.AreEqual("pattern", info.Pattern, "Pattern");
            Assert.AreEqual(options, info.Options, "Options");
            Assert.AreEqual("name", info.Name, "Name");
            Assert.AreEqual("fullnamespace", info.Namespace, "Namespace");
            Assert.IsTrue(info.IsPublic, "IsPublic");
        }
Ejemplo n.º 13
0
        private List <RegexCompilationInfo> GetRegexCompilation()
        {
            RegexOptions defaultRegexOptions = GetRegexOptions(Options);

            var regexList = new List <RegexCompilationInfo>();

            if (RegularExpressions == null)
            {
                return(regexList);
            }

            foreach (ITaskItem expression in RegularExpressions)
            {
                string name = expression.ItemSpec;

                string pattern = expression.GetMetadata("Pattern");
                string nspace  = expression.GetMetadata("Namespace");
                string options = expression.GetMetadata("Options");
                string pub     = expression.GetMetadata("IsPublic");

                if (string.IsNullOrEmpty(pattern))
                {
                    throw new InvalidOperationException(string.Format(
                                                            "The regular expression '{0}' is missing the Pattern metadata.", name));
                }

                if (string.IsNullOrEmpty(nspace))
                {
                    nspace = Namespace;
                }
                if (string.IsNullOrEmpty(nspace))
                {
                    nspace = Path.GetFileNameWithoutExtension(AssemblyName);
                }

                RegexOptions regexOptions = string.IsNullOrEmpty(options)
                                                ? defaultRegexOptions
                                                : GetRegexOptions(options);

                bool isPublic;

                if (!bool.TryParse(pub, out isPublic))
                {
                    isPublic = IsPublic;
                }

                var info = new RegexCompilationInfo(pattern, regexOptions, name, nspace, isPublic);
                regexList.Add(info);
            }

            return(regexList);
        }
        public void Compile()
        {
            var SentencePattern = new RegexCompilationInfo(@"[a-z]+(0)",
                                                           RegexOptions.Singleline,
                                                           "SentencePattern",
                                                           "Utilities.RegularExpressions",
                                                           true);

            var regexes      = new[] { SentencePattern };
            var assemblyName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

            Regex.CompileToAssembly(regexes, assemblyName);
        }
    private bool Compile()
    {
        AssemblyName assemName = new AssemblyName();

        assemName.Name = Path.GetFileNameWithoutExtension(txtFileName.Text);

        string       _regex  = AppContext.Instance.ActiveProject.Regex;
        RegexOptions options = AppContext.Instance.ActiveProject.Options;

        RegexCompilationInfo info = new RegexCompilationInfo(_regex, options, txtClass.Text, txtNamespace.Text, (listProtection.Text == "Public"));

        Regex.CompileToAssembly(new RegexCompilationInfo[] { info }, assemName);
        return(true);
    }
Ejemplo n.º 16
0
    public static void Main()
    {
        RegexCompilationInfo SentencePattern =
            new RegexCompilationInfo(@"\b(\w+((\r?\n)|,?\s))*\w+[.?:;!]",
                                     RegexOptions.Multiline,
                                     "SentencePattern",
                                     "Utilities.RegularExpressions",
                                     true);

        RegexCompilationInfo[] regexes   = { SentencePattern };
        AssemblyName           assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

        Regex.CompileToAssembly(regexes, assemName);
    }
Ejemplo n.º 17
0
        public static void CompileAndSaveRegex()
        {
            string allPattern = @"(kB|K[Bb]|K|M[Bb]|M|G[Bb]|G|B)";
            RegexCompilationInfo TermPattern = new RegexCompilationInfo(@"(?<=(\s|\b\d+))" + allPattern + @"\b",
                                                                        RegexOptions.Compiled,
                                                                        "TermPattern",
                                                                        "Utilities.RegularExpressions",
                                                                        true);

            RegexCompilationInfo[] regexes   = { TermPattern };
            AssemblyName           assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

            Regex.CompileToAssembly(regexes, assemName);
        }
    private void TestFileIOPermisssion()
    {
        FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);

        perm.Deny();
        RegexCompilationInfo[] compiles;
        AssemblyName           asmName;

        compiles     = new RegexCompilationInfo[1];
        compiles[0]  = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
        asmName      = new AssemblyName();
        asmName.Name = "RegexPatAsm3";
        Regex.CompileToAssembly(compiles, asmName);
    }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            //定义模式匹配字符串
            string pat = @"(\w+)\s+(car)";
            //建立正则式编译类实例
            RegexCompilationInfo rci = new RegexCompilationInfo(pat, RegexOptions.IgnoreCase, "CarRegex", "MyApp", true);
            //建立程序集合实例
            AssemblyName an = new AssemblyName();

            an.Name = "CarRegex_Cs";
            RegexCompilationInfo[] rcilist = { rci };
            //编译模式匹配字符串
            Regex.CompileToAssembly(rcilist, an);
            Console.WriteLine("RegexCompilationInfo's Namespace is {0}, Pattern is {1}", rci.Namespace, rci.Pattern);
        }
Ejemplo n.º 20
0
        /// <summary>Creates the regular expressions that are used by the EmailValidator.</summary>
        /// <returns>The constructed regular expressions.</returns>
        private static IEnumerable <RegexCompilationInfo> CreateEmailExpressions()
        {
            string commentPattern  = @"(?<comment{0}>(\(.*\))?)";
            string commentPattern1 = string.Format(CultureInfo.InvariantCulture, commentPattern, 1);
            string commentPattern2 = string.Format(CultureInfo.InvariantCulture, commentPattern, 2);

            /* Construct the regex for the domain part */
            /* ... for IP addresses */
            string ipAddressPattern = @"(?<ipAddress>\[.*\])";
            /* ... for domain names */
            string hostNamePattern   = @"(?<domain>(([a-zA-Z0-9]{1,63})|([a-zA-Z0-9][a-zA-Z0-9\-]{1,61}[a-zA-Z0-9]))(\.(([a-zA-Z0-9]{1,63})|([a-zA-Z0-9][a-zA-Z0-9\-]{1,61}[a-zA-Z0-9])))*)";
            string domainPartPattern = string.Format(CultureInfo.InvariantCulture, "^{0}({1}|{2}){3}$", commentPattern1, hostNamePattern, ipAddressPattern, commentPattern2);

            RegexCompilationInfo domainPartRegex = new RegexCompilationInfo(domainPartPattern,
                                                                            RegexOptions.Singleline,
                                                                            "EmailValidatorDomainPartRegex",
                                                                            "Enkoni.Framework.Validation.RegularExpressions",
                                                                            true);

            /* Construct the regexes for the local part */
            string allowedCharactersBasic            = @"a-zA-Z0-9\-_";
            string localPartBasicPattern             = string.Format(CultureInfo.InvariantCulture, @"^{0}[{1}]+(\.?[{1}])*{2}$", commentPattern1, allowedCharactersBasic, commentPattern2);
            RegexCompilationInfo localPartBasicRegex = new RegexCompilationInfo(localPartBasicPattern,
                                                                                RegexOptions.Singleline,
                                                                                "EmailValidatorLocalPartBasicRegex",
                                                                                "Enkoni.Framework.Validation.RegularExpressions",
                                                                                true);

            string allowedCharactersExtended            = allowedCharactersBasic + @"!#$%&'\*\+/=\?^`\{\|\}~";
            string localPartExtendedPattern             = string.Format(CultureInfo.InvariantCulture, @"^{0}[{1}]+(\.?[{1}])*{2}$", commentPattern1, allowedCharactersExtended, commentPattern2);
            RegexCompilationInfo localPartExtendedRegex = new RegexCompilationInfo(localPartExtendedPattern,
                                                                                   RegexOptions.Singleline,
                                                                                   "EmailValidatorLocalPartExtendedRegex",
                                                                                   "Enkoni.Framework.Validation.RegularExpressions",
                                                                                   true);

            string quotedPattern                        = string.Format(CultureInfo.InvariantCulture, "\"([{0}\\. \\(\\),:;\\<\\>@\\[\\]]*|(\\\")*|(\\\\\\\\)*)*\"", allowedCharactersExtended);
            string localPartCompletePattern             = string.Format(CultureInfo.InvariantCulture, @"^{0}(({1})|([{2}]+(\.(([{2}]+)|({1})\.[{2}]+))*)){3}$", commentPattern1, quotedPattern, allowedCharactersExtended, commentPattern2);
            RegexCompilationInfo localPartCompleteRegex = new RegexCompilationInfo(localPartCompletePattern,
                                                                                   RegexOptions.Singleline,
                                                                                   "EmailValidatorLocalPartCompleteRegex",
                                                                                   "Enkoni.Framework.Validation.RegularExpressions",
                                                                                   true);

            RegexCompilationInfo[] regexes = { domainPartRegex, localPartBasicRegex, localPartExtendedRegex, localPartCompleteRegex };

            return(regexes);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assmName"></param>
        public static void CreateRegExDLL(string assmName)
        {
            RegexCompilationInfo[] RE = new RegexCompilationInfo[2]
            {
                new RegexCompilationInfo("PATTERN", RegexOptions.Compiled,
                                         "CompiledPATTERN", "Chapter_Code", true),
                new RegexCompilationInfo("NAME", RegexOptions.Compiled,
                                         "CompiledNAME", "Chapter_Code", true)
            };

            System.Reflection.AssemblyName aName =
                new System.Reflection.AssemblyName();
            aName.Name = assmName;

            Regex.CompileToAssembly(RE, aName);
        }
Ejemplo n.º 22
0
        public static void Main()
        {
            RegexCompilationInfo HashTagPattern =
                new RegexCompilationInfo(@"#[A-Za-z0-9]{3,}",
                                         RegexOptions.None,
                                         "HashTagPattern",
                                         "VinylC.Common.Regex",
                                         true);

            RegexCompilationInfo[] regexes = { HashTagPattern };

            AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

            Regex.CompileToAssembly(regexes, assemName);

            Environment.Exit(0);
        }
Ejemplo n.º 23
0
        public override RegexCompilationInfo CreateRegexCompilationInfo()
        {
            String pattern = @"{(?<start>\d+)}{(?<end>\d+)}(?<text>.*(\r\n|\r|\n)?)";

            String regexName = "MicroDVDEntryRegex";

            String regexNamespace = "SubeditorRegexLib";

            RegexCompilationInfo info = new RegexCompilationInfo(
                pattern,
                RegexOptions.None,
                regexName,
                regexNamespace,
                true);

            return(info);
        }
Ejemplo n.º 24
0
        public override RegexCompilationInfo CreateRegexCompilationInfo()
        {
            String pattern = @"(?<start>\d{2}:\d{2}:\d{2}):(?<text>.*(\r\n|\r|\n)?)";

            String regexName = "TMPlayerEntryRegex";

            String regexNamespace = "SubeditorRegexLib";

            RegexCompilationInfo info = new RegexCompilationInfo(
                pattern,
                RegexOptions.None,
                regexName,
                regexNamespace,
                true);

            return(info);
        }
Ejemplo n.º 25
0
        public override RegexCompilationInfo CreateRegexCompilationInfo()
        {
            String pattern = @"(?<start>\d{2}:\d{2}:\d{2},\d{3})\s-->\s(?<end>\d{2}:\d{2}:\d{2},\d{3})";

            String regexName = "SubripTimingRegex";

            String regexNamespace = "SubeditorRegexLib";

            RegexCompilationInfo info = new RegexCompilationInfo(
                pattern,
                RegexOptions.None,
                regexName,
                regexNamespace,
                true);

            return(info);
        }
Ejemplo n.º 26
0
    static void Main(string[] args)
    {
        string       name        = args[0];
        string       nameSpace   = args[1];
        string       assmNameStr = args[2];
        string       regExString = args[3];
        RegexOptions options     = (RegexOptions)Convert.ToInt32(args[4]);

        RegexCompilationInfo info     = new RegexCompilationInfo(regExString, options, name, nameSpace, true);
        AssemblyName         assmName = new AssemblyName();

        assmName.Name = assmNameStr;

        Regex.CompileToAssembly(new RegexCompilationInfo[] { info }, assmName);

        Console.WriteLine("Regular expression successfully compiled to " + assmNameStr);
    }
Ejemplo n.º 27
0
        public RegexCompiledToAssemblySplitLines()
        {
            RegexCompilationInfo SentencePattern =
                new RegexCompilationInfo("\r\n|\r|\n",
                                         RegexOptions.Multiline,
                                         "SentencePattern",
                                         "Utilities.RegularExpressions",
                                         true);

            RegexCompilationInfo[] regexes   = { SentencePattern };
            AssemblyName           assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

            Regex.CompileToAssembly(regexes, assemName);
            var asm  = Assembly.Load(assemName);
            var type = asm.GetType("Utilities.RegularExpressions.SentencePattern");

            _regex = (Regex)Activator.CreateInstance(type);
        }
    private void TestReflectionEmit()
    {
        ReflectionPermission perm = new ReflectionPermission(ReflectionPermissionFlag.ReflectionEmit);

        perm.Deny();
        RegexCompilationInfo[] compiles;
        AssemblyName           asmName;

        compiles     = new RegexCompilationInfo[1];
        compiles[0]  = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
        asmName      = new AssemblyName();
        asmName.Name = "RegexPatAsm1";
        Regex.CompileToAssembly(compiles, asmName);
        if (File.Exists("RegexPatAsm1.dll"))
        {
            File.Delete("RegexPatAsm1.dll");
        }
    }
Ejemplo n.º 29
0
    public static void Main()
    {
        RegexCompilationInfo        expr;
        List <RegexCompilationInfo> compilationList = new List <RegexCompilationInfo>();

        // Define regular expression to detect duplicate words
        expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b",
                                        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
                                        "DuplicatedString",
                                        "Utilities.RegularExpressions",
                                        true);
        // Add info object to list of objects
        compilationList.Add(expr);

        // Define regular expression to validate format of email address
        expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" +
                                        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[zA-Z]{2,6}))$",
                                        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant,
                                        "EmailAddress",
                                        "Utilities.RegularExpressions",
                                        true);
        // Add info object to list of objects
        compilationList.Add(expr);

        // Apply AssemblyTitle attribute to the new assembly
        //
        // Define the parameter(s) of the AssemblyTitle attribute's constructor
        Type[] parameters = { typeof(string) };
        // Define the assembly's title
        object[] paramValues = { "General-purpose library of compiled regular expressions" };
        // Get the ConstructorInfo object representing the attribute's constructor
        ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(parameters);

        // Create the CustomAttributeBuilder object array
        CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, paramValues) };

        // Generate assembly with compiled regular expressions
        RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
        AssemblyName           assemName        = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");

        compilationList.CopyTo(compilationArray);
        Regex.CompileToAssembly(compilationArray, assemName, attBuilder);
    }
    public static void Main()
    {
        // Match two or more occurrences of the same character.
        string pattern = @"(\w)\1+";

        // Use case-insensitive matching.
        var rci = new RegexCompilationInfo(pattern, RegexOptions.IgnoreCase,
                                           "DuplicateChars", "CustomRegexes",
                                           true, TimeSpan.FromSeconds(2));

        // Define an assembly to contain the compiled regular expression.
        var an = new AssemblyName();

        an.Name = "RegexLib";
        RegexCompilationInfo[] rciList = { rci };

        // Compile the regular expression and create the assembly.
        Regex.CompileToAssembly(rciList, an);
    }
 public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname)
 {
 }
Ejemplo n.º 32
0
    private bool Compile()
    {
        AssemblyName   assemName = new AssemblyName();
        assemName.Name = Path.GetFileNameWithoutExtension(txtFileName.Text);

        string _regex = AppContext.Instance.ActiveProject.Regex;
        RegexOptions options = AppContext.Instance.ActiveProject.Options;

        RegexCompilationInfo   info = new RegexCompilationInfo(_regex, options, txtClass.Text, txtNamespace.Text, (listProtection.Text == "Public"));
        Regex.CompileToAssembly(new RegexCompilationInfo[] { info }, assemName);
        return true;
    }
Ejemplo n.º 33
0
 private void TestReflectionEmit()
   {		
   ReflectionPermission perm = new ReflectionPermission(ReflectionPermissionFlag.ReflectionEmit);
   perm.Deny();
   RegexCompilationInfo[] compiles;
   AssemblyName asmName;
   compiles = new RegexCompilationInfo[1];
   compiles[0] = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
   asmName = new AssemblyName();
   asmName.Name = "RegexPatAsm1";
   Regex.CompileToAssembly(compiles, asmName);
   if(File.Exists("RegexPatAsm1.dll"))
     File.Delete("RegexPatAsm1.dll");
   }
 public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile)
 {
 }
Ejemplo n.º 35
0
 private void TestReflectionEmitIsNotPropagated()
   {		
   ReflectionPermission perm = new ReflectionPermission(ReflectionPermissionFlag.ReflectionEmit);
   perm.Deny();
   RegexCompilationInfo[] compiles;
   AssemblyName asmName;
   compiles = new RegexCompilationInfo[1];
   compiles[0] = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
   asmName = new AssemblyName();
   asmName.Name = "RegexPatAsm2";
   Regex.CompileToAssembly(compiles, asmName);
   if(File.Exists("RegexPatAsm2.dll"))
     File.Delete("RegexPatAsm2.dll");
   Debug.WriteLine(String.Format("Finished with regex"));
   String g = "tempfile" + Guid.NewGuid().ToString();
   AssemblyName asmname = new AssemblyName();
   asmname.Name = g;
   AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain().
     DefineDynamicAssembly(asmname, AssemblyBuilderAccess.RunAndSave);   
   Debug.WriteLine(String.Format("AssemblyBuilder created, {0}", asmbuild));
   ModuleBuilder mod = asmbuild.DefineDynamicModule("Mod1", asmname.Name + ".exe" );
   Debug.WriteLine(String.Format("Module created, {0}", mod));
   throw new Exception("We shouldn't have gotten this far");
   }
Ejemplo n.º 36
0
 private void TestFileIOPermisssion()
   {		
   FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
   perm.Deny();
   RegexCompilationInfo[] compiles;
   AssemblyName asmName;
   compiles = new RegexCompilationInfo[1];
   compiles[0] = new RegexCompilationInfo(@"[a-z]+\d+", RegexOptions.None, "RegexPatOne", "RegexPatterns", true);
   asmName = new AssemblyName();
   asmName.Name = "RegexPatAsm3";
   Regex.CompileToAssembly(compiles, asmName);
   }