I had a list of JSON objects stored as individual blobs in Azure blob storage. I needed to get them out of blob storage sorted by last modified time and then reconstitute them as an array of JSON objects. Hit a few curiosities in writing this code, which someone else may benefit from. Without further ado, here’s the code:

            CloudBlobDirectory dir = eventContainer.GetDirectoryReference("http://---";);  
            SortedDictionary<DateTime, string> dictionary = new SortedDictionary<DateTime, string>();
            foreach (CloudBlob blob in dir.ListBlobs())
            {
                if (blob.Name == string.Format("{0}/$$$.$$$", "live")) continue;
                dictionary.Add(blob.Properties.LastModifiedUtc, blob.DownloadText());
            }
            StringBuilder json = new StringBuilder();
            json.Append("Callback([");
            foreach (string s in dictionary.Values)
            {
                json.Append(s);
                json.Append(",");
            }
            json.Remove(json.Length - 1, 1);
            json.Append("])");
            CloudBlob liveJson = dir.GetBlobReference("live.json");
            liveJson.Properties.CacheControl = cacheControl;
            liveJson.UploadText(json.ToString());

Okay, so what is going on here?

I start out with a nifty SortedDictionary, which will sort my items by the key of the dictionary as I add them.

I then call ListBlobs(). There’s this peculiar oddity with Blob Storage when you use CloudXplorer where this ghost file name $$$.$$$ gets created, which is why I have to check the name of the file. I then throw the string and the date into the dictionary.

Once that finishes, I iterate the dictionary, adding the callback and syntax for making a json array. Get rid of the final comma and then throw the whole deal back into blob storage. Hoorah!

At first, I was actually deserializing the strings into objects using JSON.Net and then I realized there was no reason to do that when all I needed to do was manipulate strings.