Saturday, February 27, 2010

Extracting SSP user profiles in a xml file

Have you ever wanted to get all user profiles in one listing, especially that in the SSP UI, profiles are displayed in a paginated list? If you happen to have thousands of users then expect to have hundred of pages. The SSP user profiles list is not very intuitive that's why I developed a console application to get all users in a single xml file that I can sort an filter as I wish. Here is the code :

Imports System.Text
Imports System.IO
Imports System
Imports Microsoft.SharePoint
Imports System.Xml
Imports System.Web
Imports Microsoft.Office.Server
Imports Microsoft.Office.Server.UserProfiles

Module SSPUserProfiles

    Sub Main()
    End Sub
    Private Sub EnumUserProfiles()
            Using Site As New SPSite("http://ServerName")
                Dim siteContext As ServerContext = ServerContext.GetContext(Site)
                Dim ProfileManager As New UserProfileManager(siteContext)
                ' Open a new XML file stream for writing
                Dim stream As IO.FileStream
                stream = File.OpenWrite("UserProfiles.xml")
                Dim writer As XmlTextWriter = New XmlTextWriter(stream, Encoding.UTF8)

                ' Causes child elements to be indented
                writer.Formatting = Formatting.Indented

                writer.WriteProcessingInstruction("xml", "version=""1.0"" encoding=""utf-8""")
                writer.WriteAttributeString("Count", ProfileManager.Count.ToString)
                For Each Userp As UserProfile In ProfileManager
                    writer.WriteAttributeString("AccountName", Userp("AccountName").Value.ToString())
                    writer.WriteAttributeString("PreferredName", Userp("PreferredName").Value.ToString())
                    If Userp("WorkEmail").Value IsNot Nothing Then
                        writer.WriteAttributeString("E-Mail", Userp("WorkEmail").Value.ToString())
                    End If
                    writer.WriteEndElement() 'UserProfile
                writer.WriteEndElement() 'UserProfiles
                ' Flush the writer and close the stream
            End Using
        Catch exp As Exception
        End Try
    End Sub
End Module

For a full list of user profiles properties, please read Anne Stenberg's Blog.

Hope this helps.