Listing 13.1 shows two examples of how we can build System.Uri instances based on System.UriTemplate classes. The first example uses the BindByPosition method to create a System.Uri instance to retrieve Yahoo! stock quotes. The second example uses the BindByName method to pass a collection of name/value pairs to create a System.Uri instance to retrieve Google stock quotes.
using System;using System.Collections.Specialized;
namespace EssentialWCF{ class Program { static void Main(string[] args) { string symbol = "MSFT";
// BindByPosition Uri YahooStockBaseUri = new Uri("http://finance.yahoo.com"); UriTemplate YahooStockUriTemplate = new UriTemplate("/d/quotes?s={symbol}&f=sl1t1d1"); Uri YahooStockUri = YahooStockUriTemplate.BindByPosition( YahooStockBaseUri, symbol); Console.WriteLine(YahooStockUri.ToString());
// BindByName Uri GoogleStockBaseUri = new Uri("http://finance.google.com"); UriTemplate GoogleStockUriTemplate = new UriTemplate("/finance/info?q={symbol}"); NameValueCollection GoogleParams = new NameValueCollection(); GoogleParams.Add("symbol", symbol); Uri GoogleStockUri = GoogleStockUriTemplate.BindByName( GoogleStockBaseUri, GoogleParams); Console.WriteLine(GoogleStockUri.ToString());
Console.ReadLine(); } }}
We just saw how easy it was to create System.Uri instances based on patterns. Listing 13.2 shows how we can take existing URIs and parse out parameters. Again we have two examples. The first example shows how we can parse out parameters based on query string parameters. The second example shows how we can parse out parameters based on a path. In both cases, we are able to extract a set of name/value pairs based on a pattern. We will see in the "Creating Operations for the Web" section how the UriTemplate can be used to dispatch Web service methods based on URIs.
using System;
namespace UriTemplate102{ class Program { static void Main(string[] args) { Uri YahooBaseUri = new Uri("http://finance.yahoo.com"); UriTemplate YahooStockTemplate = new UriTemplate("/d/quotes?s={symbol}"); Uri YahooStockUri = new Uri("http://finance.yahoo.com/d/quotes?s=MSFT&f=spt1d"); UriTemplateMatch match = YahooStockTemplate.Match(YahooBaseUri, YahooStockUri); foreach (string key in match.BoundVariables.Keys) Console.WriteLine(String.Format("{0}: {1}", key, match.BoundVariables[key])); Console.WriteLine();
Uri ReferenceDotComBaseUri = new Uri("http://dictionary.reference.com"); UriTemplate ReferenceDotComTemplate = new UriTemplate("/browse/{word}"); Uri ReferenceDotComUri = new Uri("http://dictionary.reference.com/browse/opaque"); match = ReferenceDotComTemplate.Match(ReferenceDotComBaseUri ReferenceDotComUri);
foreach (string key in match.BoundVariables.Keys) Console.WriteLine(String.Format("{0}: {1}", key, match.BoundVariables[key]));