/// <summary> /// Convert a pattern - such as /Pet/{Kind}/Toy/{Name} to a regular expression to help matching against real paths. /// </summary> /// <param name="pattern"></param> /// <param name="nameCaptures">If true, the regular expression will name the capture groups. </param> /// <returns></returns> public static string ConvertPatternToRegularExpression(string pattern, bool nameCaptures) { if (null == pattern) return pattern; string resourceName = "?<resourceName>"; string resourceIdentifier = "?<resourceIdentifier>"; if (!nameCaptures) { resourceName = ""; resourceIdentifier = ""; } Substitution s = new Substitution(); var vars = s.GetVariables(pattern); if (vars.Count == 0) { if (nameCaptures) { return string.Format("^?<resourceName>{0}$", pattern); } return string.Format("^{0}$", pattern); } // NOTE: Currently only matches the first {variable}. // We need to replace the {variable} with a regular expression that will match. System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(RegularExpression); var matches = r.Matches(pattern); StringBuilder b = new StringBuilder(); foreach (System.Text.RegularExpressions.Match m in matches) { vars = s.GetVariables(m.Value); if (vars.Count == 0) { // This is entirely a resourceName - a fixed value. b.AppendFormat(string.Format("({1}{0})", Regex.Escape(m.Value), resourceName)); continue; } // This includes variables. In particular: /Pet/{Kind} foreach (var v in vars) { var fullVariable = string.Format("{{{0}}}", v.Name); var start = m.Value.Substring(0, v.Position); start = Regex.Escape(start); if (nameCaptures && start != "/") { start = resourceName + start; } var regex = ".*?"; if (nameCaptures) { regex = resourceIdentifier + regex; } var end = m.Value.Substring(v.Position + fullVariable.Length); b.AppendFormat("({0})({1})({2})", start, regex, Regex.Escape(end)); } } // By doing this, we get separate tokens. var result = string.Format("^{0}$", b.ToString()); return result; }
/// <summary> /// Indicates that the object referenced using a {placeholder} in the Path does not exist as part of the condition. /// </summary> /// <returns></returns> public SimulationCondition NotExists() { if (SimulationConditionContent.ContentKind != Common.ContentKind.Json) { throw new System.InvalidOperationException("ERROR: NotExists can only be used with Json. Use .AsJson(). before the .NotExists call. "); } Substitution s = new Substitution(); var vars = s.GetVariables(SimulationConditionContent.Pattern); if (vars.Count() != 1) { throw new System.InvalidOperationException(@"ERROR: To use Exists(), the Path parameter must contain at least one placeholder. ie: When.I.Get().From(""/Endpoint({id})"")"); } SimulationConditionContent.IndexProperty = string.Format("{0}", vars.Last().Name); SimulationConditionContent.Persistence = Common.Persistence.NotExists; return this; }