1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
|
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System
{
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Globalization;
[TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
public class UriTemplate
{
internal readonly int firstOptionalSegment;
internal readonly string originalTemplate;
internal readonly Dictionary<string, UriTemplateQueryValue> queries; // keys are original case specified in UriTemplate constructor, dictionary ignores case
internal readonly List<UriTemplatePathSegment> segments;
internal const string WildcardPath = "*";
readonly Dictionary<string, string> additionalDefaults; // keys are original case specified in UriTemplate constructor, dictionary ignores case
readonly string fragment;
readonly bool ignoreTrailingSlash;
const string NullableDefault = "null";
readonly WildcardInfo wildcard;
IDictionary<string, string> defaults;
ConcurrentDictionary<string, string> unescapedDefaults;
VariablesCollection variables;
// constructors validates that template is well-formed
public UriTemplate(string template)
: this(template, false)
{
}
public UriTemplate(string template, bool ignoreTrailingSlash)
: this(template, ignoreTrailingSlash, null)
{
}
public UriTemplate(string template, IDictionary<string, string> additionalDefaults)
: this(template, false, additionalDefaults)
{
}
public UriTemplate(string template, bool ignoreTrailingSlash, IDictionary<string, string> additionalDefaults)
{
if (template == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("template");
}
this.originalTemplate = template;
this.ignoreTrailingSlash = ignoreTrailingSlash;
this.segments = new List<UriTemplatePathSegment>();
this.queries = new Dictionary<string, UriTemplateQueryValue>(StringComparer.OrdinalIgnoreCase);
// parse it
string pathTemplate;
string queryTemplate;
// ignore a leading slash
if (template.StartsWith("/", StringComparison.Ordinal))
{
template = template.Substring(1);
}
// pull out fragment
int fragmentStart = template.IndexOf('#');
if (fragmentStart == -1)
{
this.fragment = "";
}
else
{
this.fragment = template.Substring(fragmentStart + 1);
template = template.Substring(0, fragmentStart);
}
// pull out path and query
int queryStart = template.IndexOf('?');
if (queryStart == -1)
{
queryTemplate = string.Empty;
pathTemplate = template;
}
else
{
queryTemplate = template.Substring(queryStart + 1);
pathTemplate = template.Substring(0, queryStart);
}
template = null; // to ensure we don't accidentally reference this variable any more
// setup path template and validate
if (!string.IsNullOrEmpty(pathTemplate))
{
int startIndex = 0;
while (startIndex < pathTemplate.Length)
{
// Identify the next segment
int endIndex = pathTemplate.IndexOf('/', startIndex);
string segment;
if (endIndex != -1)
{
segment = pathTemplate.Substring(startIndex, endIndex + 1 - startIndex);
startIndex = endIndex + 1;
}
else
{
segment = pathTemplate.Substring(startIndex);
startIndex = pathTemplate.Length;
}
// Checking for wildcard segment ("*") or ("{*<var name>}")
UriTemplatePartType wildcardType;
if ((startIndex == pathTemplate.Length) &&
UriTemplateHelpers.IsWildcardSegment(segment, out wildcardType))
{
switch (wildcardType)
{
case UriTemplatePartType.Literal:
this.wildcard = new WildcardInfo(this);
break;
case UriTemplatePartType.Variable:
this.wildcard = new WildcardInfo(this, segment);
break;
default:
Fx.Assert("Error in identifying the type of the wildcard segment");
break;
}
}
else
{
this.segments.Add(UriTemplatePathSegment.CreateFromUriTemplate(segment, this));
}
}
}
// setup query template and validate
if (!string.IsNullOrEmpty(queryTemplate))
{
int startIndex = 0;
while (startIndex < queryTemplate.Length)
{
// Identify the next query part
int endIndex = queryTemplate.IndexOf('&', startIndex);
int queryPartStart = startIndex;
int queryPartEnd;
if (endIndex != -1)
{
queryPartEnd = endIndex;
startIndex = endIndex + 1;
if (startIndex >= queryTemplate.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.UTQueryCannotEndInAmpersand, this.originalTemplate)));
}
}
else
{
queryPartEnd = queryTemplate.Length;
startIndex = queryTemplate.Length;
}
// Checking query part type; identifying key and value
int equalSignIndex = queryTemplate.IndexOf('=', queryPartStart, queryPartEnd - queryPartStart);
string key;
string value;
if (equalSignIndex >= 0)
{
key = queryTemplate.Substring(queryPartStart, equalSignIndex - queryPartStart);
value = queryTemplate.Substring(equalSignIndex + 1, queryPartEnd - equalSignIndex - 1);
}
else
{
key = queryTemplate.Substring(queryPartStart, queryPartEnd - queryPartStart);
value = null;
}
if (string.IsNullOrEmpty(key))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.UTQueryCannotHaveEmptyName, this.originalTemplate)));
}
if (UriTemplateHelpers.IdentifyPartType(key) != UriTemplatePartType.Literal)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("template", SR.GetString(
SR.UTQueryMustHaveLiteralNames, this.originalTemplate));
}
// Adding a new entry to the queries dictionary
key = UrlUtility.UrlDecode(key, Encoding.UTF8);
if (this.queries.ContainsKey(key))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
SR.UTQueryNamesMustBeUnique, this.originalTemplate)));
}
this.queries.Add(key, UriTemplateQueryValue.CreateFromUriTemplate(value, this));
}
}
// Process additional defaults (if has some) :
if (additionalDefaults != null)
{
if (this.variables == null)
{
if (additionalDefaults.Count > 0)
{
this.additionalDefaults = new Dictionary<string, string>(additionalDefaults, StringComparer.OrdinalIgnoreCase);
}
}
else
{
foreach (KeyValuePair<string, string> kvp in additionalDefaults)
{
string uppercaseKey = kvp.Key.ToUpperInvariant();
if ((this.variables.DefaultValues != null) && this.variables.DefaultValues.ContainsKey(uppercaseKey))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("additionalDefaults",
SR.GetString(SR.UTAdditionalDefaultIsInvalid, kvp.Key, this.originalTemplate));
}
if (this.variables.PathSegmentVariableNames.Contains(uppercaseKey))
{
this.variables.AddDefaultValue(uppercaseKey, kvp.Value);
}
else if (this.variables.QueryValueVariableNames.Contains(uppercaseKey))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTDefaultValueToQueryVarFromAdditionalDefaults, this.originalTemplate,
uppercaseKey)));
}
else if (string.Compare(kvp.Value, UriTemplate.NullableDefault, StringComparison.OrdinalIgnoreCase) == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTNullableDefaultAtAdditionalDefaults, this.originalTemplate,
uppercaseKey)));
}
else
{
if (this.additionalDefaults == null)
{
this.additionalDefaults = new Dictionary<string, string>(additionalDefaults.Count, StringComparer.OrdinalIgnoreCase);
}
this.additionalDefaults.Add(kvp.Key, kvp.Value);
}
}
}
}
// Validate defaults (if should)
if ((this.variables != null) && (this.variables.DefaultValues != null))
{
this.variables.ValidateDefaults(out this.firstOptionalSegment);
}
else
{
this.firstOptionalSegment = this.segments.Count;
}
}
public IDictionary<string, string> Defaults
{
get
{
if (this.defaults == null)
{
Interlocked.CompareExchange<IDictionary<string, string>>(ref this.defaults, new UriTemplateDefaults(this), null);
}
return this.defaults;
}
}
public bool IgnoreTrailingSlash
{
get
{
return this.ignoreTrailingSlash;
}
}
public ReadOnlyCollection<string> PathSegmentVariableNames
{
get
{
if (this.variables == null)
{
return VariablesCollection.EmptyCollection;
}
else
{
return this.variables.PathSegmentVariableNames;
}
}
}
public ReadOnlyCollection<string> QueryValueVariableNames
{
get
{
if (this.variables == null)
{
return VariablesCollection.EmptyCollection;
}
else
{
return this.variables.QueryValueVariableNames;
}
}
}
internal bool HasNoVariables
{
get
{
return (this.variables == null);
}
}
internal bool HasWildcard
{
get
{
return (this.wildcard != null);
}
}
// make a Uri by subbing in the values, throw on bad input
public Uri BindByName(Uri baseAddress, IDictionary<string, string> parameters)
{
return BindByName(baseAddress, parameters, false);
}
public Uri BindByName(Uri baseAddress, IDictionary<string, string> parameters, bool omitDefaults)
{
if (baseAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddress");
}
if (!baseAddress.IsAbsoluteUri)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("baseAddress", SR.GetString(
SR.UTBadBaseAddress));
}
BindInformation bindInfo;
if (this.variables == null)
{
bindInfo = PrepareBindInformation(parameters, omitDefaults);
}
else
{
bindInfo = this.variables.PrepareBindInformation(parameters, omitDefaults);
}
return Bind(baseAddress, bindInfo, omitDefaults);
}
public Uri BindByName(Uri baseAddress, NameValueCollection parameters)
{
return BindByName(baseAddress, parameters, false);
}
public Uri BindByName(Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
{
if (baseAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddress");
}
if (!baseAddress.IsAbsoluteUri)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("baseAddress", SR.GetString(
SR.UTBadBaseAddress));
}
BindInformation bindInfo;
if (this.variables == null)
{
bindInfo = PrepareBindInformation(parameters, omitDefaults);
}
else
{
bindInfo = this.variables.PrepareBindInformation(parameters, omitDefaults);
}
return Bind(baseAddress, bindInfo, omitDefaults);
}
public Uri BindByPosition(Uri baseAddress, params string[] values)
{
if (baseAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddress");
}
if (!baseAddress.IsAbsoluteUri)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("baseAddress", SR.GetString(
SR.UTBadBaseAddress));
}
BindInformation bindInfo;
if (this.variables == null)
{
if (values.Length > 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(
SR.UTBindByPositionNoVariables, this.originalTemplate, values.Length)));
}
bindInfo = new BindInformation(this.additionalDefaults);
}
else
{
bindInfo = this.variables.PrepareBindInformation(values);
}
return Bind(baseAddress, bindInfo, false);
}
// A note about UriTemplate equivalency:
// The introduction of defaults and, more over, terminal defaults, broke the simple
// intuative notion of equivalency between templates. We will define equivalent
// templates as such based on the structure of them and not based on the set of uri
// that are matched by them. The result is that, even though they do not match the
// same set of uri's, the following templates are equivalent:
// - "/foo/{bar}"
// - "/foo/{bar=xyz}"
// A direct result from the support for 'terminal defaults' is that the IsPathEquivalentTo
// method, which was used both to determine the equivalence between templates, as
// well as verify that all the templates, combined together in the same PathEquivalentSet,
// are equivalent in thier path is no longer valid for both purposes. We will break
// it to two distinct methods, each will be called in a different case.
public bool IsEquivalentTo(UriTemplate other)
{
if (other == null)
{
return false;
}
if (other.segments == null || other.queries == null)
{
// they never are null, but PreSharp is complaining,
// and warning suppression isn't working
return false;
}
if (!IsPathFullyEquivalent(other))
{
return false;
}
if (!IsQueryEquivalent(other))
{
return false;
}
Fx.Assert(UriTemplateEquivalenceComparer.Instance.GetHashCode(this) == UriTemplateEquivalenceComparer.Instance.GetHashCode(other), "bad GetHashCode impl");
return true;
}
public UriTemplateMatch Match(Uri baseAddress, Uri candidate)
{
if (baseAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddress");
}
if (!baseAddress.IsAbsoluteUri)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("baseAddress", SR.GetString(
SR.UTBadBaseAddress));
}
if (candidate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("candidate");
}
// ensure that the candidate is 'under' the base address
if (!candidate.IsAbsoluteUri)
{
return null;
}
string basePath = UriTemplateHelpers.GetUriPath(baseAddress);
string candidatePath = UriTemplateHelpers.GetUriPath(candidate);
if (candidatePath.Length < basePath.Length)
{
return null;
}
if (!candidatePath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
{
return null;
}
// Identifying the relative segments \ checking matching to the path :
int numSegmentsInBaseAddress = baseAddress.Segments.Length;
string[] candidateSegments = candidate.Segments;
int numMatchedSegments;
Collection<string> relativeCandidateSegments;
if (!IsCandidatePathMatch(numSegmentsInBaseAddress, candidateSegments,
out numMatchedSegments, out relativeCandidateSegments))
{
return null;
}
// Checking matching to the query (if should) :
NameValueCollection candidateQuery = null;
if (!UriTemplateHelpers.CanMatchQueryTrivially(this))
{
candidateQuery = UriTemplateHelpers.ParseQueryString(candidate.Query);
if (!UriTemplateHelpers.CanMatchQueryInterestingly(this, candidateQuery, false))
{
return null;
}
}
// We matched; lets build the UriTemplateMatch
return CreateUriTemplateMatch(baseAddress, candidate, null, numMatchedSegments,
relativeCandidateSegments, candidateQuery);
}
public override string ToString()
{
return this.originalTemplate;
}
internal string AddPathVariable(UriTemplatePartType sourceNature, string varDeclaration)
{
bool hasDefaultValue;
return AddPathVariable(sourceNature, varDeclaration, out hasDefaultValue);
}
internal string AddPathVariable(UriTemplatePartType sourceNature, string varDeclaration,
out bool hasDefaultValue)
{
if (this.variables == null)
{
this.variables = new VariablesCollection(this);
}
return this.variables.AddPathVariable(sourceNature, varDeclaration, out hasDefaultValue);
}
internal string AddQueryVariable(string varDeclaration)
{
if (this.variables == null)
{
this.variables = new VariablesCollection(this);
}
return this.variables.AddQueryVariable(varDeclaration);
}
internal UriTemplateMatch CreateUriTemplateMatch(Uri baseUri, Uri uri, object data,
int numMatchedSegments, Collection<string> relativePathSegments, NameValueCollection uriQuery)
{
UriTemplateMatch result = new UriTemplateMatch();
result.RequestUri = uri;
result.BaseUri = baseUri;
if (uriQuery != null)
{
result.SetQueryParameters(uriQuery);
}
result.SetRelativePathSegments(relativePathSegments);
result.Data = data;
result.Template = this;
for (int i = 0; i < numMatchedSegments; i++)
{
this.segments[i].Lookup(result.RelativePathSegments[i], result.BoundVariables);
}
if (this.wildcard != null)
{
this.wildcard.Lookup(numMatchedSegments, result.RelativePathSegments,
result.BoundVariables);
}
else if (numMatchedSegments < this.segments.Count)
{
BindTerminalDefaults(numMatchedSegments, result.BoundVariables);
}
if (this.queries.Count > 0)
{
foreach (KeyValuePair<string, UriTemplateQueryValue> kvp in this.queries)
{
kvp.Value.Lookup(result.QueryParameters[kvp.Key], result.BoundVariables);
//UriTemplateHelpers.AssertCanonical(varName);
}
}
if (this.additionalDefaults != null)
{
foreach (KeyValuePair<string, string> kvp in this.additionalDefaults)
{
result.BoundVariables.Add(kvp.Key, UnescapeDefaultValue(kvp.Value));
}
}
Fx.Assert(result.RelativePathSegments.Count - numMatchedSegments >= 0, "bad segment computation");
result.SetWildcardPathSegmentsStart(numMatchedSegments);
return result;
}
internal bool IsPathPartiallyEquivalentAt(UriTemplate other, int segmentsCount)
{
// Refer to the note on template equivalency at IsEquivalentTo
// This method checks if any uri with given number of segments, which can be matched
// by this template, can be also matched by the other template.
Fx.Assert(segmentsCount >= this.firstOptionalSegment - 1, "How can that be? The Trie is constructed that way!");
Fx.Assert(segmentsCount <= this.segments.Count, "How can that be? The Trie is constructed that way!");
Fx.Assert(segmentsCount >= other.firstOptionalSegment - 1, "How can that be? The Trie is constructed that way!");
Fx.Assert(segmentsCount <= other.segments.Count, "How can that be? The Trie is constructed that way!");
for (int i = 0; i < segmentsCount; ++i)
{
if (!this.segments[i].IsEquivalentTo(other.segments[i],
((i == segmentsCount - 1) && (this.ignoreTrailingSlash || other.ignoreTrailingSlash))))
{
return false;
}
}
return true;
}
internal bool IsQueryEquivalent(UriTemplate other)
{
if (this.queries.Count != other.queries.Count)
{
return false;
}
foreach (string key in this.queries.Keys)
{
UriTemplateQueryValue utqv = this.queries[key];
UriTemplateQueryValue otherUtqv;
if (!other.queries.TryGetValue(key, out otherUtqv))
{
return false;
}
if (!utqv.IsEquivalentTo(otherUtqv))
{
return false;
}
}
return true;
}
internal static Uri RewriteUri(Uri uri, string host)
{
if (!string.IsNullOrEmpty(host))
{
string originalHostHeader = uri.Host + ((!uri.IsDefaultPort) ? ":" + uri.Port.ToString(CultureInfo.InvariantCulture) : string.Empty);
if (!String.Equals(originalHostHeader, host, StringComparison.OrdinalIgnoreCase))
{
Uri sourceUri = new Uri(String.Format(CultureInfo.InvariantCulture, "{0}://{1}", uri.Scheme, host));
return (new UriBuilder(uri) { Host = sourceUri.Host, Port = sourceUri.Port }).Uri;
}
}
return uri;
}
Uri Bind(Uri baseAddress, BindInformation bindInfo, bool omitDefaults)
{
UriBuilder result = new UriBuilder(baseAddress);
int parameterIndex = 0;
int lastPathParameter = ((this.variables == null) ? -1 : this.variables.PathSegmentVariableNames.Count - 1);
int lastPathParameterToBind;
if (lastPathParameter == -1)
{
lastPathParameterToBind = -1;
}
else if (omitDefaults)
{
lastPathParameterToBind = bindInfo.LastNonDefaultPathParameter;
}
else
{
lastPathParameterToBind = bindInfo.LastNonNullablePathParameter;
}
string[] parameters = bindInfo.NormalizedParameters;
IDictionary<string, string> extraQueryParameters = bindInfo.AdditionalParameters;
// Binding the path :
StringBuilder pathString = new StringBuilder(result.Path);
if (pathString[pathString.Length - 1] != '/')
{
pathString.Append('/');
}
if (lastPathParameterToBind < lastPathParameter)
{
// Binding all the parameters we need
int segmentIndex = 0;
while (parameterIndex <= lastPathParameterToBind)
{
Fx.Assert(segmentIndex < this.segments.Count,
"Calculation of LastNonDefaultPathParameter,lastPathParameter or parameterIndex failed");
this.segments[segmentIndex++].Bind(parameters, ref parameterIndex, pathString);
}
Fx.Assert(parameterIndex == lastPathParameterToBind + 1,
"That is the exit criteria from the loop");
// Maybe we have some literals yet to bind
Fx.Assert(segmentIndex < this.segments.Count,
"Calculation of LastNonDefaultPathParameter,lastPathParameter or parameterIndex failed");
while (this.segments[segmentIndex].Nature == UriTemplatePartType.Literal)
{
this.segments[segmentIndex++].Bind(parameters, ref parameterIndex, pathString);
Fx.Assert(parameterIndex == lastPathParameterToBind + 1,
"We have moved the parameter index in a literal binding");
Fx.Assert(segmentIndex < this.segments.Count,
"Calculation of LastNonDefaultPathParameter,lastPathParameter or parameterIndex failed");
}
// We're done; skip to the beggining of the query parameters
parameterIndex = lastPathParameter + 1;
}
else if (this.segments.Count > 0 || this.wildcard != null)
{
for (int i = 0; i < this.segments.Count; i++)
{
this.segments[i].Bind(parameters, ref parameterIndex, pathString);
}
if (this.wildcard != null)
{
this.wildcard.Bind(parameters, ref parameterIndex, pathString);
}
}
if (this.ignoreTrailingSlash && (pathString[pathString.Length - 1] == '/'))
{
pathString.Remove(pathString.Length - 1, 1);
}
result.Path = pathString.ToString();
// Binding the query :
if ((this.queries.Count != 0) || (extraQueryParameters != null))
{
StringBuilder query = new StringBuilder("");
foreach (string key in this.queries.Keys)
{
this.queries[key].Bind(key, parameters, ref parameterIndex, query);
}
if (extraQueryParameters != null)
{
foreach (string key in extraQueryParameters.Keys)
{
if (this.queries.ContainsKey(key.ToUpperInvariant()))
{
// This can only be if the key passed has the same name as some literal key
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("parameters", SR.GetString(
SR.UTBothLiteralAndNameValueCollectionKey, key));
}
string value = extraQueryParameters[key];
string escapedValue = (string.IsNullOrEmpty(value) ? string.Empty : UrlUtility.UrlEncode(value, Encoding.UTF8));
query.AppendFormat("&{0}={1}", UrlUtility.UrlEncode(key, Encoding.UTF8), escapedValue);
}
}
if (query.Length != 0)
{
query.Remove(0, 1); // remove extra leading '&'
}
result.Query = query.ToString();
}
// Adding the fragment (if needed)
if (this.fragment != null)
{
result.Fragment = this.fragment;
}
return result.Uri;
}
void BindTerminalDefaults(int numMatchedSegments, NameValueCollection boundParameters)
{
Fx.Assert(!this.HasWildcard, "There are no terminal default when ends with wildcard");
Fx.Assert(numMatchedSegments < this.segments.Count, "Otherwise - no defaults to bind");
Fx.Assert(this.variables != null, "Otherwise - no default values to bind");
Fx.Assert(this.variables.DefaultValues != null, "Otherwise - no default values to bind");
for (int i = numMatchedSegments; i < this.segments.Count; i++)
{
switch (this.segments[i].Nature)
{
case UriTemplatePartType.Variable:
{
UriTemplateVariablePathSegment vps = this.segments[i] as UriTemplateVariablePathSegment;
Fx.Assert(vps != null, "How can that be? That its nature");
this.variables.LookupDefault(vps.VarName, boundParameters);
}
break;
default:
Fx.Assert("We only support terminal defaults on Variable segments");
break;
}
}
}
bool IsCandidatePathMatch(int numSegmentsInBaseAddress, string[] candidateSegments,
out int numMatchedSegments, out Collection<string> relativeSegments)
{
int numRelativeSegments = candidateSegments.Length - numSegmentsInBaseAddress;
Fx.Assert(numRelativeSegments >= 0, "bad segments num");
relativeSegments = new Collection<string>();
bool isStillMatch = true;
int relativeSegmentsIndex = 0;
while (isStillMatch && (relativeSegmentsIndex < numRelativeSegments))
{
string segment = candidateSegments[relativeSegmentsIndex + numSegmentsInBaseAddress];
// Mathcing to next regular segment in the template (if there is one); building the wire segment representation
if (relativeSegmentsIndex < this.segments.Count)
{
bool ignoreSlash = (this.ignoreTrailingSlash && (relativeSegmentsIndex == numRelativeSegments - 1));
UriTemplateLiteralPathSegment lps = UriTemplateLiteralPathSegment.CreateFromWireData(segment);
if (!this.segments[relativeSegmentsIndex].IsMatch(lps, ignoreSlash))
{
isStillMatch = false;
break;
}
string relPathSeg = Uri.UnescapeDataString(segment);
if (lps.EndsWithSlash)
{
Fx.Assert(relPathSeg.EndsWith("/", StringComparison.Ordinal), "problem with relative path segment");
relPathSeg = relPathSeg.Substring(0, relPathSeg.Length - 1); // trim slash
}
relativeSegments.Add(relPathSeg);
}
// Checking if the template has a wild card ('*') or a final star var segment ("{*<var name>}"
else if (this.HasWildcard)
{
break;
}
else
{
isStillMatch = false;
break;
}
relativeSegmentsIndex++;
}
if (isStillMatch)
{
numMatchedSegments = relativeSegmentsIndex;
// building the wire representation to segments that were matched to a wild card
if (relativeSegmentsIndex < numRelativeSegments)
{
while (relativeSegmentsIndex < numRelativeSegments)
{
string relPathSeg = Uri.UnescapeDataString(candidateSegments[relativeSegmentsIndex + numSegmentsInBaseAddress]);
if (relPathSeg.EndsWith("/", StringComparison.Ordinal))
{
relPathSeg = relPathSeg.Substring(0, relPathSeg.Length - 1); // trim slash
}
relativeSegments.Add(relPathSeg);
relativeSegmentsIndex++;
}
}
// Checking if we matched all required segments already
else if (numMatchedSegments < this.firstOptionalSegment)
{
isStillMatch = false;
}
}
else
{
numMatchedSegments = 0;
}
return isStillMatch;
}
bool IsPathFullyEquivalent(UriTemplate other)
{
// Refer to the note on template equivalency at IsEquivalentTo
// This method checks if both templates has a fully equivalent path.
if (this.HasWildcard != other.HasWildcard)
{
return false;
}
if (this.segments.Count != other.segments.Count)
{
return false;
}
for (int i = 0; i < this.segments.Count; ++i)
{
if (!this.segments[i].IsEquivalentTo(other.segments[i],
(i == this.segments.Count - 1) && !this.HasWildcard && (this.ignoreTrailingSlash || other.ignoreTrailingSlash)))
{
return false;
}
}
return true;
}
BindInformation PrepareBindInformation(IDictionary<string, string> parameters, bool omitDefaults)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
IDictionary<string, string> extraParameters = new Dictionary<string, string>(UriTemplateHelpers.GetQueryKeyComparer());
foreach (KeyValuePair<string, string> kvp in parameters)
{
if (string.IsNullOrEmpty(kvp.Key))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("parameters",
SR.GetString(SR.UTBindByNameCalledWithEmptyKey));
}
extraParameters.Add(kvp);
}
BindInformation bindInfo;
ProcessDefaultsAndCreateBindInfo(omitDefaults, extraParameters, out bindInfo);
return bindInfo;
}
BindInformation PrepareBindInformation(NameValueCollection parameters, bool omitDefaults)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
IDictionary<string, string> extraParameters = new Dictionary<string, string>(UriTemplateHelpers.GetQueryKeyComparer());
foreach (string key in parameters.AllKeys)
{
if (string.IsNullOrEmpty(key))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("parameters",
SR.GetString(SR.UTBindByNameCalledWithEmptyKey));
}
extraParameters.Add(key, parameters[key]);
}
BindInformation bindInfo;
ProcessDefaultsAndCreateBindInfo(omitDefaults, extraParameters, out bindInfo);
return bindInfo;
}
void ProcessDefaultsAndCreateBindInfo(bool omitDefaults, IDictionary<string, string> extraParameters,
out BindInformation bindInfo)
{
Fx.Assert(extraParameters != null, "We are expected to create it at the calling PrepareBindInformation");
if (this.additionalDefaults != null)
{
if (omitDefaults)
{
foreach (KeyValuePair<string, string> kvp in this.additionalDefaults)
{
string extraParameter;
if (extraParameters.TryGetValue(kvp.Key, out extraParameter))
{
if (string.Compare(extraParameter, kvp.Value, StringComparison.Ordinal) == 0)
{
extraParameters.Remove(kvp.Key);
}
}
}
}
else
{
foreach (KeyValuePair<string, string> kvp in this.additionalDefaults)
{
if (!extraParameters.ContainsKey(kvp.Key))
{
extraParameters.Add(kvp.Key, kvp.Value);
}
}
}
}
if (extraParameters.Count == 0)
{
extraParameters = null;
}
bindInfo = new BindInformation(extraParameters);
}
string UnescapeDefaultValue(string escapedValue)
{
if (string.IsNullOrEmpty(escapedValue))
{
return escapedValue;
}
if (this.unescapedDefaults == null)
{
this.unescapedDefaults = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
}
return this.unescapedDefaults.GetOrAdd(escapedValue, Uri.UnescapeDataString);
}
struct BindInformation
{
IDictionary<string, string> additionalParameters;
int lastNonDefaultPathParameter;
int lastNonNullablePathParameter;
string[] normalizedParameters;
public BindInformation(string[] normalizedParameters, int lastNonDefaultPathParameter,
int lastNonNullablePathParameter, IDictionary<string, string> additionalParameters)
{
this.normalizedParameters = normalizedParameters;
this.lastNonDefaultPathParameter = lastNonDefaultPathParameter;
this.lastNonNullablePathParameter = lastNonNullablePathParameter;
this.additionalParameters = additionalParameters;
}
public BindInformation(IDictionary<string, string> additionalParameters)
{
this.normalizedParameters = null;
this.lastNonDefaultPathParameter = -1;
this.lastNonNullablePathParameter = -1;
this.additionalParameters = additionalParameters;
}
public IDictionary<string, string> AdditionalParameters
{
get
{
return this.additionalParameters;
}
}
public int LastNonDefaultPathParameter
{
get
{
return this.lastNonDefaultPathParameter;
}
}
public int LastNonNullablePathParameter
{
get
{
return this.lastNonNullablePathParameter;
}
}
public string[] NormalizedParameters
{
get
{
return this.normalizedParameters;
}
}
}
class UriTemplateDefaults : IDictionary<string, string>
{
Dictionary<string, string> defaults;
ReadOnlyCollection<string> keys;
ReadOnlyCollection<string> values;
public UriTemplateDefaults(UriTemplate template)
{
this.defaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if ((template.variables != null) && (template.variables.DefaultValues != null))
{
foreach (KeyValuePair<string, string> kvp in template.variables.DefaultValues)
{
this.defaults.Add(kvp.Key, kvp.Value);
}
}
if (template.additionalDefaults != null)
{
foreach (KeyValuePair<string, string> kvp in template.additionalDefaults)
{
this.defaults.Add(kvp.Key.ToUpperInvariant(), kvp.Value);
}
}
this.keys = new ReadOnlyCollection<string>(new List<string>(this.defaults.Keys));
this.values = new ReadOnlyCollection<string>(new List<string>(this.defaults.Values));
}
// ICollection<KeyValuePair<string, string>> Members
public int Count
{
get
{
return this.defaults.Count;
}
}
public bool IsReadOnly
{
get
{
return true;
}
}
// IDictionary<string, string> Members
public ICollection<string> Keys
{
get
{
return this.keys;
}
}
public ICollection<string> Values
{
get
{
return this.values;
}
}
public string this[string key]
{
get
{
return this.defaults[key];
}
set
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
}
public void Add(string key, string value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
public void Add(KeyValuePair<string, string> item)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
public void Clear()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
public bool Contains(KeyValuePair<string, string> item)
{
return (this.defaults as ICollection<KeyValuePair<string, string>>).Contains(item);
}
public bool ContainsKey(string key)
{
return this.defaults.ContainsKey(key);
}
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
{
(this.defaults as ICollection<KeyValuePair<string, string>>).CopyTo(array, arrayIndex);
}
// IEnumerable<KeyValuePair<string, string>> Members
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return this.defaults.GetEnumerator();
}
public bool Remove(string key)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
public bool Remove(KeyValuePair<string, string> item)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
SR.GetString(SR.UTDefaultValuesAreImmutable)));
}
// IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.defaults.GetEnumerator();
}
public bool TryGetValue(string key, out string value)
{
return this.defaults.TryGetValue(key, out value);
}
}
class VariablesCollection
{
readonly UriTemplate owner;
static ReadOnlyCollection<string> emptyStringCollection = null;
Dictionary<string, string> defaultValues; // key is the variable name (in uppercase; as appear in the variable names lists)
int firstNullablePathVariable;
List<string> pathSegmentVariableNames; // ToUpperInvariant, in order they occur in the original template string
ReadOnlyCollection<string> pathSegmentVariableNamesSnapshot = null;
List<UriTemplatePartType> pathSegmentVariableNature;
List<string> queryValueVariableNames; // ToUpperInvariant, in order they occur in the original template string
ReadOnlyCollection<string> queryValueVariableNamesSnapshot = null;
public VariablesCollection(UriTemplate owner)
{
this.owner = owner;
this.pathSegmentVariableNames = new List<string>();
this.pathSegmentVariableNature = new List<UriTemplatePartType>();
this.queryValueVariableNames = new List<string>();
this.firstNullablePathVariable = -1;
}
public static ReadOnlyCollection<string> EmptyCollection
{
get
{
if (emptyStringCollection == null)
{
emptyStringCollection = new ReadOnlyCollection<string>(new List<string>());
}
return emptyStringCollection;
}
}
public Dictionary<string, string> DefaultValues
{
get
{
return this.defaultValues;
}
}
public ReadOnlyCollection<string> PathSegmentVariableNames
{
get
{
if (this.pathSegmentVariableNamesSnapshot == null)
{
Interlocked.CompareExchange<ReadOnlyCollection<string>>(ref this.pathSegmentVariableNamesSnapshot, new ReadOnlyCollection<string>(
this.pathSegmentVariableNames), null);
}
return this.pathSegmentVariableNamesSnapshot;
}
}
public ReadOnlyCollection<string> QueryValueVariableNames
{
get
{
if (this.queryValueVariableNamesSnapshot == null)
{
Interlocked.CompareExchange<ReadOnlyCollection<string>>(ref this.queryValueVariableNamesSnapshot, new ReadOnlyCollection<string>(
this.queryValueVariableNames), null);
}
return this.queryValueVariableNamesSnapshot;
}
}
public void AddDefaultValue(string varName, string value)
{
int varIndex = this.pathSegmentVariableNames.IndexOf(varName);
Fx.Assert(varIndex != -1, "Adding default value is restricted to path variables");
if ((this.owner.wildcard != null) && this.owner.wildcard.HasVariable &&
(varIndex == this.pathSegmentVariableNames.Count - 1))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTStarVariableWithDefaultsFromAdditionalDefaults,
this.owner.originalTemplate, varName)));
}
if (this.pathSegmentVariableNature[varIndex] != UriTemplatePartType.Variable)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTDefaultValueToCompoundSegmentVarFromAdditionalDefaults,
this.owner.originalTemplate, varName)));
}
if (string.IsNullOrEmpty(value) ||
(string.Compare(value, UriTemplate.NullableDefault, StringComparison.OrdinalIgnoreCase) == 0))
{
value = null;
}
if (this.defaultValues == null)
{
this.defaultValues = new Dictionary<string, string>();
}
this.defaultValues.Add(varName, value);
}
public string AddPathVariable(UriTemplatePartType sourceNature, string varDeclaration, out bool hasDefaultValue)
{
Fx.Assert(sourceNature != UriTemplatePartType.Literal, "Literal path segments can't be the source for path variables");
string varName;
string defaultValue;
ParseVariableDeclaration(varDeclaration, out varName, out defaultValue);
hasDefaultValue = (defaultValue != null);
if (varName.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, this.owner.originalTemplate, UriTemplate.WildcardPath)));
}
string uppercaseVarName = varName.ToUpperInvariant();
if (this.pathSegmentVariableNames.Contains(uppercaseVarName) ||
this.queryValueVariableNames.Contains(uppercaseVarName))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTVarNamesMustBeUnique, this.owner.originalTemplate, varName)));
}
this.pathSegmentVariableNames.Add(uppercaseVarName);
this.pathSegmentVariableNature.Add(sourceNature);
if (hasDefaultValue)
{
if (defaultValue == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTInvalidDefaultPathValue, this.owner.originalTemplate,
varDeclaration, varName)));
}
if (string.Compare(defaultValue, UriTemplate.NullableDefault, StringComparison.OrdinalIgnoreCase) == 0)
{
defaultValue = null;
}
if (this.defaultValues == null)
{
this.defaultValues = new Dictionary<string, string>();
}
this.defaultValues.Add(uppercaseVarName, defaultValue);
}
return uppercaseVarName;
}
public string AddQueryVariable(string varDeclaration)
{
string varName;
string defaultValue;
ParseVariableDeclaration(varDeclaration, out varName, out defaultValue);
if (varName.IndexOf(UriTemplate.WildcardPath, StringComparison.Ordinal) != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidWildcardInVariableOrLiteral, this.owner.originalTemplate, UriTemplate.WildcardPath)));
}
if (defaultValue != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTDefaultValueToQueryVar, this.owner.originalTemplate,
varDeclaration, varName)));
}
string uppercaseVarName = varName.ToUpperInvariant();
if (this.pathSegmentVariableNames.Contains(uppercaseVarName) ||
this.queryValueVariableNames.Contains(uppercaseVarName))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTVarNamesMustBeUnique, this.owner.originalTemplate, varName)));
}
this.queryValueVariableNames.Add(uppercaseVarName);
return uppercaseVarName;
}
public void LookupDefault(string varName, NameValueCollection boundParameters)
{
Fx.Assert(this.defaultValues.ContainsKey(varName), "Otherwise, we don't have a value to bind");
boundParameters.Add(varName, owner.UnescapeDefaultValue(this.defaultValues[varName]));
}
public BindInformation PrepareBindInformation(IDictionary<string, string> parameters, bool omitDefaults)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
string[] normalizedParameters = PrepareNormalizedParameters();
IDictionary<string, string> extraParameters = null;
foreach (string key in parameters.Keys)
{
ProcessBindParameter(key, parameters[key], normalizedParameters, ref extraParameters);
}
BindInformation bindInfo;
ProcessDefaultsAndCreateBindInfo(omitDefaults, normalizedParameters, extraParameters, out bindInfo);
return bindInfo;
}
public BindInformation PrepareBindInformation(NameValueCollection parameters, bool omitDefaults)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
}
string[] normalizedParameters = PrepareNormalizedParameters();
IDictionary<string, string> extraParameters = null;
foreach (string key in parameters.AllKeys)
{
ProcessBindParameter(key, parameters[key], normalizedParameters, ref extraParameters);
}
BindInformation bindInfo;
ProcessDefaultsAndCreateBindInfo(omitDefaults, normalizedParameters, extraParameters, out bindInfo);
return bindInfo;
}
public BindInformation PrepareBindInformation(params string[] parameters)
{
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("values");
}
if ((parameters.Length < this.pathSegmentVariableNames.Count) ||
(parameters.Length > this.pathSegmentVariableNames.Count + this.queryValueVariableNames.Count))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTBindByPositionWrongCount, this.owner.originalTemplate,
this.pathSegmentVariableNames.Count, this.queryValueVariableNames.Count,
parameters.Length)));
}
string[] normalizedParameters;
if (parameters.Length == this.pathSegmentVariableNames.Count + this.queryValueVariableNames.Count)
{
normalizedParameters = parameters;
}
else
{
normalizedParameters = new string[this.pathSegmentVariableNames.Count + this.queryValueVariableNames.Count];
parameters.CopyTo(normalizedParameters, 0);
for (int i = parameters.Length; i < normalizedParameters.Length; i++)
{
normalizedParameters[i] = null;
}
}
int lastNonDefaultPathParameter;
int lastNonNullablePathParameter;
LoadDefaultsAndValidate(normalizedParameters, out lastNonDefaultPathParameter,
out lastNonNullablePathParameter);
return new BindInformation(normalizedParameters, lastNonDefaultPathParameter,
lastNonNullablePathParameter, this.owner.additionalDefaults);
}
public void ValidateDefaults(out int firstOptionalSegment)
{
Fx.Assert(this.defaultValues != null, "We are checking this condition from the c'tor");
Fx.Assert(this.pathSegmentVariableNames.Count > 0, "Otherwise, how can we have default values");
// Finding the first valid nullable defaults
for (int i = this.pathSegmentVariableNames.Count - 1; (i >= 0) && (this.firstNullablePathVariable == -1); i--)
{
string varName = this.pathSegmentVariableNames[i];
string defaultValue;
if (!this.defaultValues.TryGetValue(varName, out defaultValue))
{
this.firstNullablePathVariable = i + 1;
}
else if (defaultValue != null)
{
this.firstNullablePathVariable = i + 1;
}
}
if (this.firstNullablePathVariable == -1)
{
this.firstNullablePathVariable = 0;
}
// Making sure that there are no nullables to the left of the first valid nullable
if (this.firstNullablePathVariable > 1)
{
for (int i = this.firstNullablePathVariable - 2; i >= 0; i--)
{
string varName = this.pathSegmentVariableNames[i];
string defaultValue;
if (this.defaultValues.TryGetValue(varName, out defaultValue))
{
if (defaultValue == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTNullableDefaultMustBeFollowedWithNullables, this.owner.originalTemplate,
varName, this.pathSegmentVariableNames[i + 1])));
}
}
}
}
// Making sure that there are no Literals\WildCards to the right
// Based on the fact that only Variable Path Segments support default values,
// if firstNullablePathVariable=N and pathSegmentVariableNames.Count=M then
// the nature of the last M-N path segments should be StringNature.Variable; otherwise,
// there was a literal segment in between. Also, there shouldn't be a wildcard.
if (this.firstNullablePathVariable < this.pathSegmentVariableNames.Count)
{
if (this.owner.HasWildcard)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTNullableDefaultMustNotBeFollowedWithWildcard,
this.owner.originalTemplate, this.pathSegmentVariableNames[this.firstNullablePathVariable])));
}
for (int i = this.pathSegmentVariableNames.Count - 1; i >= this.firstNullablePathVariable; i--)
{
int segmentIndex = this.owner.segments.Count - (this.pathSegmentVariableNames.Count - i);
if (this.owner.segments[segmentIndex].Nature != UriTemplatePartType.Variable)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTNullableDefaultMustNotBeFollowedWithLiteral,
this.owner.originalTemplate, this.pathSegmentVariableNames[this.firstNullablePathVariable],
this.owner.segments[segmentIndex].OriginalSegment)));
}
}
}
// Now that we have the firstNullablePathVariable set, lets calculate the firstOptionalSegment.
// We already knows that the last M-N path segments (when M=pathSegmentVariableNames.Count and
// N=firstNullablePathVariable) are optional (see the previos comment). We will start there and
// move to the left, stopping at the first segment, which is not a variable or is a variable
// and doesn't have a default value.
int numNullablePathVariables = (this.pathSegmentVariableNames.Count - this.firstNullablePathVariable);
firstOptionalSegment = this.owner.segments.Count - numNullablePathVariables;
if (!this.owner.HasWildcard)
{
while (firstOptionalSegment > 0)
{
UriTemplatePathSegment ps = this.owner.segments[firstOptionalSegment - 1];
if (ps.Nature != UriTemplatePartType.Variable)
{
break;
}
UriTemplateVariablePathSegment vps = (ps as UriTemplateVariablePathSegment);
Fx.Assert(vps != null, "Should be; that's his nature");
if (!this.defaultValues.ContainsKey(vps.VarName))
{
break;
}
firstOptionalSegment--;
}
}
}
void AddAdditionalDefaults(ref IDictionary<string, string> extraParameters)
{
if (extraParameters == null)
{
extraParameters = this.owner.additionalDefaults;
}
else
{
foreach (KeyValuePair<string, string> kvp in this.owner.additionalDefaults)
{
if (!extraParameters.ContainsKey(kvp.Key))
{
extraParameters.Add(kvp.Key, kvp.Value);
}
}
}
}
void LoadDefaultsAndValidate(string[] normalizedParameters, out int lastNonDefaultPathParameter,
out int lastNonNullablePathParameter)
{
// First step - loading defaults
for (int i = 0; i < this.pathSegmentVariableNames.Count; i++)
{
if (string.IsNullOrEmpty(normalizedParameters[i]) && (this.defaultValues != null))
{
this.defaultValues.TryGetValue(this.pathSegmentVariableNames[i], out normalizedParameters[i]);
}
}
// Second step - calculating bind constrains
lastNonDefaultPathParameter = this.pathSegmentVariableNames.Count - 1;
if ((this.defaultValues != null) &&
(this.owner.segments[this.owner.segments.Count - 1].Nature != UriTemplatePartType.Literal))
{
bool foundNonDefaultPathParameter = false;
while (!foundNonDefaultPathParameter && (lastNonDefaultPathParameter >= 0))
{
string defaultValue;
if (this.defaultValues.TryGetValue(this.pathSegmentVariableNames[lastNonDefaultPathParameter],
out defaultValue))
{
if (string.Compare(normalizedParameters[lastNonDefaultPathParameter],
defaultValue, StringComparison.Ordinal) != 0)
{
foundNonDefaultPathParameter = true;
}
else
{
lastNonDefaultPathParameter--;
}
}
else
{
foundNonDefaultPathParameter = true;
}
}
}
if (this.firstNullablePathVariable > lastNonDefaultPathParameter)
{
lastNonNullablePathParameter = this.firstNullablePathVariable - 1;
}
else
{
lastNonNullablePathParameter = lastNonDefaultPathParameter;
}
// Third step - validate
for (int i = 0; i <= lastNonNullablePathParameter; i++)
{
// Skip validation for terminating star variable segment :
if (this.owner.HasWildcard && this.owner.wildcard.HasVariable &&
(i == this.pathSegmentVariableNames.Count - 1))
{
continue;
}
// Validate
if (string.IsNullOrEmpty(normalizedParameters[i]))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("parameters",
SR.GetString(SR.BindUriTemplateToNullOrEmptyPathParam, this.pathSegmentVariableNames[i]));
}
}
}
void ParseVariableDeclaration(string varDeclaration, out string varName, out string defaultValue)
{
if ((varDeclaration.IndexOf('{') != -1) || (varDeclaration.IndexOf('}') != -1))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidVarDeclaration, this.owner.originalTemplate, varDeclaration)));
}
int equalSignIndex = varDeclaration.IndexOf('=');
switch (equalSignIndex)
{
case -1:
varName = varDeclaration;
defaultValue = null;
break;
case 0:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidVarDeclaration, this.owner.originalTemplate, varDeclaration)));
default:
varName = varDeclaration.Substring(0, equalSignIndex);
defaultValue = varDeclaration.Substring(equalSignIndex + 1);
if (defaultValue.IndexOf('=') != -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(
SR.GetString(SR.UTInvalidVarDeclaration, this.owner.originalTemplate, varDeclaration)));
}
break;
}
}
string[] PrepareNormalizedParameters()
{
string[] normalizedParameters = new string[this.pathSegmentVariableNames.Count + this.queryValueVariableNames.Count];
for (int i = 0; i < normalizedParameters.Length; i++)
{
normalizedParameters[i] = null;
}
return normalizedParameters;
}
void ProcessBindParameter(string name, string value, string[] normalizedParameters,
ref IDictionary<string, string> extraParameters)
{
if (string.IsNullOrEmpty(name))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("parameters",
SR.GetString(SR.UTBindByNameCalledWithEmptyKey));
}
string uppercaseVarName = name.ToUpperInvariant();
int pathVarIndex = this.pathSegmentVariableNames.IndexOf(uppercaseVarName);
if (pathVarIndex != -1)
{
normalizedParameters[pathVarIndex] = (string.IsNullOrEmpty(value) ? string.Empty : value);
return;
}
int queryVarIndex = this.queryValueVariableNames.IndexOf(uppercaseVarName);
if (queryVarIndex != -1)
{
normalizedParameters[this.pathSegmentVariableNames.Count + queryVarIndex] = (string.IsNullOrEmpty(value) ? string.Empty : value);
return;
}
if (extraParameters == null)
{
extraParameters = new Dictionary<string, string>(UriTemplateHelpers.GetQueryKeyComparer());
}
extraParameters.Add(name, value);
}
void ProcessDefaultsAndCreateBindInfo(bool omitDefaults, string[] normalizedParameters,
IDictionary<string, string> extraParameters, out BindInformation bindInfo)
{
int lastNonDefaultPathParameter;
int lastNonNullablePathParameter;
LoadDefaultsAndValidate(normalizedParameters, out lastNonDefaultPathParameter,
out lastNonNullablePathParameter);
if (this.owner.additionalDefaults != null)
{
if (omitDefaults)
{
RemoveAdditionalDefaults(ref extraParameters);
}
else
{
AddAdditionalDefaults(ref extraParameters);
}
}
bindInfo = new BindInformation(normalizedParameters, lastNonDefaultPathParameter,
lastNonNullablePathParameter, extraParameters);
}
void RemoveAdditionalDefaults(ref IDictionary<string, string> extraParameters)
{
if (extraParameters == null)
{
return;
}
foreach (KeyValuePair<string, string> kvp in this.owner.additionalDefaults)
{
string extraParameter;
if (extraParameters.TryGetValue(kvp.Key, out extraParameter))
{
if (string.Compare(extraParameter, kvp.Value, StringComparison.Ordinal) == 0)
{
extraParameters.Remove(kvp.Key);
}
}
}
if (extraParameters.Count == 0)
{
extraParameters = null;
}
}
}
class WildcardInfo
{
readonly UriTemplate owner;
readonly string varName;
public WildcardInfo(UriTemplate owner)
{
this.varName = null;
this.owner = owner;
}
public WildcardInfo(UriTemplate owner, string segment)
{
Fx.Assert(!segment.EndsWith("/", StringComparison.Ordinal), "We are expecting to check this earlier");
bool hasDefault;
this.varName = owner.AddPathVariable(UriTemplatePartType.Variable,
segment.Substring(1 + WildcardPath.Length, segment.Length - 2 - WildcardPath.Length),
out hasDefault);
// Since this is a terminating star segment there shouldn't be a default
if (hasDefault)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.UTStarVariableWithDefaults, owner.originalTemplate,
segment, this.varName)));
}
this.owner = owner;
}
internal bool HasVariable
{
get
{
return (!string.IsNullOrEmpty(this.varName));
}
}
public void Bind(string[] values, ref int valueIndex, StringBuilder path)
{
if (HasVariable)
{
Fx.Assert(valueIndex < values.Length, "Not enough values to bind");
if (string.IsNullOrEmpty(values[valueIndex]))
{
valueIndex++;
}
else
{
path.Append(values[valueIndex++]);
}
}
}
public void Lookup(int numMatchedSegments, Collection<string> relativePathSegments,
NameValueCollection boundParameters)
{
Fx.Assert(numMatchedSegments == this.owner.segments.Count, "We should have matched the other segments");
if (HasVariable)
{
StringBuilder remainingPath = new StringBuilder();
for (int i = numMatchedSegments; i < relativePathSegments.Count; i++)
{
if (i < relativePathSegments.Count - 1)
{
remainingPath.AppendFormat("{0}/", relativePathSegments[i]);
}
else
{
remainingPath.Append(relativePathSegments[i]);
}
}
boundParameters.Add(this.varName, remainingPath.ToString());
}
}
}
}
}
|