SharePoint Tip #21: Importing User Profiles

One of the best things of SharePoint's User Profiles, is that the profile data can be imported from several data sources (Active Directory or other LDAP directories, Databases and web services). It gets even better since you can schedule these imports to be performed automatically every given period of time.

But what if you want to start a profile import programmatically, without having to wait for the next scheduled import? Well, that can be done using the following code snippet.

// open a site collection
using (SPSite site = new SPSite("http://myportal"))
    // get the server context
    ServerContext context = ServerContext.GetContext(site);

    // create the profile configuration manager object
    UserProfileConfigManager upcm = new UserProfileConfigManager(context);

    // check if there is already an import in progress
    if (!upcm.IsImportInProgress())
        // if not, start a new one
        // pass "true" as a parameter, if the import is incremental
        // pass "false" as a parameter, if you want a full import

The profile import process is managed using the UserProfileConfigManager object, which can be created using a ServerContext object. Before starting an import, using the StartImport method, you should always check if there is already an import in progress (using the IsImportInProgress method).

The StartImport method accepts a single boolean parameter which specifies if you want an incremental import (true) or a full import (false).

If necessary, you can build a while cycle to wait for the import to be over, testing the IsImportInProgress return value, until it returns false.

Attention: User Profiles are a MOSS only feature. You cannot use them with WSS.