2

I want to cache the active directory data i.e Email,firstname and last name two times a day. This should happen behind the scenes maybe in global.aspx application.start(). And now whenevr I want to fetch 1700 (my application allows a functionlaity of browse users) users I would do that from cached data. My code is in Asp.net C#.

Can someone let me know the way to do it.

1 Answer 1

6

My code runs the first time it is accessed (you could make this application start by putting a couple of lines in your global.asax file). It stores the cached data in the ASP.Net cache for 12 hours. After the 12 hours are up the cache will be refreshed the next time the data is accessed.

public class UserInfo
{
    public static List<UserInfo> UserInfoCache { 
        get{
            if(HttpContext.Current.Cache["CachedUserList"] == null) {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

                PrincipalSearcher ps = new PrincipalSearcher(new UserPrincipal(ctx) { SamAccountName = "*" });

                var users = ps.FindAll();

                var result = from c in users
                             let u = (UserPrincipal)c
                             select new UserInfo() { Email = u.EmailAddress, FirstName = u.GivenName, LastName = u.Surname };

                HttpContext.Current.Cache.Insert("CachedUserList", result, null, DateTime.Now.AddHours(12), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return (List<UserInfo>)HttpContext.Current.Cache["CachedUserList"];
        }
    }

    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
1
  • I did that but at Cache.Insert it is showing me error:Value cannot be null. Parameter name: value
    – sweta shah
    Jul 6, 2011 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.