Esempio n. 1
0
 public static bool InputValidate(string InputStr, Pattern kind)
 {
     if ((InputStr.Trim() == "") || (InputStr == null))
         return false;
     else
     {
         Regex RegexPattern;
         switch (kind)
         {
             case Pattern.Pic_id:
                 RegexPattern = new Regex(@"([^'&%^!#*|?*+\t\n\r\\.]{3,20})$");
                 break;
             case Pattern.Email:
                 RegexPattern = new Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
                 break;
             case Pattern.Folder:
                 RegexPattern = new Regex(@"[\w]{2,15}$");
                 break;
             case Pattern.Telephone:
                 RegexPattern = new Regex(@"[\d-]{6,30}$");
                 break;
             case Pattern.Mobilephone:
                 RegexPattern = new Regex(@"[\d]{8,11}$");
                 break;
             case Pattern.IdentifyID:
                 RegexPattern = new Regex(@"[\d]{15,18}$");
                 break;
             case Pattern.Username:
                 RegexPattern = new Regex(@"[^'&%\^\?\t\n\r\\\*,\+]{2,20}$");
                 break;
             case Pattern.Password:
                 RegexPattern = new Regex(@"[\w]{6,20}$");
                 break;
             case Pattern.Noblank:
                 RegexPattern = new Regex(@"([^ ]+$");
                 break;
             case Pattern.Noand:
                 RegexPattern = new Regex(@"[^&\+]+$");
                 break;
             case Pattern.Noinject:
                 RegexPattern = new Regex(@"[^'&%\^\?\t\n\r\\\*\+]+$");
                 break;
             case Pattern.IsDate:
                 RegexPattern = new Regex(@"^([1-2]\d{3})[-](0?[1-9]|10|11|12)[\-]([1-2]?[0-9]|0[1-9]|30|31)$");
                 break;
             case Pattern.IsNumeric:
                 RegexPattern = new Regex(@"^[0-9.]+$");
                 break;
             case Pattern.IsASCIIText:
                 RegexPattern = new Regex(@"^[\w]+$");
                 break;
             case Pattern.IsGBText:
                 RegexPattern = new Regex(@"[^x00-xff']+$");
                 break;
             default:
                 return false;
         }
         return RegexPattern.IsMatch(InputStr);
     }
 }
		public void VerifyExecuteWithOneConditionalValue()
		{
			var text = "http://%1/$1";
			var pattern = new Pattern("/([a-z]+)/index.aspx", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var target = new DefaultRuleAction(pattern, text);

			var condTest = new DefaultConditionTestValue("%{HTTP_HOST}");
			var condPattern = new Pattern(".*", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var cond = MockCond(condPattern, condTest, null);

			Uri url = new Uri("http://www.managedfusion.com/success/index.aspx");
			var httpContext = HttpHelpers.MockHttpContext(url);
			httpContext.Request.SetServerVariables(new Dictionary<string, string> { 
				{ "HTTP_HOST", "www.managedfusion.com" } 
			});
			var rule = MockRule(new List<ICondition> { cond }, target, null);

			RuleContext context = CreateRuleContext(url, httpContext, rule);
			target.Execute(context);

			Uri result = context.SubstitutedUrl;
			Uri expected = new Uri("http://www.managedfusion.com/success");

			Assert.AreEqual(expected, result);
		}
		public void VerifyExecuteWithOneConditionalValue()
		{
			var text = "http://%1/$1";
			var pattern = new Pattern("/([a-z]+)/index.aspx", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var target = new DefaultOutputRuleAction(pattern, text);

			var condTest = new DefaultConditionTestValue("%{HTTP_HOST}");
			var condPattern = new Pattern(".*", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var cond = MockCond(condPattern, condTest, null);

			var httpContext = HttpHelpers.MockHttpContext(new Uri("http://www.managedfusion.com/success/index.aspx"));
			httpContext.Request.SetServerVariables(new Dictionary<string, string> { 
				{ "HTTP_HOST", "www.managedfusion.com" } 
			});
			string content = CreateHtmlContent(@"<a href=""/success/index.aspx"" target=""_blank"">Link</a>");
			var rule = MockRule(new List<ICondition> { cond }, target, null);

			RuleContext context = CreateOutputRuleContext(content.ToByteArray(), httpContext, rule);
			target.Execute(context);

			string result = context.SubstitutedContent.GetString();
			string expected = CreateHtmlContent(@"<a href=""http://www.managedfusion.com/success"" target=""_blank"">Link</a>");

			Assert.AreEqual(expected, result);
		}
Esempio n. 4
0
        //public static char[] Parse(string text,string separators)
        //{
        //    //string Result="";
        //    System.Text.StringBuilder Result=new System.Text.StringBuilder ();
        //    text= " " + text +" ";

        //    char c;

        //    for(int i = 0; i <text.Length;i++)
        //    {
        //        c = text[i];
        //        if (separators.IndexOf (c)>=0 )
        //            Result.Append (' ');
        //        else
        //            Result.Append ('.');
        //    }

        //    return Result.ToString().ToCharArray ();
        //}



        public static void AddPatternString(string text, Row row, Pattern pattern, TextStyle style, TextStyle matchingStyle, Segment segment, bool hasError)
        {
            Word x = row.Add(text);
            x.Style = style;
            x.MatchingStyle = matchingStyle;
            x.Pattern = pattern;
            x.HasError = hasError;
            x.Segment = segment;
        }
		public void InvertMatch_False()
		{
			string pattern = "^(www).*$";
			RegexOptions options = Manager.RuleOptions;
			Pattern target = new Pattern(pattern, options);

			bool actual = target.InvertMatch;

			Assert.AreEqual(false, actual);
		}
Esempio n. 6
0
        private static void Dump(string title, Pattern pattern)
        {
            var options = PatternOptions.FormatAndComment;

            if (!string.IsNullOrEmpty(title))
                Console.WriteLine($"{title}:");

            Console.WriteLine(pattern.ToString(options));
            Console.WriteLine(string.Empty);
        }
		public new void ToString()
		{
			string pattern = "!^(www).*$";
			RegexOptions options = Manager.RuleOptions;
			Pattern target = new Pattern(pattern, options);

			string expected = pattern;
			string actual = target.ToString();

			Assert.AreEqual(expected, actual);
		}
		public void ToString_True()
		{
			string pattern = "!^(www).*$";
			RegexOptions options = Manager.RuleOptions;
			Pattern target = new Pattern(pattern, options);

			bool showOnlyPattern = true;
			string expected = "^(www).*$";
			string actual = target.ToString(showOnlyPattern);

			Assert.AreEqual(expected, actual);
		}
		public void VerifyExecute()
		{
			var text = "/$1";
			var pattern = new Pattern("/([a-z]+)/index.aspx", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var target = new DefaultOutputRuleAction(pattern, text);

			var httpContext = HttpHelpers.MockHttpContext(new Uri("http://www.somesite.com/success/index.aspx"));
			string content = CreateHtmlContent(@"<a href=""http://www.somesite.com/success/index.aspx"" target=""_blank"">Link</a>");
			var rule = MockRule(null, target, null);

			RuleContext context = CreateOutputRuleContext(content.ToByteArray(), httpContext, rule);
			target.Execute(context);
			
			string result = context.SubstitutedContent.GetString();
			string expected = CreateHtmlContent(@"<a href=""http://www.somesite.com/success"" target=""_blank"">Link</a>");

			Assert.AreEqual(expected, result);
		}
		public void VerifyExecute()
		{
			var text = "/$1";
			var pattern = new Pattern("/([a-z]+)/index.aspx", RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var target = new DefaultRuleAction(pattern, text);

			Uri url = new Uri("http://www.somesite.com/success/index.aspx");
			var httpContext = HttpHelpers.MockHttpContext(url);
			var rule = MockRule(null, target, null);

			RuleContext context = CreateRuleContext(url, httpContext, rule);
			target.Execute(context);

			Uri result = context.SubstitutedUrl;
			Uri expected = new Uri("http://www.somesite.com/success");

			Assert.AreEqual(expected, result);
		}
		public void Replace_ServerVariable()
		{
			var url = new Uri("http://www.somesite.com/test.aspx");
			var httpContext = HttpHelpers.MockHttpContext(url);
			httpContext.Request.SetServerVariables(new Dictionary<string, string> { 
				{ "SERVER_PORT", "1234" } 
			});
			var context = CreateRuleContext(url, httpContext);
			string pattern = "^(.*)$";
			string input = "/test.aspx";
			string replacement = "/pass?port=%{SERVER_PORT}";
			RegexOptions options = Manager.RuleOptions;
			Pattern target = new Pattern(pattern, options);

			string result = Pattern.Replace(replacement, context);
			string expected = "/pass?port=1234";

			Assert.AreEqual(expected, result);
		}
Esempio n. 12
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="pattern"></param>
		/// <param name="test"></param>
		/// <param name="flags"></param>
		/// <returns></returns>
		public ICondition MockCond(Pattern pattern, IConditionTestValue test, IConditionFlagProcessor flags)
		{
			// create properties
			if (pattern == null)
				pattern = new Pattern(".*", RegexOptions.Singleline);

			if (test == null)
				test = new Mock<IConditionTestValue>().Object;

			if (flags == null)
				flags = new Mock<IConditionFlagProcessor>().Object;

			var condMock = new Mock<ICondition>();
			condMock.SetupGet(c => c.Pattern).Returns(pattern);
			condMock.SetupGet(c => c.Test).Returns(test);
			condMock.SetupGet(c => c.Flags).Returns(flags);
			var cond = condMock.Object;

			return cond;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="DefaultRuleAction"/> class.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="substitution"></param>
		public DefaultRuleAction(Pattern pattern, string substitution)
		{
			((IRuleAction)this).Init(pattern, substitution);
		}
Esempio n. 14
0
        Pattern And(Pattern p1, Pattern p2)
        {
            if (p1.Type == PatternType.NOT_ALLOWED)
            return p1;

              if (p2.Type == PatternType.NOT_ALLOWED)
            return p2;

              if (p1.Type == PatternType.AND)
            return And(p1.p1, And(p1.p2, p2));

              return Create(new Pattern() {
            p1 = p1,
            p2 = p2,
            Nullable = p1.Nullable && p2.Nullable,
            Type = PatternType.AND
              });
        }
Esempio n. 15
0
        Pattern Choice(Pattern p1, Pattern p2)
        {
            if (p1.Type == PatternType.NOT_ALLOWED)
            return p2;

              if (p2.Type == PatternType.NOT_ALLOWED)
            return p1;

              if (p1.Type == PatternType.CHOICE)
            return Choice(p1.p1, Choice(p1.p2, p2));

              for (var child = p2; true; child = child.p2) {
            if (child == p1)
              return p2;
            if (!(child.Type == PatternType.CHOICE))
              break;
            if (child.p1 == p1)
              return p2;
              }

              return Create(new Pattern() {
            p1 = p1,
            p2 = p2,
            Nullable = p1.Nullable || p2.Nullable,
            Type = PatternType.CHOICE
              });
        }
Esempio n. 16
0
        Pattern Group(Pattern p1, Pattern p2)
        {
            if (p1.Type == PatternType.NOT_ALLOWED)
            return p1;

              if (p2.Type == PatternType.NOT_ALLOWED)
            return p2;

              if (p1.Type == PatternType.EMPTY)
            return p2;

              if (p2.Type == PatternType.EMPTY)
            return p1;

              if (p1.Type == PatternType.GROUP)
            return Group(p1.p1, Group(p1.p2, p2));

              return Create(new Pattern() {
            p1 = p1,
            p2 = p2,
            Nullable = p1.Nullable && p2.Nullable,
            Type = PatternType.GROUP
              });
        }
Esempio n. 17
0
 Pattern Create(Pattern p)
 {
     if (cache.ContainsKey(p)) {
     return cache[p];
       }
       cache.Add(p, p);
       return p;
 }
Esempio n. 18
0
        public State Simulate(Pattern elem)
        {
            if (Seen.Contains(elem))
            return Pattern2State[elem];

              var ElemState = new State() { IsNullable = elem.Nullable };
              var root = elem;

              if (!Pattern2State.ContainsKey(root)) {
            Pattern2State.Add(root, ElemState);
              }

              Queue<Pattern> queue = new Queue<Pattern>();
              queue.Enqueue(root);

              var leaves = elem.DescendantNodesAndSelf().Where(x =>
            x.Type == PatternType.ATTRIBUTE ||
            x.Type == PatternType.REF).Distinct().ToList();

              while (queue.Count > 0) {
            var current = queue.Dequeue();
            var cstate = Pattern2State[current];

            if (Seen.Contains(current))
              continue;

            current.DescendantNodesAndSelf()
              .Where(x => x.Type == PatternType.DEFINE)
              .Where(x => x.Nullable)
              .ToList()
              .ForEach(x => cstate.NullableDefines.Add(x.Name));

            Seen.Add(current);

            foreach (var leaf in leaves) {

              var derived = Deriv(current, leaf);

              if (derived.Type == PatternType.NOT_ALLOWED)
            continue;

              if (!Pattern2State.ContainsKey(derived)) {
            Pattern2State.Add(derived, new State() { IsNullable = derived.Nullable });
            queue.Enqueue(derived);
              }

              var dstate = Pattern2State[derived];

              if (leaf.Type == PatternType.ATTRIBUTE) {
            if (leaf.Namespace.Length > 0)
              cstate.AttrStates.Add("{" + leaf.Namespace + "}" + leaf.Name, dstate);
            else
              cstate.AttrStates.Add(leaf.Name, dstate);
              }
              else if (leaf.Type == PatternType.REF) {
            cstate.ChildStates.Add(leaf.Name, dstate);
              }
            }
              }
              if (!Pattern2State.ContainsValue(ElemState))
            throw new Exception();
              return ElemState;
        }
Esempio n. 19
0
        internal static IEnumerable<PatternNode<Word, ShapeNode>> DeepCloneExceptBoundaries(this IEnumerable<PatternNode<Word, ShapeNode>> nodes)
        {
            foreach (PatternNode<Word, ShapeNode> node in nodes)
            {
                var constraint = node as Constraint<Word, ShapeNode>;
                if (constraint != null && (constraint.FeatureStruct.IsEmpty || constraint.Type() != HCFeatureSystem.Boundary))
                {
                    yield return constraint.DeepClone();
                    continue;
                }

                var alternation = node as Alternation<Word, ShapeNode>;
                if (alternation != null)
                {
                    var newAlteration = new Alternation<Word, ShapeNode>(alternation.Children.DeepCloneExceptBoundaries());
                    if (newAlteration.Children.Count > 0)
                        yield return newAlteration;
                    continue;
                }

                var group = node as Group<Word, ShapeNode>;
                if (group != null)
                {
                    var newGroup = new Group<Word, ShapeNode>(group.Name, group.Children.DeepCloneExceptBoundaries());
                    if (newGroup.Children.Count > 0)
                        yield return newGroup;
                    continue;
                }

                var quantifier = node as Quantifier<Word, ShapeNode>;
                if (quantifier != null)
                {
                    var newQuantifier = new Quantifier<Word, ShapeNode>(quantifier.MinOccur, quantifier.MaxOccur, quantifier.Children.DeepCloneExceptBoundaries().SingleOrDefault());
                    if (newQuantifier.Children.Count > 0)
                        yield return newQuantifier;
                    continue;
                }

                var pattern = node as Pattern<Word, ShapeNode>;
                if (pattern != null)
                {
                    var newPattern = new Pattern<Word, ShapeNode>(pattern.Name, pattern.Children.DeepCloneExceptBoundaries());
                    if (newPattern.Children.Count > 0)
                        yield return newPattern;
                }
            }
        }
Esempio n. 20
0
 Pattern Define(string name, Pattern p)
 {
     return Create(new Pattern() {
     p1 = p,
     Name = name,
     Nullable = p.Nullable,
     Type = PatternType.DEFINE
       });
 }
Esempio n. 21
0
 XElement SerializePattern(Pattern p)
 {
     var elem = new XElement(Enum.GetName(typeof(PatternType), p.Type),
     p.Nodes().Select(x => SerializePattern(x)));
       elem.Add(new XAttribute("name", p.Name + ""),
        new XAttribute("ns", p.Namespace + ""),
        new XAttribute("nullable", p.Nullable));
       return elem;
 }
Esempio n. 22
0
        Pattern Deriv(Pattern p, Pattern c)
        {
            switch (p.Type) {
            case PatternType.NOT_ALLOWED:
              return p;
            case PatternType.EMPTY:
              return NotAllowed();
            case PatternType.REF:
              return c.Type == PatternType.REF &&
            p.Name == c.Name ? Empty() : NotAllowed();
            case PatternType.ONE_OR_MORE:
              return Group(Deriv(p.p1, c), Optional(p));
            case PatternType.CHOICE:
              return Choice(Deriv(p.p1, c), Deriv(p.p2, c));
            case PatternType.AND:
              return And(Deriv(p.p1, c), Deriv(p.p2, c));
            case PatternType.NOT:
              return Not(Deriv(p.p1, c));
            case PatternType.GROUP:

              if (c.Type == PatternType.ATTRIBUTE)
            return Choice(Group(Deriv(p.p1, c), p.p2),
              Group(p.p1, Deriv(p.p2, c)));

              if (p.p1.Nullable)
            return Choice(Deriv(p.p2, c), Group(Deriv(p.p1, c), p.p2));
              return Group(Deriv(p.p1, c), p.p2);

            case PatternType.TEXT:
              return NotAllowed();
            case PatternType.ATTRIBUTE:
              return c.Type == PatternType.ATTRIBUTE &&
            p.Name == c.Name ? Optional(p) : NotAllowed();
            case PatternType.INTERLEAVE:
              return Choice(Interleave(Deriv(p.p1, c), p.p2),
            Interleave(p.p1, Deriv(p.p2, c)));
            case PatternType.DEFINE:
              return Define(p.Name, Deriv(p.p1, c));

            case PatternType.ANYNAME:
              return p;
            case PatternType.LNNAME:
              return c.Type == PatternType.LNNAME &&
            c.Name == p.Name ? Empty() : NotAllowed();
            case PatternType.NSNAME:
              return c.Type == PatternType.NSNAME &&
            c.Namespace == p.Namespace ? Empty() : NotAllowed();

            default:
              throw new Exception();
              }
        }
Esempio n. 23
0
 Pattern Not(Pattern p)
 {
     return Create(new Pattern() {
     p1 = p,
     Nullable = !p.Nullable,
     Type = PatternType.NOT
       });
 }
Esempio n. 24
0
        Pattern Interleave(Pattern p1, Pattern p2)
        {
            if (p1.Type == PatternType.NOT_ALLOWED)
            return p1;

              if (p2.Type == PatternType.NOT_ALLOWED)
            return p2;

              if (p1.Type == PatternType.EMPTY)
            return p2;

              if (p2.Type == PatternType.EMPTY)
            return p1;

              if (p1.Type == PatternType.INTERLEAVE)
            return Group(p1.p1, Group(p1.p2, p2));

              return Create(new Pattern() {
            p1 = p1,
            p2 = p2,
            Nullable = p1.Nullable && p2.Nullable,
            Type = PatternType.INTERLEAVE
              });
        }
		/// <summary>
		/// Inits the specified text.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="substitution"></param>
		void IRuleAction.Init(Pattern pattern, string substitution)
		{
			_pattern = pattern;
			_substitution = substitution;
		}
		/// <summary>
		/// Refreshes the rules.
		/// </summary>
		/// <param name="reader">The reader.</param>
		public void RefreshRules(TextReader reader)
		{
			// put a lock on the refresh process so that only one refresh can happen at a time
			lock (_refreshLock)
			{
				Manager.LogEnabled = false;
				Manager.LogPath = null;

				string tempBase = PhysicalBase;
				string tempLogPath = null;
				int tempLogLevel = 0;
				int tempMaxInternalTransfers = 10;
				bool tempEngineEnabled = false;

				string line;
				IList<ICondition> conditions = new List<ICondition>(0);
				IList<IRule> rules = new List<IRule>();
				IList<IRule> outputRules = new List<IRule>();
				IList<string> unknownLines = new List<string>();
				ModuleFactory modules = new ModuleFactory();

				while (reader.Peek() >= 0)
				{
					line = reader.ReadLine().Trim();

					if (String.IsNullOrEmpty(line))
					{
						// just plain old ignore empty lines no logging or anything
						continue;
					}
					else if (line[0] == '#')
					{
						Manager.LogIf(tempLogLevel >= 4, "Comment: " + line, "Rule Processing");
					}
					else if (RewriteEngineLine.IsMatch(line))
					{
						#region RewriteEngine

						Match match = RewriteEngineLine.Match(line);
						string engineState = match.Groups["state"].Value;

						// by default the engine is turned off
						if (String.IsNullOrEmpty(engineState) || String.Equals(engineState, "off", StringComparison.OrdinalIgnoreCase))
						{
							rules.Clear();
							tempEngineEnabled = false;

							// don't bother processing any other rules if the engine is disabled
							break;
						}
						else
						{
							tempEngineEnabled = true;
						}

						Manager.LogIf(tempLogLevel >= 3, "RewriteEngine: " + (tempEngineEnabled ? "Enabled" : "Disabled"), "Rule Processing");

						#endregion
					}
					else if (RewriteOptionsLine.IsMatch(line))
					{
						#region RewriteOptions

						Match match = RewriteOptionsLine.Match(line);
						Group variables = match.Groups["var"];

						if (variables.Success)
						{
							foreach (Capture var in variables.Captures)
							{
								string[] parts = var.Value.Split(new[] { '=' }, 2);
								bool variableUnderstood = false;

								if (parts.Length == 2)
								{
									switch (parts[0])
									{
										case "inherit":
											break;

										// obsolete in 2.1 mod_rewrite
										case "MaxRedirects":
											Manager.LogIf(tempLogLevel >= 1, "MaxRedirects is obsolete", "Obsolete");

											int maxInternalTransfers;
											if (Int32.TryParse(parts[1], out maxInternalTransfers))
											{
												tempMaxInternalTransfers = maxInternalTransfers;
												variableUnderstood = true;
											}
											break;
									}
								}

								if (!variableUnderstood)
									Manager.LogIf(tempLogLevel >= 4, "Not Understood: " + var.Value, "Unknown");
							}
						}

						#endregion
					}
					else if (RewriteBaseLine.IsMatch(line))
					{
						#region RewriteBase

						Match match = RewriteBaseLine.Match(line);
						tempBase = match.Groups["base"].Value;

						Manager.LogIf(tempLogLevel >= 3, "RewriteBase: " + VirtualBase, "Rule Processing");

						#endregion
					}
					else if (RewriteModuleLine.IsMatch(line))
					{
						#region RewriteModule

						Match match = RewriteModuleLine.Match(line);
						string moduleName = match.Groups["name"].Value;
						string moduleType = match.Groups["type"].Value;
						Type module = Type.GetType(moduleType, false, true);

						if (module == null)
							module = BuildManager.GetType(moduleType, false, true);

						if (module == null)
						{
							Manager.LogIf(tempLogLevel >= 3, "RewriteModule: Error finding " + moduleType, "Rule Processing");
						}
						else
						{
							// add the module to the list
							modules.AddModule(moduleName, module);

							Manager.LogIf(tempLogLevel >= 3, "RewriteModule: " + moduleType, "Rule Processing");
						}

						#endregion
					}
					else if (RewriteLogLine.IsMatch(line))
					{
						#region RewriteLog

						Match match = RewriteLogLine.Match(line);
						tempLogPath = match.Groups["location"].Value;
						tempLogPath = NormalizeLogLocation(tempLogPath);

						Manager.LogIf(tempLogLevel >= 3, "RewriteLog: " + tempLogPath, "Rule Processing");

						#endregion
					}
					else if (RewriteLogLevelLine.IsMatch(line))
					{
						#region RewriteLogLevel

						Match match = RewriteLogLevelLine.Match(line);
						int logLevel = 1;

						if (!Int32.TryParse(match.Groups["level"].Value, out logLevel))
						{
							tempLogLevel = 0;
							Manager.LogIf(tempLogLevel >= 3, "RewriteLogLevel: " + match.Groups["level"].Value + " not understood.", "Rule Processing");
						}
						else
						{
							tempLogLevel = logLevel;
						}

						Manager.LogIf(tempLogLevel >= 3, "RewriteLogLevel: " + logLevel, "Rule Processing");

						#endregion
					}
					else if (RewriteCondLine.IsMatch(line))
					{
						#region RewriteCond

						Match match = RewriteCondLine.Match(line);

						string module1 = match.Groups["module1"].Value;
						string module2 = match.Groups["module2"].Value;

						Type moduleType1 = null;
						Type moduleType2 = null;

						// set the types of the first module
						if (modules.ContainsName(module1))
							moduleType1 = modules.GetModule(module1);

						// make sure the module is of the right type
						if (moduleType1 != null && moduleType1.GetInterface("ICondition", false) == null)
							moduleType1 = null;

						// set the types of the second module
						if (modules.ContainsName(module2))
							moduleType2 = modules.GetModule(module2);

						// make sure the module is of the right type
						if (moduleType2 != null && moduleType2.GetInterface("IConditionTestValue", false) == null)
							moduleType2 = null;

						try
						{
							RegexOptions patternOptions = Manager.RuleOptions;
							IConditionFlagProcessor flags;

							if (match.Groups["flags"] != null)
								flags = SplitConditionFlags(match.Groups["flags"].Value);
							else
								flags = new ConditionFlagProcessor();

							// check to see if the pattern should ignore the case when testing
							if (ConditionFlagsProcessor.HasNoCase(flags))
								patternOptions |= RegexOptions.IgnoreCase;

							string test = match.Groups["test"].Value;
							string pattern = match.Groups["pattern"].Value;
							IConditionTestValue testValue;
							ICondition condition;

							// create the second module
							if (moduleType2 == null)
								testValue = GetConditionTestValue(ref test);
							else
								testValue = Activator.CreateInstance(moduleType2) as IConditionTestValue;

							// create the first module
							if (moduleType1 == null)
								condition = GetCondition(pattern);
							else
								condition = Activator.CreateInstance(moduleType1) as ICondition;

							// initialize the modules
							testValue.Init(test);
							condition.Init(new Pattern(pattern, patternOptions), testValue, flags);

							// add condition to next rule that shows up
							conditions.Add(condition);
						}
						catch (Exception exc)
						{
							if (tempLogLevel >= 3)
								Manager.Log("RewriteCond: " + exc.Message, "Error");
							else
								Manager.Log("RewriteCond: " + exc, "Error");
						}
						finally
						{
							Manager.LogIf(tempLogLevel >= 3, "RewriteCond: " + match.Groups["test"].Value + " " + match.Groups["pattern"].Value + " [" + match.Groups["flags"].Value + "]", "Rule Processing");
						}

						#endregion
					}
					else if (RewriteRuleLine.IsMatch(line))
					{
						#region RewriteRule

						Match match = RewriteRuleLine.Match(line);

						string module1 = match.Groups["module1"].Value;
						string module2 = match.Groups["module2"].Value;

						Type moduleType1 = null;
						Type moduleType2 = null;

						// set the types of the first module
						if (modules.ContainsName(module1))
							moduleType1 = modules.GetModule(module1);

						// make sure the module is of the right type
						if (moduleType1 != null && moduleType1.GetInterface("IRule", false) == null)
							moduleType1 = null;

						// set the types of the second module
						if (modules.ContainsName(module2))
							moduleType2 = modules.GetModule(module2);

						// make sure the module is of the right type
						if (moduleType2 != null && moduleType2.GetInterface("IRuleAction", false) == null)
							moduleType2 = null;

						try
						{
							RegexOptions patternOptions = Manager.RuleOptions;
							IRuleFlagProcessor flags;

							if (match.Groups["flags"] != null)
								flags = SplitRuleFlags(match.Groups["flags"].Value);
							else
								flags = new RuleFlagProcessor();

							// check to see if the pattern should ignore the case when testing
							if (RuleFlagsProcessor.HasNoCase(flags))
								patternOptions |= RegexOptions.IgnoreCase;

							IRule rule = null;
							IRuleAction substitution = null;
							Pattern pattern = new Pattern(match.Groups["pattern"].Value, patternOptions);

							// create the first module
							if (moduleType1 == null)
								rule = new DefaultRule();
							else
								rule = Activator.CreateInstance(moduleType1) as IRule;

							// create the second module
							if (moduleType2 == null)
								substitution = new DefaultRuleAction();
							else
								substitution = Activator.CreateInstance(moduleType2) as IRuleAction;

							// initialize the modules
							substitution.Init(pattern, match.Groups["substitution"].Value);
							rule.Init(conditions, substitution, flags);

							// add condition to next rule that shows up
							rules.Add(rule);

							// clear conditions for next rule
							conditions.Clear();
						}
						catch (Exception exc)
						{
							if (tempLogLevel >= 3)
								Manager.Log("RewriteRule: " + exc.Message, "Error");
							else
								Manager.Log("RewriteRule: " + exc, "Error");
						}
						finally
						{
							Manager.LogIf(tempLogLevel >= 3, "RewriteRule: " + match.Groups["pattern"].Value + " " + match.Groups["substitution"].Value + " [" + match.Groups["flags"].Value + "]", "Rule Processing");
						}

						#endregion
					}
					else if (OutRewriteCondLine.IsMatch(line))
					{
						#region OutRewriteCond

						Match match = OutRewriteCondLine.Match(line);

						string module1 = match.Groups["module1"].Value;
						string module2 = match.Groups["module2"].Value;

						Type moduleType1 = null;
						Type moduleType2 = null;

						// set the types of the first module
						if (modules.ContainsName(module1))
							moduleType1 = modules.GetModule(module1);

						// make sure the module is of the right type
						if (moduleType1 != null && moduleType1.GetInterface("ICondition", false) == null)
							moduleType1 = null;

						// set the types of the second module
						if (modules.ContainsName(module2))
							moduleType2 = modules.GetModule(module2);

						// make sure the module is of the right type
						if (moduleType2 != null && moduleType2.GetInterface("IConditionTestValue", false) == null)
							moduleType2 = null;

						try
						{
							RegexOptions patternOptions = Manager.RuleOptions;
							IConditionFlagProcessor flags;

							if (match.Groups["flags"] != null)
								flags = SplitConditionFlags(match.Groups["flags"].Value);
							else
								flags = new ConditionFlagProcessor();

							// check to see if the pattern should ignore the case when testing
							if (ConditionFlagsProcessor.HasNoCase(flags))
								patternOptions |= RegexOptions.IgnoreCase;

							string test = match.Groups["test"].Value;
							string pattern = match.Groups["pattern"].Value;
							IConditionTestValue testValue;
							ICondition condition;

							// create the second module
							if (moduleType2 == null)
								testValue = GetConditionTestValue(ref test);
							else
								testValue = Activator.CreateInstance(moduleType2) as IConditionTestValue;

							// create the first module
							if (moduleType1 == null)
								condition = GetCondition(pattern);
							else
								condition = Activator.CreateInstance(moduleType1) as ICondition;

							// initialize the modules
							testValue.Init(test);
							condition.Init(new Pattern(pattern, patternOptions), testValue, flags);

							// add condition to next rule that shows up
							conditions.Add(condition);
						}
						catch (Exception exc)
						{
							if (tempLogLevel >= 3)
								Manager.Log("OutRewriteCond: " + exc.Message, "Error");
							else
								Manager.Log("OutRewriteCond: " + exc, "Error");
						}
						finally
						{
							Manager.LogIf(tempLogLevel >= 3, "OutRewriteCond: " + match.Groups["test"].Value + " " + match.Groups["pattern"].Value + " [" + match.Groups["flags"].Value + "]", "Rule Processing");
						}

						#endregion
					}
					else if (OutRewriteRuleLine.IsMatch(line))
					{
						#region OutRewriteRule

						Match match = OutRewriteRuleLine.Match(line);

						string module1 = match.Groups["module1"].Value;
						string module2 = match.Groups["module2"].Value;

						Type moduleType1 = null;
						Type moduleType2 = null;

						// set the types of the first module
						if (modules.ContainsName(module1))
							moduleType1 = modules.GetModule(module1);

						// make sure the module is of the right type
						if (moduleType1 != null && moduleType1.GetInterface("IRule", false) == null)
							moduleType1 = null;

						// set the types of the second module
						if (modules.ContainsName(module2))
							moduleType2 = modules.GetModule(module2);

						// make sure the module is of the right type
						if (moduleType2 != null && moduleType2.GetInterface("IRuleAction", false) == null)
							moduleType2 = null;

						try
						{
							RegexOptions patternOptions = Manager.RuleOptions;
							IRuleFlagProcessor flags;

							if (match.Groups["flags"] != null)
								flags = SplitRuleFlags(match.Groups["flags"].Value);
							else
								flags = new RuleFlagProcessor();

							// check to see if the pattern should ignore the case when testing
							if (RuleFlagsProcessor.HasNoCase(flags))
								patternOptions |= RegexOptions.IgnoreCase;

							IRule rule = null;
							IRuleAction substitution = null;
							Pattern pattern = new Pattern(match.Groups["pattern"].Value, patternOptions);

							// create the first module
							if (moduleType1 == null)
								rule = new DefaultRule();
							else
								rule = Activator.CreateInstance(moduleType1) as IRule;

							// create the second module
							if (moduleType2 == null)
								substitution = new DefaultOutputRuleAction();
							else
								substitution = Activator.CreateInstance(moduleType2) as IRuleAction;

							// initialize the modules
							substitution.Init(pattern, match.Groups["substitution"].Value);
							rule.Init(conditions, substitution, flags);

							// add condition to next rule that shows up
							outputRules.Add(rule);

							// clear conditions for next rule
							conditions.Clear();
						}
						catch (Exception exc)
						{
							if (tempLogLevel >= 3)
								Manager.Log("OutRewriteRule: " + exc.Message, "Error");
							else
								Manager.Log("OutRewriteRule: " + exc, "Error");
						}
						finally
						{
							Manager.LogIf(tempLogLevel >= 3, "OutRewriteRule: " + match.Groups["pattern"].Value + " " + match.Groups["substitution"].Value + " [" + match.Groups["flags"].Value + "]", "Rule Processing");
						}

						#endregion
					}
					else
					{
						unknownLines.Add(line);
					}
				}

				Manager.LogIf(tempLogLevel > 0, "Managed Fusion Rewriter Version: " + Manager.RewriterVersion, "Rule Processing");

				// clear and add new rules
				ClearRules();
				AddRules(rules);
				AddOutputRules(outputRules);

				// try to process any unknown lines
				if (unknownLines.Count > 0)
				{
					RefreshUnknownLines(ref unknownLines);

					foreach (var unknownLine in unknownLines)
						Manager.LogIf(tempLogLevel >= 4, "Not Understood: " + unknownLine, "Unknown");
				}
							

				// set the ruleset defining properties
				VirtualBase = tempBase;
				LogLocation = tempLogPath;
				LogLevel = tempLogLevel;
				EngineEnabled = tempEngineEnabled;
				Manager.LogPath = tempLogPath;
				Manager.LogEnabled = tempLogLevel > 0;
			}
		}
Esempio n. 27
0
 Pattern OneOrMore(Pattern p)
 {
     return Create(new Pattern() {
     p1 = p,
     Nullable = p.Nullable,
     Type = PatternType.ONE_OR_MORE
       });
 }
Esempio n. 28
0
 Pattern Element(Pattern nc, Pattern p)
 {
     return Create(new Pattern() {
     p1 = nc,
     p2 = p,
     Nullable = p.Nullable,
     Type = PatternType.ELEMENT
       });
 }
Esempio n. 29
0
        private void add(string expression, object replacement)
        {
            Pattern pattern = new Pattern();
            pattern.expression = expression;
            pattern.replacement = replacement;
            //count the number of sub-expressions
            // - add 1 because each group is itself a sub-expression
            pattern.length = GROUPS.Matches(internalEscape(expression)).Count + 1;

            //does the pattern deal with sup-expressions?
            if (replacement is string && SUB_REPLACE.IsMatch((string)replacement))
            {
                string sreplacement = (string)replacement;
                // a simple lookup (e.g. $2)
                if (INDEXED.IsMatch(sreplacement))
                {
                    pattern.replacement = int.Parse(sreplacement.Substring(1)) - 1;
                }
            }

            patterns.Add(pattern);
        }
Esempio n. 30
0
 Pattern Optional(Pattern p)
 {
     return Choice(Empty(), p);
 }