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()
        EnumUserProfiles()
    End Sub
    Private Sub EnumUserProfiles()
        Try
            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.WriteStartElement("UserProfiles")
                writer.WriteAttributeString("Count", ProfileManager.Count.ToString)
                For Each Userp As UserProfile In ProfileManager
                    
                    writer.WriteStartElement("UserProfile")
                    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
                Next
                writer.WriteEndElement() 'UserProfiles
                ' Flush the writer and close the stream
                writer.Flush()
                stream.Close()
            End Using
        Catch exp As Exception
            Console.WriteLine(exp.Message)
        End Try
    End Sub
End Module




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

Hope this helps.