/// <summary> /// Retrieve an unused ActiveKey for this Login. /// </summary> private static ActiveKey RetrieveUnusedKey(CSSDataContext db, Login login) { var random = new Random(); var earliest = DateTime.Now.AddHours(-ActiveKey.PreferredMinLifetime); var availableKeys = db.AvailableKey(login.Id) .Where(p => p.DateCreated > earliest && p.IsValid == true); var length = availableKeys.Count(); if (length == 0) { return(null); } //Find a key (at random) which this Login has not already used. var index = random.Next(0, length - 1); var keyresult = availableKeys.Skip(index).Take(1).FirstOrDefault(); return(db.ActiveKeys.FirstOrDefault(p => p.Id == keyresult.Id)); }