public UriConfiguration(Uri baseAddress, UriTemplate recentFeedTemplate, UriTemplate feedTemplate, UriTemplate entryTemplate) { this.baseAddress = baseAddress; this.recentFeedTemplate = recentFeedTemplate; this.feedTemplate = feedTemplate; this.entryTemplate = entryTemplate; }
public void MultipleExpandVarArgs() { UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); Uri result = template.Expand("2", 21); result = template.Expand(1, "42"); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); }
public HtmlFormRequestDispatchFormatter(OperationDescription operation, UriTemplate uriTemplate, QueryStringConverter converter, IDispatchMessageFormatter innerFormatter) : base(operation, uriTemplate, converter, innerFormatter) { // This formatter will only support deserializing form post data to a type if: // (1) The type can be converted via the QueryStringConverter or... // (2) The type meets the following requirements: // (A) The type is decorated with the DataContractAttribute // (B) Every public field or property that is decorated with the DataMemberAttribute is of a type that // can be converted by the QueryStringConverter this.canConvertBodyType = this.QueryStringConverter.CanConvert(this.BodyParameterType); if (!this.canConvertBodyType) { if (this.BodyParameterType.GetCustomAttributes(typeof(DataContractAttribute), false).Length == 0) { throw new NotSupportedException( string.Format("Body parameter '{0}' from operation '{1}' is of type '{2}', which is not decorated with a DataContractAttribute. " + "Only body parameter types decorated with the DataContractAttribute are supported.", this.BodyParameterName, operation.Name, this.BodyParameterType)); } // For the body type, we'll need to cache information about each of the public fields/properties // that is decorated with the DataMemberAttribute; we'll store this info in the bodyMembers dictionary // where the member name is the dictionary key bodyMembers = new Dictionary<string, BodyMemberData>(); GetBobyMemberDataForFields(operation.Name); GetBodyMemberDataForProperties(operation.Name); requiredBodyMembers = bodyMembers.Where(p => p.Value.IsRequired == true).Select(p => p.Key).ToArray(); } }
public string BuildUriString(NancyContext context, string routeName, dynamic parameters) { var baseUri = new Uri(context.Request.BaseUri().TrimEnd('/')); var pathTemplate = AllRoutes.Single(r => r.Name == routeName).Path; var uriTemplate = new UriTemplate(pathTemplate, true); return uriTemplate.BindByName(baseUri, ToDictionary(parameters ?? new {})).ToString(); }
protected void EncryptionButtonInValidateCard_Click(object sender, EventArgs e) { Uri baseUri = new Uri("http://webstrar49.fulton.asu.edu/page3/Service1.svc"); UriTemplate myTemplate = new UriTemplate("encrypt?plainText={plainText}"); String plainText = PlainText_TextBox1.Text; Uri completeUri = myTemplate.BindByPosition(baseUri, plainText); System.Net.WebClient webClient = new System.Net.WebClient(); byte[] content = webClient.DownloadData(completeUri); //EncryptionService.Service1Client encryptionClient = new EncryptionService.Service1Client(); // String cipher=encryptionClient.encrypt(plainText); String contentinString = Encoding.UTF8.GetString(content, 0, content.Length); String pattern = @"(?<=\>)(.*?)(?=\<)"; Regex r = new Regex(pattern); Match m = r.Match(contentinString); String cipher = ""; if (m.Success) { cipher = m.Groups[1].ToString(); } cipherTextBox.Enabled = true; cipherTextBox.Text = cipher; cipherTextBox.Enabled = false; }
public MethodAndUriTemplateOperationSelector(ServiceEndpoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } this.delegates = new Dictionary<string, UriTemplateOperationSelector>(); var operations = endpoint.Contract.Operations.Select(od => new HttpOperationDescription(od)); foreach (var methodGroup in operations.GroupBy(od => od.GetWebMethod())) { UriTemplateTable table = new UriTemplateTable(endpoint.ListenUri); foreach (var operation in methodGroup) { UriTemplate template = new UriTemplate(operation.GetUriTemplateString()); table.KeyValuePairs.Add( new KeyValuePair<UriTemplate, object>(template, operation.Name)); } table.MakeReadOnly(false); UriTemplateOperationSelector templateSelector = new UriTemplateOperationSelector(table); this.delegates.Add(methodGroup.Key, templateSelector); } }
public void when_validating_a_uri_template_with_url_encoded_chars() { var template = new UriTemplate("/streams/$all?embed={embed}"); var uri = new Uri("http://127.0.0.1/streams/$all"); var baseaddress = new Uri("http://127.0.0.1"); Assert.IsTrue(template.Match(baseaddress, uri) != null); }
public static Uri BindUri(this ISession session, Uri url, object parameters = null) { Uri baseUri = new Uri(url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)); UriTemplate template = new UriTemplate(url.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped)); return BindTemplate(baseUri, template, parameters); }
public CompetitionResultAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate CompetitionResultsTemplate, UriTemplate ResultResourceTemplate, string AcceptHeader) : base(Request, Response, Prefix, AcceptHeader) { this.CompetitionResultsTemplate = CompetitionResultsTemplate; this.ResultResourceTemplate = ResultResourceTemplate; processRequest(); }
public void TestCompoundFragmentExpansionAssociativeMapVariable() { string template = "{#keys*}"; UriTemplate uriTemplate = new UriTemplate(template); Uri uri = uriTemplate.BindByName(variables); string[] allowed = { "#comma=,,dot=.,semi=;", "#comma=,,semi=;,dot=.", "#dot=.,comma=,,semi=;", "#dot=.,semi=;,comma=,", "#semi=;,comma=,,dot=.", "#semi=;,dot=.,comma=," }; CollectionAssert.Contains(allowed, uri.ToString()); UriTemplateMatch match = uriTemplate.Match(uri, new[] { "list" }, new[] { "keys" }); Assert.IsNotNull(match); CollectionAssert.AreEqual((ICollection)variables["keys"], (ICollection)match.Bindings["keys"].Value); match = uriTemplate.Match(uri, requiredVariables, new[] { "list" }, new[] { "keys" }); Assert.IsNotNull(match); CollectionAssert.AreEqual((ICollection)variables["keys"], (ICollection)match.Bindings["keys"].Value); }
public static UriTemplatePathSegment CreateFromUriTemplate(string segment, UriTemplate template) { // Identifying the type of segment - Literal|Compound|Variable switch (UriTemplateHelpers.IdentifyPartType(segment)) { case UriTemplatePartType.Literal: return UriTemplateLiteralPathSegment.CreateFromUriTemplate(segment, template); case UriTemplatePartType.Compound: return UriTemplateCompoundPathSegment.CreateFromUriTemplate(segment, template); case UriTemplatePartType.Variable: if (segment.EndsWith("/", StringComparison.Ordinal)) { string varName = template.AddPathVariable(UriTemplatePartType.Variable, segment.Substring(1, segment.Length - 3)); return new UriTemplateVariablePathSegment(segment, true, varName); } else { string varName = template.AddPathVariable(UriTemplatePartType.Variable, segment.Substring(1, segment.Length - 2)); return new UriTemplateVariablePathSegment(segment, false, varName); } default: Fx.Assert("Invalid value from IdentifyStringNature"); return null; } }
private bool TryUriTemplateMatch(string uri, out UriTemplateMatch uriTemplateMatch) { var uriTemplate = new UriTemplate(uri); var serverPath = Request.Url.GetServerBaseUri(); uriTemplateMatch = uriTemplate.Match(new Uri(serverPath), Request.Url); return uriTemplateMatch != null; }
public void ExpandVarArgsDuplicateVariables() { UriTemplate template = new UriTemplate("http://example.com/order/{c}/{c}/{c}"); Assert.AreEqual(new string[] { "c" }, template.VariableNames, "Invalid variable names"); Uri result = template.Expand("cheeseburger"); Assert.AreEqual(new Uri("http://example.com/order/cheeseburger/cheeseburger/cheeseburger"), result, "Invalid expanded template"); }
public string BuildUriString(string prefix, string template, dynamic parameters) { var newBaseUri = new Uri(baseUri.TrimEnd('/') + prefix); var uriTemplate = new UriTemplate(template, true); return uriTemplate.BindByName(newBaseUri, ToDictionary(parameters ?? new {})).ToString(); }
public static UriTemplateQueryValue CreateFromUriTemplate(string value, UriTemplate template) { // Checking for empty value if (value == null) { return UriTemplateQueryValue.Empty; } // Identifying the type of value - Literal|Compound|Variable switch (UriTemplateHelpers.IdentifyPartType(value)) { case UriTemplatePartType.Literal: return UriTemplateLiteralQueryValue.CreateFromUriTemplate(value); case UriTemplatePartType.Compound: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.UTQueryCannotHaveCompoundValue, template.originalTemplate))); case UriTemplatePartType.Variable: return new UriTemplateVariableQueryValue(template.AddQueryVariable(value.Substring(1, value.Length - 2))); default: Fx.Assert("Invalid value from IdentifyStringNature"); return null; } }
public SerializedResult(Result x, Uri Prefix, UriTemplate ResultResourceTemplate, UriTemplate FencerResourceTemplate,UriTemplate CompetitionResourceTemplate) { ID = x.ResultID; Placing = x.Placing; ReferenceURI = ResultResourceTemplate.BindByPosition(Prefix, ID.ToString()); FencerURI = FencerResourceTemplate.BindByPosition(Prefix, x.FencerID.ToString()); CompetitionURI = CompetitionResourceTemplate.BindByPosition(Prefix, x.CompetitionID.ToString()); }
public void WhenMatchingMultipleArgs_ThenUriTemplateMatches() { var template = new UriTemplate("?search={search}"); var match = template.Match(new Uri("http://localhost/products"), new Uri("http://localhost/products?search=foo,bar")); Assert.NotNull(match); }
public FencerAppelRequestHandler(HttpRequest Request, HttpResponse Response, Uri Prefix, UriTemplate FencerRootTemplate, UriTemplate FencerResourceTemplate, UriTemplate FencerResultTemplate, string AcceptHeader) : base(Request, Response, Prefix, AcceptHeader) { this.FencerRootTemplate = FencerRootTemplate; this.FencerResourceTemplate = FencerResourceTemplate; this.FencerResultTemplate = FencerResultTemplate; processRequest(); }
public void AddHandler(UriTemplate uriTemplate, HandlerDelegate handler) { _uriHandlers.Add(new UriHandler() { UriTemplate = uriTemplate, Handler = handler }); }
public void ExpandDictionaryInvalidAmountVariables() { IDictionary<string, object> uriVariables = new Dictionary<string, object>(2); uriVariables.Add("hotel", 1); UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); template.Expand(uriVariables); }
public SerializedCompetition(Competition x, Uri Prefix, UriTemplate CompetitionTemplate, UriTemplate CompetitionResultTemplate) { ID = x.CompetitionID; Title = x.Title; Venue = x.Venue; ReferenceURI = CompetitionTemplate.BindByPosition(Prefix, ID.ToString()); CompetitionResultsURI = CompetitionResultTemplate.BindByPosition(Prefix, ID.ToString()); }
public SerializedResultArrayBeta(List<Result> x, UriTemplateMatch templateMatch, Uri Prefix, UriTemplate ResultResourceTemplate, UriTemplate ResourceArrayTemplate) { List<SerializedResultArrayEntry> r = new List<SerializedResultArrayEntry>(); foreach (Result result in x) { r.Add(new SerializedResultArrayEntry(result, Prefix, ResultResourceTemplate)); } Results = r; }
public SerializedFencer(Fencer x, Uri Prefix, UriTemplate FencerTemplate, UriTemplate FencerResultTemplate) { ID = x.FencerID; LastName = x.LastName; FirstName = x.FirstName; Club = x.Club; ReferenceURI = FencerTemplate.BindByPosition(Prefix, ID.ToString()); FencerResultsURI = FencerResultTemplate.BindByPosition(Prefix, ID.ToString()); }
public UriFactoryWorker(string routePrefix, string uriTemplateValue) { CheckString.Is(Not.NullOrEmptyOrWhitespace, routePrefix, "routePrefix"); CheckString.Is(Not.Null | Not.Whitespace, uriTemplateValue, "uriTemplateValue"); this.routePrefix = routePrefix; uriTemplate = new UriTemplate(uriTemplateValue, !(uriTemplateValue.StartsWith("/") || uriTemplateValue.EndsWith("/"))); dummyBaseAddress = new Uri(Localhost, routePrefix); }
public void TestEmptyTemplate() { string template = string.Empty; UriTemplate uriTemplate = new UriTemplate(template); Uri uri = uriTemplate.BindByName(variables); Assert.AreEqual(string.Empty, uri.ToString()); UriTemplateMatch match = uriTemplate.Match(uri); Assert.IsNotNull(match); Assert.AreEqual(0, match.Bindings.Count); }
/// <summary> /// Resolve absolute string URI template and create request with implicit session. /// </summary> /// <param name="url"></param> /// <param name="parameters"></param> /// <returns></returns> public static Request Bind(this string url, object parameters = null) { Condition.Requires(url, "url").IsNotNull(); Uri uri = new Uri(url); Uri baseUri = new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)); UriTemplate template = new UriTemplate(uri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped)); Uri boundUrl = BindTemplate(baseUri, template, parameters); return new Request(boundUrl); }
public bool Matches(RequestContext ctx) { if (!String.IsNullOrEmpty(method) && ctx.Request.HttpMethod != method) return false; var uriTemplate = new UriTemplate(uri); var serverPath = ctx.Request.Url.GetServerBaseUri(); var uriTemplateMatch = uriTemplate.Match(new Uri(serverPath), ctx.Request.Url); if (uriTemplateMatch == null) return false; ctx.Request.LoadArguments(uriTemplateMatch.BoundVariables); return true; }
public void Experiment() { var template = new UriTemplate("devices/{deviceId}/messages/outbound/{*subTopic}"); var baseUri = new Uri("http://whatever"); Uri bound = template.BindByName(baseUri, new Dictionary<string, string> { { "deviceId", "VINno" }, { "SubTopic", "toptop/toptoptop" }, }); var t2 = new UriTemplate("devices/{deviceId}/messages/log/{level=info}/{subject=n%2Fa}", true); UriTemplateMatch match = t2.Match(baseUri, new Uri("http://whatever/devices/VINno/messages/log", UriKind.Absolute)); }
public SerializedResultArrayV1(List<Result> x, UriTemplateMatch templateMatch, Uri Prefix, UriTemplate ResultResourceTemplate, UriTemplate ResourceArrayTemplate) { Pagination = createPagination(x.Count,templateMatch, Prefix, ResourceArrayTemplate); List<SerializedResultArrayEntry> r = new List<SerializedResultArrayEntry>(); foreach (Result result in x) { r.Add(new SerializedResultArrayEntry(result, Prefix, ResultResourceTemplate)); } Results = filterResults(r); ReferenceURI = ResourceArrayTemplate.BindByPosition(Prefix,templateMatch.BoundVariables["id"]); }
public void ExpandVarArgs() { // absolute UriTemplate template = new UriTemplate("http://example.com/hotels/{hotel}/bookings/{booking}"); Uri result = template.Expand("1", "42"); Assert.AreEqual(new Uri("http://example.com/hotels/1/bookings/42"), result, "Invalid expanded template"); // relative template = new UriTemplate("/hotels/{hotel}/bookings/{booking}"); result = template.Expand("1", "42"); Assert.AreEqual(new Uri("/hotels/1/bookings/42", UriKind.Relative), result, "Invalid expanded template"); }
static string[] GetQueryLiterals(UriTemplate up, Dictionary <string, byte> queryVarNames) { string[] queryLitVals = new string[queryVarNames.Count]; int i = 0; foreach (string queryVarName in queryVarNames.Keys) { Fx.Assert(up.queries.ContainsKey(queryVarName), "query doesn't have name"); UriTemplateQueryValue utqv = up.queries[queryVarName]; Fx.Assert(utqv.Nature == UriTemplatePartType.Literal, "query for name is not literal"); if (utqv == UriTemplateQueryValue.Empty) { queryLitVals[i] = null; } else { queryLitVals[i] = ((UriTemplateLiteralQueryValue)(utqv)).AsRawUnescapedString(); } ++i; } return(queryLitVals); }
private static void Validate(UriTemplatePathPartiallyEquivalentSet pes, bool allowDuplicateEquivalentUriTemplates) { if (pes.Items.Count >= 2) { for (int i = 0; i < (pes.Items.Count - 1); i++) { } UriTemplate[] array = new UriTemplate[pes.Items.Count]; int b = 0; foreach (KeyValuePair <UriTemplate, object> pair in pes.Items) { if (pes.SegmentsCount >= pair.Key.segments.Count) { array[b++] = pair.Key; } } if (b > 0) { UriTemplateHelpers.DisambiguateSamePath(array, 0, b, allowDuplicateEquivalentUriTemplates); } } }
void ConstructFastPathTable() { this.noTemplateHasQueryPart = true; foreach (KeyValuePair <UriTemplate, object> kvp in this.templates) { UriTemplate ut = kvp.Key; if (!UriTemplateHelpers.CanMatchQueryTrivially(ut)) { this.noTemplateHasQueryPart = false; } if (ut.HasNoVariables && !ut.HasWildcard) { // eligible for fast path if (this.fastPathTable == null) { this.fastPathTable = new Dictionary <string, FastPathInfo>(); } Uri uri = ut.BindByPosition(this.originalUncanonicalizedBaseAddress); string uriPath = UriTemplateHelpers.GetUriPath(uri); if (this.fastPathTable.ContainsKey(uriPath)) { // nothing to do, we've already seen it } else { FastPathInfo fpInfo = new FastPathInfo(); if (ComputeRelativeSegmentsAndLookup(uri, fpInfo.RelativePathSegments, fpInfo.Candidates)) { fpInfo.Freeze(); this.fastPathTable.Add(uriPath, fpInfo); } } } } }
private static void Validate(UriTemplateTrieNode root, bool allowDuplicateEquivalentUriTemplates) { Queue <UriTemplateTrieNode> queue = new Queue <UriTemplateTrieNode>(); UriTemplateTrieNode node = root; while (true) { Validate(node.endOfPath, allowDuplicateEquivalentUriTemplates); Validate(node.finalVariableSegment, allowDuplicateEquivalentUriTemplates); Validate(node.star, allowDuplicateEquivalentUriTemplates); if (node.finalLiteralSegment != null) { foreach (KeyValuePair <UriTemplateLiteralPathSegment, UriTemplatePathPartiallyEquivalentSet> pair in node.finalLiteralSegment) { Validate(pair.Value, allowDuplicateEquivalentUriTemplates); } } if (node.finalCompoundSegment != null) { IList <IList <UriTemplatePathPartiallyEquivalentSet> > values = node.finalCompoundSegment.Values; for (int i = 0; i < values.Count; i++) { if (!allowDuplicateEquivalentUriTemplates && (values[i].Count > 1)) { object[] args = new object[2]; KeyValuePair <UriTemplate, object> pair3 = values[i][0].Items[0]; args[0] = pair3.Key.ToString(); KeyValuePair <UriTemplate, object> pair4 = values[i][1].Items[0]; args[1] = pair4.Key.ToString(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UTTDuplicate", args))); } for (int j = 0; j < values[i].Count; j++) { Validate(values[i][j], allowDuplicateEquivalentUriTemplates); } } } if (node.nextLiteralSegment != null) { foreach (KeyValuePair <UriTemplateLiteralPathSegment, UriTemplateTrieLocation> pair2 in node.nextLiteralSegment) { queue.Enqueue(pair2.Value.node); } } if (node.nextCompoundSegment != null) { IList <IList <UriTemplateTrieLocation> > list2 = node.nextCompoundSegment.Values; for (int k = 0; k < list2.Count; k++) { if (!allowDuplicateEquivalentUriTemplates && (list2[k].Count > 1)) { UriTemplate template = FindAnyUriTemplate(list2[k][0].node); UriTemplate template2 = FindAnyUriTemplate(list2[k][1].node); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UTTDuplicate", new object[] { template.ToString(), template2.ToString() }))); } for (int m = 0; m < list2[k].Count; m++) { UriTemplateTrieLocation location = list2[k][m]; queue.Enqueue(location.node); } } } if (node.nextVariableSegment != null) { queue.Enqueue(node.nextVariableSegment.node); } if (queue.Count == 0) { return; } node = queue.Dequeue(); } }
public static new UriTemplateLiteralPathSegment CreateFromUriTemplate(string segment, UriTemplate template) { // run it through UriBuilder to escape-if-necessary it if (string.Compare(segment, "/", StringComparison.Ordinal) == 0) { // running an empty segment through UriBuilder has unexpected/wrong results return(new UriTemplateLiteralPathSegment("/")); } if (segment.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException( SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, template.originalTemplate, UriTemplate.WildcardPath))); } // '*' is not usually escaped by the Uri\UriBuilder to %2a, since we forbid passing a // clear character and the workaroud is to pass the escaped form, we should replace the // escaped form with the regular one. segment = segment.Replace("%2a", "*").Replace("%2A", "*"); UriBuilder ub = new UriBuilder(dummyUri); ub.Path = segment; string escapedIfNecessarySegment = ub.Uri.AbsolutePath.Substring(1); if (escapedIfNecessarySegment == string.Empty) { // This path through UriBuilder will sometimes '----' various segments // such as '../' and './'. When this happens and the result is an empty // string, we should just throw and tell the user we don't handle that. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("segment", SR.GetString(SR.UTInvalidFormatSegmentOrQueryPart, segment)); } return(new UriTemplateLiteralPathSegment(escapedIfNecessarySegment)); }
public UriTemplateTableMatchCandidate(UriTemplate template, int segmentsCount, object data) { this.template = template; this.segmentsCount = segmentsCount; this.data = data; }
public static UriTemplateCompoundPathSegment CreateFromUriTemplate(string segment, UriTemplate template) { string originalSegment = segment; bool endsWithSlash = segment.EndsWith("/", StringComparison.Ordinal); if (endsWithSlash) { segment = segment.Remove(segment.Length - 1); } int index = segment.IndexOf("{", StringComparison.Ordinal); string stringToUnescape = (index > 0) ? segment.Substring(0, index) : string.Empty; if (stringToUnescape.IndexOf("*", StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.ServiceModel.SR.GetString("UTInvalidWildcardInVariableOrLiteral", new object[] { template.originalTemplate, "*" }))); } UriTemplateCompoundPathSegment segment2 = new UriTemplateCompoundPathSegment(originalSegment, endsWithSlash, (stringToUnescape != string.Empty) ? Uri.UnescapeDataString(stringToUnescape) : string.Empty); do { bool flag2; string str4; int num2 = segment.IndexOf("}", index + 1, StringComparison.Ordinal); if (num2 < (index + 2)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.ServiceModel.SR.GetString("UTInvalidFormatSegmentOrQueryPart", new object[] { segment }))); } string varName = template.AddPathVariable(UriTemplatePartType.Compound, segment.Substring(index + 1, (num2 - index) - 1), out flag2); if (flag2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UTDefaultValueToCompoundSegmentVar", new object[] { template, originalSegment, varName }))); } index = segment.IndexOf("{", num2 + 1, StringComparison.Ordinal); if (index > 0) { if (index == (num2 + 1)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("template", System.ServiceModel.SR.GetString("UTDoesNotSupportAdjacentVarsInCompoundSegment", new object[] { template, segment })); } str4 = segment.Substring(num2 + 1, (index - num2) - 1); } else if ((num2 + 1) < segment.Length) { str4 = segment.Substring(num2 + 1); } else { str4 = string.Empty; } if (str4.IndexOf("*", StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.ServiceModel.SR.GetString("UTInvalidWildcardInVariableOrLiteral", new object[] { template.originalTemplate, "*" }))); } if (str4.IndexOf('}') != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.ServiceModel.SR.GetString("UTInvalidFormatSegmentOrQueryPart", new object[] { segment }))); } segment2.varLitPairs.Add(new VarAndLitPair(varName, (str4 == string.Empty) ? string.Empty : Uri.UnescapeDataString(str4))); }while (index > 0); if (string.IsNullOrEmpty(segment2.firstLiteral)) { VarAndLitPair pair = segment2.varLitPairs[segment2.varLitPairs.Count - 1]; if (string.IsNullOrEmpty(pair.Literal)) { segment2.csClass = CompoundSegmentClass.HasNoPrefixNorSuffix; return(segment2); } segment2.csClass = CompoundSegmentClass.HasOnlySuffix; return(segment2); } VarAndLitPair pair2 = segment2.varLitPairs[segment2.varLitPairs.Count - 1]; if (string.IsNullOrEmpty(pair2.Literal)) { segment2.csClass = CompoundSegmentClass.HasOnlyPrefix; return(segment2); } segment2.csClass = CompoundSegmentClass.HasPrefixAndSuffix; return(segment2); }
public static bool CanMatchQueryTrivially(UriTemplate ut) { return(ut.queries.Count == 0); }
static void Add(UriTemplateTrieNode root, KeyValuePair <UriTemplate, object> kvp) { // Currently UTT doesn't support teplates with ignoreTrailingSlash == true; thus we // don't care about supporting it in the trie as well. UriTemplateTrieNode current = root; UriTemplate ut = kvp.Key; bool needProcessingOnFinalNode = ((ut.segments.Count == 0) || ut.HasWildcard || ut.segments[ut.segments.Count - 1].EndsWithSlash); for (int i = 0; i < ut.segments.Count; ++i) { if (i >= ut.firstOptionalSegment) { current.endOfPath.Items.Add(kvp); } UriTemplatePathSegment ps = ut.segments[i]; if (!ps.EndsWithSlash) { Fx.Assert(i == ut.segments.Count - 1, "only the last segment can !EndsWithSlash"); Fx.Assert(!ut.HasWildcard, "path star cannot have !EndsWithSlash"); switch (ps.Nature) { case UriTemplatePartType.Literal: current.AddFinalLiteralSegment(ps as UriTemplateLiteralPathSegment, kvp); break; case UriTemplatePartType.Compound: current.AddFinalCompoundSegment(ps as UriTemplateCompoundPathSegment, kvp); break; case UriTemplatePartType.Variable: current.finalVariableSegment.Items.Add(kvp); break; default: Fx.Assert("Invalid value as PathSegment.Nature"); break; } } else { Fx.Assert(ps.EndsWithSlash, "ps.EndsWithSlash"); switch (ps.Nature) { case UriTemplatePartType.Literal: current = current.AddNextLiteralSegment(ps as UriTemplateLiteralPathSegment); break; case UriTemplatePartType.Compound: current = current.AddNextCompoundSegment(ps as UriTemplateCompoundPathSegment); break; case UriTemplatePartType.Variable: current = current.AddNextVariableSegment(); break; default: Fx.Assert("Invalid value as PathSegment.Nature"); break; } } } if (needProcessingOnFinalNode) { // if the last segment ended in a slash, there is still more to do if (ut.HasWildcard) { // e.g. "path1/path2/*" current.star.Items.Add(kvp); } else { // e.g. "path1/path2/" current.endOfPath.Items.Add(kvp); } } }
static void Validate(UriTemplateTrieNode root, bool allowDuplicateEquivalentUriTemplates) { // walk the entire tree, and ensure that each PathEquivalentSet is ok (no ambiguous queries), // verify thst compound segments didn't add potentialy multiple matchs; // also Assert various data-structure invariants Queue <UriTemplateTrieNode> nodesQueue = new Queue <UriTemplateTrieNode>(); UriTemplateTrieNode current = root; while (true) { // validate all the PathEquivalentSets that live in this node Validate(current.endOfPath, allowDuplicateEquivalentUriTemplates); Validate(current.finalVariableSegment, allowDuplicateEquivalentUriTemplates); Validate(current.star, allowDuplicateEquivalentUriTemplates); if (current.finalLiteralSegment != null) { foreach (KeyValuePair <UriTemplateLiteralPathSegment, UriTemplatePathPartiallyEquivalentSet> kvp in current.finalLiteralSegment) { Validate(kvp.Value, allowDuplicateEquivalentUriTemplates); } } if (current.finalCompoundSegment != null) { IList <IList <UriTemplatePathPartiallyEquivalentSet> > pesLists = current.finalCompoundSegment.Values; for (int i = 0; i < pesLists.Count; i++) { if (!allowDuplicateEquivalentUriTemplates && (pesLists[i].Count > 1)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.UTTDuplicate, pesLists[i][0].Items[0].Key.ToString(), pesLists[i][1].Items[0].Key.ToString()))); } for (int j = 0; j < pesLists[i].Count; j++) { Validate(pesLists[i][j], allowDuplicateEquivalentUriTemplates); } } } // deal with children of this node if (current.nextLiteralSegment != null) { foreach (KeyValuePair <UriTemplateLiteralPathSegment, UriTemplateTrieLocation> kvp in current.nextLiteralSegment) { Fx.Assert(kvp.Value.locationWithin == UriTemplateTrieIntraNodeLocation.BeforeLiteral, "forward-pointers should always point to a BeforeLiteral location"); Fx.Assert(kvp.Value.node.depth == current.depth + 1, "kvp.Value.node.depth == current.depth + 1"); Fx.Assert(kvp.Value.node.onFailure.node == current, "back pointer should point back to here"); Fx.Assert(kvp.Value.node.onFailure.locationWithin == UriTemplateTrieIntraNodeLocation.AfterLiteral, "back-pointer should be AfterLiteral"); nodesQueue.Enqueue(kvp.Value.node); } } if (current.nextCompoundSegment != null) { IList <IList <UriTemplateTrieLocation> > locations = current.nextCompoundSegment.Values; for (int i = 0; i < locations.Count; i++) { if (!allowDuplicateEquivalentUriTemplates && (locations[i].Count > 1)) { // In the future we might ease up the restrictions and verify if there is realy // a potential multiple match here; for now we are throwing. UriTemplate firstTemplate = FindAnyUriTemplate(locations[i][0].node); UriTemplate secondTemplate = FindAnyUriTemplate(locations[i][1].node); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.UTTDuplicate, firstTemplate.ToString(), secondTemplate.ToString()))); } for (int j = 0; j < locations[i].Count; j++) { UriTemplateTrieLocation location = locations[i][j]; Fx.Assert(location.locationWithin == UriTemplateTrieIntraNodeLocation.BeforeLiteral, "forward-pointers should always point to a BeforeLiteral location"); Fx.Assert(location.node.depth == current.depth + 1, "kvp.Value.node.depth == current.depth + 1"); Fx.Assert(location.node.onFailure.node == current, "back pointer should point back to here"); Fx.Assert(location.node.onFailure.locationWithin == UriTemplateTrieIntraNodeLocation.AfterCompound, "back-pointer should be AfterCompound"); nodesQueue.Enqueue(location.node); } } } if (current.nextVariableSegment != null) { Fx.Assert(current.nextVariableSegment.locationWithin == UriTemplateTrieIntraNodeLocation.BeforeLiteral, "forward-pointers should always point to a BeforeLiteral location"); Fx.Assert(current.nextVariableSegment.node.depth == current.depth + 1, "current.nextVariableSegment.node.depth == current.depth + 1"); Fx.Assert(current.nextVariableSegment.node.onFailure.node == current, "back pointer should point back to here"); Fx.Assert(current.nextVariableSegment.node.onFailure.locationWithin == UriTemplateTrieIntraNodeLocation.AfterVariable, "back-pointer should be AfterVariable"); nodesQueue.Enqueue(current.nextVariableSegment.node); } // move on to next bit of work if (nodesQueue.Count == 0) { break; } current = nodesQueue.Dequeue(); } }
public bool IsEquivalentTo(System.UriTemplate other) { return(default(bool)); }
public static UriTemplateLiteralPathSegment CreateFromUriTemplate(string segment, UriTemplate template) { if (string.Compare(segment, "/", StringComparison.Ordinal) == 0) { return(new UriTemplateLiteralPathSegment("/")); } if (segment.IndexOf("*", StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.ServiceModel.SR.GetString("UTInvalidWildcardInVariableOrLiteral", new object[] { template.originalTemplate, "*" }))); } segment = segment.Replace("%2a", "*").Replace("%2A", "*"); UriBuilder builder = new UriBuilder(dummyUri) { Path = segment }; string str = builder.Uri.AbsolutePath.Substring(1); if (str == string.Empty) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("segment", System.ServiceModel.SR.GetString("UTInvalidFormatSegmentOrQueryPart", new object[] { segment })); } return(new UriTemplateLiteralPathSegment(str)); }
public static new UriTemplateCompoundPathSegment CreateFromUriTemplate(string segment, UriTemplate template) { string origSegment = segment; bool endsWithSlash = segment.EndsWith("/", StringComparison.Ordinal); if (endsWithSlash) { segment = segment.Remove(segment.Length - 1); } int nextVarStart = segment.IndexOf("{", StringComparison.Ordinal); Fx.Assert(nextVarStart >= 0, "The method is only called after identifying a '{' character in the segment"); string firstLiteral = ((nextVarStart > 0) ? segment.Substring(0, nextVarStart) : string.Empty); if (firstLiteral.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException( SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, template.originalTemplate, UriTemplate.WildcardPath))); } UriTemplateCompoundPathSegment result = new UriTemplateCompoundPathSegment(origSegment, endsWithSlash, ((firstLiteral != string.Empty) ? Uri.UnescapeDataString(firstLiteral) : string.Empty)); do { int nextVarEnd = segment.IndexOf("}", nextVarStart + 1, StringComparison.Ordinal); if (nextVarEnd < nextVarStart + 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException( SR.GetString(SR.UTInvalidFormatSegmentOrQueryPart, segment))); } bool hasDefault; string varName = template.AddPathVariable(UriTemplatePartType.Compound, segment.Substring(nextVarStart + 1, nextVarEnd - nextVarStart - 1), out hasDefault); if (hasDefault) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.UTDefaultValueToCompoundSegmentVar, template, origSegment, varName))); } nextVarStart = segment.IndexOf("{", nextVarEnd + 1, StringComparison.Ordinal); string literal; if (nextVarStart > 0) { if (nextVarStart == nextVarEnd + 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("template", SR.GetString(SR.UTDoesNotSupportAdjacentVarsInCompoundSegment, template, segment)); } literal = segment.Substring(nextVarEnd + 1, nextVarStart - nextVarEnd - 1); } else if (nextVarEnd + 1 < segment.Length) { literal = segment.Substring(nextVarEnd + 1); } else { literal = string.Empty; } if (literal.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException( SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, template.originalTemplate, UriTemplate.WildcardPath))); } if (literal.IndexOf('}') != -1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException( SR.GetString(SR.UTInvalidFormatSegmentOrQueryPart, segment))); } result.varLitPairs.Add(new VarAndLitPair(varName, ((literal == string.Empty) ? string.Empty : Uri.UnescapeDataString(literal)))); } while (nextVarStart > 0); if (string.IsNullOrEmpty(result.firstLiteral)) { if (string.IsNullOrEmpty(result.varLitPairs[result.varLitPairs.Count - 1].Literal)) { result.csClass = CompoundSegmentClass.HasNoPrefixNorSuffix; } else { result.csClass = CompoundSegmentClass.HasOnlySuffix; } } else { if (string.IsNullOrEmpty(result.varLitPairs[result.varLitPairs.Count - 1].Literal)) { result.csClass = CompoundSegmentClass.HasOnlyPrefix; } else { result.csClass = CompoundSegmentClass.HasPrefixAndSuffix; } } return(result); }