Feb 20 2008 11:13PM GMT
Posted by: Dilip Krishnan
Development,
Web services,
WCF
UPDATE: Unfortunately the formatting is messed up for a clearer formatting please visit http://dilipkrish.blogspot.com/2008/02/binding-to-uritemplate.html
The UriTemplate is pretty useful especially if we have a bunch of urls that are structurally the same.
string SomeUriTemplate = “folder/?a={a}&b={b}&c={c}“;
UriTemplate uriTemplate = new UriTemplate(SomeUriTemplate);
NameValueCollection nvc = new NameValueCollection();
After than initial setup... Lets look at the BindByPosition. Here the values supplied bind to the uri by ordinal.
Uri result = uriTemplate.BindByPosition(new Uri(”http://tempuri.org“), “1“, “2“, “3“);
Console.WriteLine(result.AbsoluteUri);
OUTPUT : http://tempuri.org/folder/?a=1&b=2&c=3
Great if the positions of the parameters dont change and also the number of parameters expected is always the same. So if we supply too many or too few parameters then we get a run time exception. Or if the template changes to "folder/?a={a}&c={c}&b={b}” we’ll start to see unexpected results!!
Uri result = uriTemplate.BindByPosition(new Uri(”http://tempuri.org“), “1“, “2“, “3“, “4“); Console.WriteLine(result.AbsoluteUri); //<- RUNTIME ERROR
The other option we have is the BindByName. Lets take a look at the following example
nvc.Add("a“, “1“);
nvc.Add(”b“, “2“);
nvc.Add(”c“, “3“);
result = uriTemplate.BindByName(new Uri(”http://tempuri.org“), nvc);
Console.WriteLine(result.AbsoluteUri);
OUTPUT : http://tempuri.org/folder/?a=1&b=2&c=3
Works as expected
nvc = new NameValueCollection();
nvc.Add(”a“, “1“);
nvc.Add(”b“, “2“);
result = uriTemplate.BindByName(new Uri(”http://tempuri.org“), nvc);
Console.WriteLine(result.AbsoluteUri);
OUTPUT : http://tempuri.org/folder/?a=1&b=2
Interesting!! it only substitutes what it knows about and leaves out the parameter c!
nvc = new NameValueCollection();
nvc.Add(”a“, “1“);
nvc.Add(”d“, “4“);
result = uriTemplate.BindByName(new Uri(”http://tempuri.org“), nvc);
Console.WriteLine(result.AbsoluteUri);
OUTPUT : http://tempuri.org/folder/?a=1&d=4
And if the NameValueCollection contains additional parameters the template does not know about it adds it to the uri when it binds to the template.