Thursday, 25 August 2011

Getting User Profile information

/ get the BadgeNumber for this user from the profile store
string _badgeNumber = string.Empty;
SPSite _SPSite = null;
try
{
    // TODO: move this to a configuration setting somewhere
    // get a reference to the current site
    _SPSite = new SPSite("http://siteurl/");
    // get a reference to the context of the current site
    ServerContext _ServerContext = ServerContext.GetContext(_SPSite);
    // get a UserProfileManager
    UserProfileManager _UserProfileManager = new UserProfileManager(_ServerContext);
    // get the UserProfile of the logged on user
    UserProfile _CurrentUserUserProfile = _UserProfileManager.GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name);
    _badgeNumber = (string)_CurrentUserUserProfile["badgeNumber "].Value;  // NOT ["Badge Number"], that was my initial mistake, using display name instead of name :)
}
finally
{
    _SPSite.RootWeb.Dispose();
    _SPSite.Dispose();
}

(or)

 object user = null;
            _SPSite = new SPSite("http://vodafonedev:24/");
            string siteURL = SPContext.Current.Site.Url;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteURL))
                {
                    ServerContext serverContext = ServerContext.GetContext(_SPSite);
                    UserProfileManager profileManager = new UserProfileManager(serverContext);
                   // SPUser spUser = site.RootWeb.Users.GetByID(id);
                    UserProfile profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);
                  
                    user = new
                    {
                        Account = profile["AccountName"].Value,
                        Title = profile["Title"].Value,
                        First = profile["FirstName"].Value,
                        Last = profile["LastName"].Value,
                        PreferredName = profile["PreferredName"].Value,
                        WorkPhone = profile["WorkPhone"].Value,
                        Fax = profile["Fax"].Value,
                        WorkEmail = profile["WorkEmail"].Value,
                        Office = profile["Office"].Value,
                        Manager = profile["Manager"].Value
                    };
                }
            });




No comments:

Post a Comment