PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/Bundles/Raven.Bundles.UniqueConstraints/Util.cs

https://github.com/nwendel/ravendb
C# | 56 lines | 49 code | 6 blank | 1 comment | 9 complexity | 59bce110fac3ee114b84f1a2e02475ff MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, CC-BY-SA-3.0
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using Raven.Imports.Newtonsoft.Json.Linq;
  5. using Raven.Json.Linq;
  6. namespace Raven.Bundles.UniqueConstraints
  7. {
  8. public static class Util
  9. {
  10. public static string EscapeUniqueValue(object value, bool caseInsensitive = false)
  11. {
  12. var stringToEscape = value.ToString();
  13. if (caseInsensitive)
  14. stringToEscape = stringToEscape.ToLowerInvariant();
  15. var escapeDataString = Uri.EscapeDataString(stringToEscape);
  16. if (stringToEscape == escapeDataString)
  17. return stringToEscape;
  18. // to avoid issues with ids, we encode the entire thing as safe Base64
  19. return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToEscape));
  20. }
  21. public static UniqueConstraint GetConstraint(RavenJToken property)
  22. {
  23. switch (property.Type)
  24. {
  25. case JTokenType.String: // backward compatability
  26. return new UniqueConstraint { PropName = property.Value<string>() };
  27. case JTokenType.Object:
  28. return new UniqueConstraint { PropName = property.Value<string>("Name"), CaseInsensitive = property.Value<bool>("CaseInsensitive") };
  29. default:
  30. throw new ArgumentOutOfRangeException(property.Type.ToString());
  31. }
  32. }
  33. public static bool TryGetUniqueValues(RavenJToken prop, out string[] uniqueValues)
  34. {
  35. if (prop == null || prop.Type == JTokenType.Null)
  36. {
  37. uniqueValues = null;
  38. return false;
  39. }
  40. var array = prop as RavenJArray;
  41. uniqueValues = array != null ? array.Select(p => p.Value<string>()).ToArray() : new[] { prop.Value<string>() };
  42. return true;
  43. }
  44. }
  45. public class UniqueConstraint
  46. {
  47. public string PropName { get; set; }
  48. public bool CaseInsensitive { get; set; }
  49. }
  50. }