Pages

Showing posts with label User Profile Service Application. Show all posts
Showing posts with label User Profile Service Application. Show all posts

Monday, August 19, 2013

Console Application to store User Profile Data into a CSV file


This post is gonna help you create a simple console application which would query the User Profile Application of your SharePoint farm and store its user profile data into a CSV file.

Let us first create two public classes - one corresponding to a CSV row and the other corresponding to the Writer object -

Class 1 - extended from a List of type string
 
 public class CsvRow : List<string>
{
    public string LineText { get; set; }
}

Class 2 - extended from StreamWriter class. It also includes logic to handle special characters in data

public class CsvFileWriter : StreamWriter
{
    public CsvFileWriter(Stream stream): base(stream)
    {
    }

    public CsvFileWriter(string filename): base(filename)
    {
    }

    public void WriteRow(CsvRow row)
    {
        StringBuilder builder = new StringBuilder();
        bool firstColumn = true;
        foreach (string value in row)
        {
// Add separator if this isn't the first value
          if (!firstColumn)
              builder.Append(',');
// Implement special handling for values that contain comma or quote
// Enclose in quotes and double up any double quotes
          if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
              builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
          else
              builder.Append(value);
          firstColumn = false;
        }
        row.LineText = builder.ToString();
        WriteLine(row.LineText);
    }
}


Now the next step's the very basic, creating the Service Context object in the main function as follows -

SPServiceContext _servicecontext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, new SPSiteSubscriptionIdentifier(Guid.Empty));

UserProfileManager CurrentUserProfileManager = new UserProfileManager(_servicecontext);

UserProfileConfigManager CurrentUserProfileConfigManager = new UserProfileConfigManager(_servicecontext);


Now, we would create an object of the above custom CsvFileWriter class and include the rest of the code in it -

using (CsvFileWriter writer = new CsvFileWriter(@"E:\Results.csv"))
{
    var Profiles = CurrentUserProfileManager.GetEnumerator();
    CsvRow columnRow = new CsvRow();
    columnRow.Add("Property1");
    columnRow.Add("Property2");
    columnRow.Add("Property3");
    writer.WriteRow(columnRow);
    while (Profiles.MoveNext())
    {
         UserProfile profile = (UserProfile)Profiles.Current;
         CsvRow row = new CsvRow();
         row.Add(profile["<Property1_Name>"].Value.ToString());
         row.Add(profile["<Property2_Name>"].Value.ToString());
         row.Add(profile["<Property3_Name>"].Value.ToString());
         writer.WriteRow(row);
    }

}

Happy Coding ppl ...

Accessing SharePoint User Profiles using PowerShell commands


This post will help you access the user profiles stored within your User Profile Service Application. It is applicable to both SharePoint 2010 as well SharePoint 2013.

Load the SharePoint snap-in into your management shell -

$snapinName = "Microsoft.SharePoint.PowerShell"
if ((Get-PSSnapin | Where-Object {$_.Name -eq $snapinName }) -eq $NULL)
{
  write-host "SharePoint SnapIn not loaded. Loading..."
  Add-PSSnapin $snapinName -ErrorAction SilentlyContinue
}

Create the SPService Context used to initialize the Profile Manager instance -

$proxyGroup = Get-SPServiceApplicationProxyGroup -default
$subId = [Microsoft.SharePoint.SPSiteSubscriptionIdentifier]::Default
$context = [Microsoft.SharePoint.SPServiceContext]::GetContext($proxyGroup, $subId)

Initialize the ProfileManager object using the created Context object -

$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

Using this object, create an Enum type object to iterate / enumerate through all the user profiles -

$Profiles = $ProfileManager.GetEnumerator()

Now, there are two ways to loop through these profiles -

1. Using foreach loop

foreach($profile in $Profiles)
{
$property1 = $profile["<Property_Name>"].Value
$property2 = $profile["<Property_Name>"].Value
}

Above, <Property_Name> denotes the name of any user profile property you have created or is available out-of-the-box.

2. Using while loop

while($Profiles.MoveNext())
{
$profile = $Profiles.Current
                $property1 = $profile["<Property_Name>"].Value
$property2 = $profile["<Property_Name>"].Value
}


If you wish to save or export the profile data into a CSV file, you can modify your code above to something like below -

Using foreach loop approach -

Get the location of the file which should save your data -

$propertiesFileName = "\UPA-Profiles.csv"
$outputFile = (Get-Location -PSProvider FileSystem).ProviderPath + $propertiesFileName

Create a Collection which would every single row of your CSV file -

$collection = @()

Then, the loop -

foreach($profile in $Profiles)
{
$profileData = "" | select "Property1","Property2","Property3"
$profileData.Property1= $profile["<Property_Name>"].Value
$profileData.Property2= $profile["<Property_Name>"].Value
$profileData.Property3= $profile["<Property_Name>"].Value
$collection += $profileData
}
$collection | Export-Csv $outputFile -NoTypeInformation


Hope this helps ...