Encoding and decoding a string that may have slashes in it

I have lines like this:

RowKey = "Local (Automatic/Manual) Tests", 

When I try to save on Windows Azure, this does not work, as I assume that it does not accept "/" as part of the string key.

Is there an easy way that I can encode a value before putting it in a RowKey?

Also, as soon as the data is in the table, I get the following:

 var Stores = storeTable.GetAll(u => u.PartitionKey == "ABC"); 

Is there an easy way by which I can get the RowKey value and decode it?

+2
source share
3 answers

One possible way to handle this is to convert the PartitionKey and RowKey values ​​to a Base64 encoded string and save them. Later, when you extract the values, you simply decode them. Actually, I had this problem a few days ago in our tool, and I was offered Base64 encoding on the MSDN forums: http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/a20cd3ce-20cb -4273-a1f2-b92a354bd868 . But again, this is not flawless proof.

+2
source

I am not familiar with Azure, so I do not know if an existing API exists for this. But it is not difficult:

encode:

 const string escapeChar='|'; RowKey.Replace(escapeChar,escapeChar+escapeChar).Replace("/",escapeChar+"S"); 

decrypts:

 StringBuilder sb=new StringBuilder(s.Length); bool escape=false; foreach(char c in s) { if(escape) { if(c=='S') sb.Append('/'); else if(c==escapeChar) sb.Append(escapeChar); else throw new ArgumentException("Invalid escape sequence "+escapeChar+c); } else if(c!=escapeChar) { sb.Append(c); escape=false; } else escape=true; return sb.ToString(); 
+1
source

When a string is encoded with Base64, the only character that is not allowed in the Azure storage key column is a slash ('/'). To fix this, simply replace the slash character with another character that is (1) valid in the Azure Table storage key column, and (2) is not a Base64 character. The most common example I found (which is given in other answers) is to replace a slash ('/') with an underscore ('_').

 private static String EncodeToKey(String originalKey) { var keyBytes = System.Text.Encoding.UTF8.GetBytes(originalKey); var base64 = System.Convert.ToBase64String(keyBytes); return base64.Replace('/','_'); } 

When decoding, simply cancel the replaced character (first!), And then Base64 decode the resulting string. That is all that is needed.

 private static String DecodeFromKey(String encodedKey) { var base64 = encodedKey.Replace('_', '/'); byte[] bytes = System.Convert.FromBase64String(base64); return System.Text.Encoding.UTF8.GetString(bytes); } 

Some people have suggested that other Base64 characters also require encoding. According to the Azure Table Storage docs , this is not the case.

0
source

All Articles