Skip to content

Instantly share code, notes, and snippets.

@DevEnable
Created March 29, 2015 04:37
Show Gist options
  • Save DevEnable/a20f55ecceb28d08dc79 to your computer and use it in GitHub Desktop.
Save DevEnable/a20f55ecceb28d08dc79 to your computer and use it in GitHub Desktop.
private ConnectionMultiplexer _connection;
void Main()
{
_connection = ConnectionMultiplexer.Connect("localhost");
var data = GetSessionData(GetKeys());
data.Dump("Session State");
}
// Define other methods and classes here
private IEnumerable<RedisKey> GetKeys()
{
var server = _connection.GetServer(_connection.GetEndPoints().First());
return server.Keys(pattern: "*_Data");
}
private Dictionary<string, SessionInformation> GetSessionData(IEnumerable<RedisKey> keys)
{
var db = _connection.GetDatabase();
return keys.ToDictionary (k => k.ToString(), k => GetSessionState(db, k));
}
private class SessionInformation
{
public Dictionary<string, object> Session {get; set; }
public string Size {get;set;}
public long SizeBytes {get;set;}
}
private SessionInformation GetSessionState(IDatabase db, string sessionKey)
{
long size = 0;
var session = db.HashGetAll(sessionKey).ToDictionary (entry => entry.Name.ToString(), entry => {
byte[] raw = (byte[])entry.Value;
size += raw.LongLength;
return GetObjectFromBytes(raw);
});
return new SessionInformation { SizeBytes = size, Size = BytesToString(size), Session = session };
}
private static object GetObjectFromBytes(byte[] dataAsBytes)
{
object obj;
if (dataAsBytes == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(dataAsBytes, 0, (int)dataAsBytes.Length))
{
memoryStream.Seek((long)0, SeekOrigin.Begin);
object retObject = binaryFormatter.Deserialize(memoryStream);
obj = (retObject.GetType().Name != "RedisNull" ? retObject : null);
}
return obj;
}
private static string BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
if (byteCount == 0)
return "0" + suf[0];
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(byteCount) * num).ToString() + suf[place];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment