Tuesday, March 31, 2015

Parallelize and Cache Role IdentityReference Group Translate

If you are working with windows authentication you might want to pull role information about your users. If you do that be careful, but the Translate method of the IdentityReference is not particularly fast. Here is some code to help parallelize the gets and cache the results:

private static readonly ConcurrentDictionary<string, string>
  GroupToTranslationMap = new ConcurrentDictionary<string, string>();
 
private IEnumerable<string> LoadGroupToTranslation(
    IList<IdentityReference> groups)
{
  var results = new ConcurrentStack<string>();
 
  Parallel.ForEach(
    groups,
    group =>
    {
      var translationValue = GroupToTranslationMap.GetOrAdd(
        group.Value,
        s =>
        {
          try
          {
            return group.Translate(NtAccountType).Value;
          }
          catch (Exception)
          {
            // TODO Log Me
          }
 
          return string.Empty;
        });
 
      if (!string.IsNullOrWhiteSpace(translationValue))
      {
        results.Push(translationValue);
      }
    });
 
  return results;
}

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics