[C#] Token-Storage and Generate

07/08/2014 10:12 Ravenstorm#1
Tokens can be used to authenticate transactions or authorize people and even more...

Initialize your Token-Storage:
Code:
static Dictionary<string, DateTime> token_storage = new Dictionary<string, DateTime>();
Generate a Token:
Code:
byte[] actual_time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] unique_token = Guid.NewGuid().ToByteArray();
string full_token = Convert.ToBase64String(actual_time.Concat(unique_token).ToArray());
Add the Token to the Storage:
Code:
token_storage.Add(full_token,DateTime.Now);
If you have a lot of tokens in your storage you want to delete the expired ones... Check every 5 minutes if there are some expired tokens...

The timer:
Code:
timer = new Timer(1000*300);
timer.Elapsed += checkTokens;
static void timer_checkTokens(object sender, ElapsedEventArgs e)
{
    var expiredTokens = token_storage.Where(p => p.Value.AddDays(1) <= DateTime.Now).Select(p => p.Key);

    foreach (var key in expiredTokens) {
        token_storage.Remove(key);
    }
}
11/03/2014 00:41 Black Tiger ツ#2
Shouldn't you create a List<string> from your IEnumerable<string> to get access inside your foreach loop?

Code:
  foreach (var key in expiredTokens.ToList())
            {
                TokenStorage.Remove(key);
            }
11/08/2014 16:59 x]vIrus[x#3
what is this shit, you described how to use a dictionary, how does one even need a tutorial for a dictionary?!
11/08/2014 19:21 YatoDev#4
Quote:
Originally Posted by x]vIrus[x View Post
what is this shit, you described how to use a dictionary, how does one even need a tutorial for a dictionary?!
it's just a snippet! calm done