Last active
March 8, 2021 12:05
-
-
Save mikegoatly/ae57f45f9c9325c7e477c139d84110cf to your computer and use it in GitHub Desktop.
A simple struct that automatically replaces unsupported characters from an Azure Table partition or row key value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// A helper class that removes any characters that are unsupported in an Azure Table partition or row key value. | |
/// </summary> | |
/// <example> | |
/// this.PartitionKey = new SafeTableKey("Somestring with unsupported characters"); | |
/// this.RowKey = new SafeTableKey("...."); | |
/// </example> | |
public struct SafeTableKey : IEquatable<SafeTableKey> | |
{ | |
private static readonly ISet<char> reservedCharacters = new HashSet<char> { '\\', '/', '#', '?', '%' }; | |
public SafeTableKey(string key) | |
{ | |
var builder = new StringBuilder(key); | |
for (var i = 0; i < builder.Length; i++) | |
{ | |
if (reservedCharacters.Contains(builder[i])) | |
{ | |
builder[i] = '_'; | |
} | |
} | |
this.Key = builder.ToString(); | |
} | |
public string Key { get; } | |
public override bool Equals(object? obj) | |
{ | |
return obj is SafeTableKey key && | |
this.Equals(key); | |
} | |
public override int GetHashCode() | |
{ | |
return HashCode.Combine(this.Key); | |
} | |
public static implicit operator string(SafeTableKey key) | |
{ | |
return key.Key; | |
} | |
public bool Equals(SafeTableKey other) | |
{ | |
return this.Key == other.Key; | |
} | |
public static bool operator ==(SafeTableKey left, SafeTableKey right) | |
{ | |
return left.Equals(right); | |
} | |
public static bool operator !=(SafeTableKey left, SafeTableKey right) | |
{ | |
return !(left == right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment