IP pull user profile information

_IPLogo

InfoPath offers the username() function in formulas to bring the current logged on username into the form. However, if you need more information from the user profile you need to tap into the users SharePoint profile.

To pull user profile information like username, telephone, email-address etc. of the current logged on user into an InfoPath form these lines of code can be used:

       private void LoadWorksheetsPreparerData()
        {
            XPathNavigator myRoot = MainDataSource.CreateNavigator();

            using (SPWeb outer_oWeb = SPContext.Current.Site.RootWeb)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(outer_oWeb.Site.ID))
                    {
                        ServerContext serverContext = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(serverContext);
                        UserProfile profile = profileManager.GetUserProfile(Application.User.LoginName);

                        myRoot.SelectSingleNode("/my:form/my:currentuser/my:User", NamespaceManager).SetValue(GetUserAttribute("PreferredName", profile));
                        myRoot.SelectSingleNode("/my:form/my:currentuser/my:Email", NamespaceManager).SetValue(GetUserAttribute("WorkEmail", profile));
                        myRoot.SelectSingleNode("/my:form/my:currentuser/my:Phone", NamespaceManager).SetValue(GetUserAttribute("WorkPhone", profile));
                    }
                });
            }
        }

        private string GetUserAttribute(string key, UserProfile userProfile)
        {
            try
            {
                UserProfileValueCollection values = userProfile[key];

                // if there is exactly one string value
                if ((values != null) && (values.Count == 1) && (values.Value is string))
                {
                    return values.Value.ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (PropertyNotDefinedException)
            {
                return string.Empty;
            }
        }

Is this Pages usefull? Usefull Useless 0 of 0 people say this Pages is usefull.