Partager via


Get the User Profile through MOSS Web Services

It is now easier than ever to pre-populate your InfoPath 2007 forms with the user profile information of the current user.

Background:

In Microsoft SharePoint Server 2003, the UserProfileService.GetUserProfileByName(string accountName) web service method required the caller to pass the account name (e.g., domain\alias) associated with the user profile to retrieve.  Though required, this argument was not needed when retrieving the profile of the current user.  After all, the form was running with the network credentials of the current user and those credentials were passed to the web service.

The typical work-around was to deploy a custom WhoAmI web service as a façade for the UserProfileService.  This façade would provide a method (e.g., WhoAmI() ) that would detect the user's identity and effectively forward a call to the UserProfileService, returning the eventual result to the caller.

New for Microsoft Office SharePoint Server 2007 and InfoPath 2007:

In InfoPath 2007, you can get the logon name of the current user by just using a new built-in function; but what if you need to get more data than just the username? Manager name, phone number, office location, and other data are all accessible through the UserProfileService: read on.

A form that uses the UserProfileService of MOSS to retrieve the User Profile of the current user no longer needs to explicitly pass the account information of the current user to the GetUserProfile method of the UserProfileService.  Simply passing a null value to this method will cause the web service to grab the user identity from the request.  The web service will then use that information as the account name and will subsequently return the User Profile of the current user.

Use this technique when you want to pre-populate the fields of an InfoPath 2007 form with user information obtained from the MOSS 2007 User Profile Database. 

The following instructions detail how to build a form to demonstrate this capability.

Assumptions:

  • The default MOSS web application is configured to use Windows Authentication.
  • The MOSS server has an SSP with a User Profile Database that has been loaded from Active Directory
  • The end-user has a profile in the User Profile Database of the MOSS server
  • The end-user is logged into the client machine using his/her domain account.

 

Step 1: Create the form

  1. Open InfoPath and design a new, blank form
  2. Save the form as UserProfileDemo.xsn

Step 2: Design the form

  1. From the Layout Task Pane, add a 2 column x 4 row table to the form
  2. Place labels into the column 1 as follows: Name, Account, Email, and Phone
  3. Using the Controls Task Pane, drag four text box controls to your form, placing one in each row of column 2
  4. Using the Data Source Task Pane, rename the four "fieldX" data elements as follows: userName, userAccount, userEmail, and userPhone

 

Step 3: Set the security level of the form

  1. From the Main Toolbar, select Tools | Form Options
  2. Select Security and Trust from the list box
  3. Clear the checkbox next to Automatically determine security level
  4. Select Full Trust
  5. Hit OK.

Step 4: Add code to the form

  1. From the Main Toolbar, select Tools | Programming | Loading Event
  2. Right-click on UserProfileDemo node of the Project Explorer and choose Add Web Reference
  3. Enter the following for the URL: /_vti_bin/UserProfileService.asmx">http://<yourServerName>/_vti_bin/UserProfileService.asmx
  4. Enter the following for Web reference name: ProfileService
  5. Click Add Reference
  6. Replace the FormEvents_Loading event handler with the following code snippet:
 public void FormEvents_Loading(object sender, LoadingEventArgs e) {
    XPathNavigator myRoot = MainDataSource.CreateNavigator();
    ProfileService.UserProfileService profileService = new ProfileService.UserProfileService();
    ProfileService.UseDefaultCredentials = true;
    ProfileService.PropertyData[] userProps = null;
    try {
        // Passing null to this method causes the profile of the current user to be returned.
        userProps = profileService.GetUserProfileByName(null);
    }
    catch { }
    if (userProps == null || userProps.Length == 0) {
        return;
    }
    for (int i = 0; i < userProps.Length; i++) {
        XPathNavigator node = null;
        switch (userProps[i].Name.ToLower())  {
            // these property names can be obtained by reviewing the user profile properties in the MOSS SSP.
            case "preferredname":
                node = myRoot.SelectSingleNode("/my:myFields/my:userName", NamespaceManager);
                break;
            case "accountname":
                node = myRoot.SelectSingleNode("/my:myFields/my:userAccount", NamespaceManager);
                break;
            case "workemail":
                node = myRoot.SelectSingleNode("/my:myFields/my:userEmail", NamespaceManager);
                break;
            case "workphone":
                node = myRoot.SelectSingleNode("/my:myFields/my:userPhone", NamespaceManager);
                break;
            default:
                continue;
        }
        ProfileService.ValueData[] values = userProps[i].Values;
        if (values.Length > 0) {
            if (node != null && string.IsNullOrEmpty(node.Value)) {
                node.SetValue(values[0].Value.ToString());
            }
        }
    }
}

 

Step 5: Build and Preview

  1. Build the project and close VSTA.
  2. From the Main Toolbar, select File | Preview| Form
  3. When the form loads, the text boxes will be populated with your User Profile Information

This example opens the door to simplifying the form submission process for your users by reducing the time they take to complete forms, as well as ensuring the accuracy of the data that they enter.

Ronald Tielke

Microsoft Consulting Services

Desert Mountain District

Comments

  • Anonymous
    March 07, 2007
    עלתה השאלה איך לטעון לתוך הטופס את פרטי המשתמש office user group במפגש האחרון של ה VSTO דרך שירותי ws

  • Anonymous
    April 04, 2007
    I've just read Meron Fridman's post from about a month ago about getting current user details into InfoPath

  • Anonymous
    May 08, 2007
    Great article!   Let's take it one step further and make it a no-code solution!  How?  Throw out steps 3 and 4.  Instead:

  1.  Create a new data connection to retrieve information from the specified web service (http://<yourServerName>/_vti_bin/UserProfileService.asmx?WSDL), and select the "GetUserProfileByName" web method.
  2.  Use an XPath query on your secondary data source to populate the fields you want.  For instance, use a formula to set the default value for an "email address" field.  You'll be selecting the "dataFields/.../Value" field.  The trick is to ensure you select the correct PropertyData node, as it is a repeating field - you'll have to edit the XPath to do so.  Assuming your secondary data source is called "GetUserProfileByName", the XPath query required to get the current user's email address looks as follows: xdXDocument:GetDOM("GetUserProfileByName")/dfs:myFields/dfs:dataFields/s0:GetUserProfileByNameResponse/s0:GetUserProfileByNameResult/s0:PropertyData[s0:Name = "WorkEmail"]/s0:Values/s0:ValueData/s0:Value Works beautifully, and without needing to bust out any code!
  • Anonymous
    May 09, 2007
    Update:  Note that the track-back above my post by Itay goes over the secondary data source option in more detail, with screenshots and all.  Nice work Itay!

  • Anonymous
    May 22, 2007
    You are in-fact my Hero.    I just got through writing this complicated webservice to return information from a the users context and deployed it to a document library and hadn't finished getting all that working when I realized that there really should be an easier way. Thank you so much, you made my day!

  • Anonymous
    June 17, 2007
    Uno de los retos que se nos ha planteado en el CIIN es como visualizar el directorio de empleados de

  • Anonymous
    June 20, 2007
    Hi, This is a nice post.  I am an InfoPath newbie and I've been looking for something list this.  I tested your code... it works good.  However, it won't work if I use it thru the SharePoint portal.  I think this has to do with the security/trust option. Basically, what I want to do is perform the same thing but under a web browser (SharePoint portal) environment.  If a user login to portal on a "share" PC, it would be wrong to pickup the PC's login credential.  So, what do your recommend? Thanks in advance. Ultra

  • Anonymous
    June 20, 2007
    Planier... I tested your "no code" approach.  What's strange is that it works if I create a brand now form but it won't work if I do this on an existing form. This is what I enter... "xdXDocument:GetDOM("GetUserProfileByName")/dfs:myFields/dfs:dataFields/s0:GetUserProfileByNameResponse/s0:GetUserProfileByNameResult/s0:PropertyData[s0:Name = "WorkEmail"]/s0:Values/s0:ValueData/s0:Value" and I get this error... ''"xdXDocument:GetDOM("GetUserProfileByName")/dfs:myFields/dfs:dataFields/s0:GetUserProfileByNameResponse/s0:GetUserProfileByNameResult/s0:PropertyData/s0:Values/s0:ValueData/s0:Value" does not point to a valid location path of a field or group." Any idea? Thanks

  • Anonymous
    June 20, 2007
    I had to modify the GetUserProfileByName data source to initialize the default value with a space.  

  • Anonymous
    June 22, 2007
    Got this working perfectly with the codeless method. What I'm wondering is where can I get information about this XPath information. (e.g. how do you come up with the XPath string "xdXDocument:GetDOM("GetUserProfileByName")/dfs:myFields/dfs:dataFields/s0:GetUserProfileByNameResponse/s0:GetUserProfileByNameResult/s0:PropertyData[s0:Name = "WorkEmail"]/s0:Values/s0:ValueData/s0:Value"? Is there a book or a reference that could get me going on understanding how to access this kind of information? Thanks, Gyan.

  • Anonymous
    August 31, 2007
    Hello I have refrence to Microsoft.Office.InfoPath and can see the xmlForm class in code but i receive error at "MainDataSource" error is "The name MainDataSource does not exist in the current context " if i use "this." there is no MaindataSource, the same kinf of problem exists with "NamespaceManager". I am dealing with these refrence errors from a long time, please help me how to fix above error. Thanks Needo

  • Anonymous
    October 07, 2007
    Hi, What if the WSS was configured for Forms Authentication, how can we get the current user's identity or profile in say infopath form to populate some data specific to user's role etc in actions pane. Kind Regards Satish.

  • Anonymous
    January 27, 2008
    i was trying to make a form with a field that contain Employee name i found the best way to do so is

  • Anonymous
    January 29, 2008
    In Step 4, when I select Tools | Programming | Loading Event, I see UserProfileDemo open in VSTA, and I find FormEvents_Loading in a FormCode.vb file.  This looks like Visual Basic to me, but the code snippet looks like C.   Obviously I'm not much of a programmer, so don't know how to proceed.  Any help appreciated -- thank you.  

  • Anonymous
    March 26, 2008
    Hi All, I'd like to populate a list of users into infopath form based on a selected profile property. Could anyone give some idea on how to go through. Thanks in advance!

  • Anonymous
    May 26, 2008
    Hello All: I got this error after previewing the IP form: "The query cannot be run for the following DataObject: GetUserProfileByName InfoPath cannot run the specified query. The SOAP response indicates that an error occurred on the server: The User Profile Manager object could not be loaded. ---> Value cannot be null. Parameter name: serverContext"

  • Note : I have my form "full trust" Thanks in advance

  • Anonymous
    July 14, 2008
    www.ceapet.com InfoPath-Getthecurrentuserwithoutwritingcode I'vejust

  • Anonymous
    July 31, 2008
    Hace un tiempo os comentaba como podemos leer User Profiles de MOSS . Como sabéis, cuando hablamos de

  • Anonymous
    July 31, 2008
    Hi, This is my 2nd post on this subject. This post will get down and dirty with code samples. The first

  • Anonymous
    November 20, 2008
    Hi everyone. I know you are going to hate me for this one, but here we go: I designed a form in 2003 and though publishing it in WSS 2.0 I am using this service from MOSS (GetUserProfile). Though me and a colleague do not have a problem when opening and submiting a form, several colleagues have either: "The following DataObject either cannot be created or cannot be initialized: GetUserProfileByName The query cannot be run for the following DataObject: GetUserProfileByName InfoPath cannot run the specified query. Access is denied." or "The following DataObject either cannot be created or cannot be initialized: GetCommonManager The query cannot be run for the following DataObject: GetCommonManager InfoPath cannot run the specified query. The SOAP response indicates that an error occurred on the server: Server was unable to process request. ---> Object reference not set to an instance of an object." I already removed the one of the services and still I have the same problem. I know it is asking a bit too much, but if you guys can through me a light, I'll appreciate it. Best, Gonçalo Sardinha

  • Anonymous
    April 27, 2009
    Sin duda, una de las ventajas de realizar formaci&oacute;n tecnol&oacute;gica especializada es que aprenden

  • Anonymous
    May 22, 2009
    Is there a "no coding" method of getting the user profile for someone other than the current user? I want to provide a field where the user could type in someone's account name and other fields in the form are filled in.

  • Anonymous
    May 22, 2009
    The comment has been removed

  • Anonymous
    June 08, 2009
    hi, if  i want to find out a user  or users  with matching a specific criteria, using this userprofileweb service, how can i  find it ?  like if i want to find out the users whose  names are starting with tim*  (like  timothy, tim john, tim hanss etc etc) is there  any kind of filtering kind of methods available or  is possible through this web service?

  • Anonymous
    June 17, 2009
    The Add Reference button is disabled when i try to Add Web Reference: http://myserver/_vti_bin/UserProfileService.asmx. Can someone tell me why? Since the sharepoint server setup by someone else who is no longer with the company, how do i verify if the the following assumptions  are correct?

  1. The default MOSS web application is configured to use Windows Authentication.
  2. The MOSS server has an SSP with a User Profile Database that has been loaded from Active Directory
  3. The end-user has a profile in the User Profile Database of the MOSS server
  • Anonymous
    June 21, 2009
    For lvirden and infopath, I have created an entire write-up that shows how to use the codeless method shown by Itay to get user information for people other than the current user: InfoPath – Get user information without writing code (extended): http://claytoncobb.wordpress.com/2009/06/21/userprofileservice-extended/.

  • Anonymous
    February 04, 2010
    Hi Great blog! Both the code and codeless version work graet, but what do I need to do to get the users COMPANY information? It doesnt seem to work in either version. Regards, Marko

  • Anonymous
    August 27, 2010
    For some reason the code on this page is cut off halfway through.  I've tried on two different PC's to get it.  Running windows 7.  It stops at continue;  and there is no more.....can someone post the code in the comments?

  • Anonymous
    August 27, 2010
    The code snippet should be visible now. Thanks.

  • Anonymous
    April 25, 2011
    while building the project i get the following error: the type or namespace name 'UseDefaultCredentials' does not exist in the namespace 'UserProfileDemo.ProfileService' please guide me!

  • Anonymous
    May 02, 2011
    also i pass null to GetUserProfileByName(null), I get error: Error 2 Cannot implicitly convert type 'Form.ProfileService.PropertyData[]' to 'Form.ProfileService.ProfileService.PropertyData[]' P:FormCode.cs 95 27 Form

  • Anonymous
    January 12, 2012
    FYI, for custom list forms in InfoPath 2010, the User Profile Service approach only works if anonymous access is disabled.   If you're allowing anonymous access, you will get an error message when the form loads saying InfoPath couldn't connect to a web service.

  • Anonymous
    June 19, 2012
    Pleaseeeeeeeeeeee help, I am having issue with calling web service from Infopath 2010 form (blank filer template). Error 2 Task failed because "sgen.exe" was not found, or the .NET Framework SDK v2.0 is not installed.  The task is looking for "sgen.exe" in the "bin" subdirectory beneath the location specified in the SDKInstallRootv2.0 value of the registry key HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFramework.  You may be able to solve the problem by doing one of the following:  1.) Install the .NET Framework SDK v2.0.  2.) Manually set the above registry key to the correct location.  3.) Pass the correct location into the "ToolPath" parameter of the task. Manualy I could run sgen.exe command and serialize dll, but from Infopath I am getting this error, whater I am running code from client or server. Do you have idea? Many thanks in advance

  • Anonymous
    June 19, 2012
    Hi Goran, To be honest, I am a bit confused: the only time I have seen this error is if you have added .NET code to your InfoPath form template. I have never seen this with a "blank" template. Did you just open the code editor and close it even? If so, this will add a code project to the XSN. At any rate, you can resolve this by installed the .NET 2.0 SDK which you can download from here: www.microsoft.com/.../details.aspx Now based on your comments, it does sound like you have code so I don't believe this is related to the UserProfileService. To confirm, create a new blank template and be sure to NOT add a code project. Add the data connection and just run it - it should work without issue. Scott

  • Anonymous
    December 12, 2012
    I am new to Infopath i have created one form and published on SharePoint, now i want when somebody opend the form it username & email address of the logged on user populates into the form automatically.

  • Anonymous
    March 05, 2013
    Esta muy bien el código y funciona bien en vista previa del infopath pero cuando lo subo al servidor, ya no funciona no muestra nada al parecer no hace nada y la verdad ya no se que hacer llevo dos dias intentando resolver error me podrian ayudar gracias

  • Anonymous
    April 02, 2014
    I know this kind requests, are not the most common, however, I have not developed in any language since long time , and in addition to this, my infopath has only installed the VB language. Would someone kindly post the same piece of code but VB