Skip to main content

Get all user profile properties to csv

Notes:
Custom properties are not fetching with the CSOM
Properties marked with "Only Me" cant be fetched with CSOM
SSOM and PowerShell is the option when you fetching properties

using System;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using CSVHelper;
using System.Data;
using System.Configuration;
using log4net;

namespace UserProfileUtility
{
class Program
{
// Get url from App config
static string siteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString();
// User Properties handler
static UserProperties userProp = new UserProperties();
//Logging
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
/// Main method
/// </summary>
/// Arguments
static void Main(string[] args)
{

#region Definitions
DataTable dataTable = new DataTable();
bool first = true;
Object[] objArray;
#endregion
//logging configure
log4net.Config.XmlConfigurator.Configure();

SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
#region Fetching user profile prop
using (SPSite site = new SPSite(siteUrl))
{
SPServiceContext serviceContext = SPServiceContext.GetContext(site);
UserProfileManager upMananger = new UserProfileManager(serviceContext);

log.Info("Number of user profiles found :"+ upMananger.Count);
Console.WriteLine("Number of user profiles found : {0}", upMananger.Count);
Console.WriteLine("");
log.Info("Working on resolve user profile poperties . . . ");
Console.WriteLine("Working on resolve user profile poperties . . . ");
Console.WriteLine("");

//Looping user profiles
foreach (UserProfile profile in upMananger)
{
//keyList = new List();

Console.BackgroundColor = ConsoleColor.Yellow;
Console.WriteLine("Found: " + profile["AccountName"]);
Console.ResetColor();
Console.WriteLine(new string('_', 20));
var userAccName = profile["AccountName"].ToString();

//Getting user properties
var dictionary = userProp.GetUserProperties(userAccName);
//Adding headers
if (first)
{
foreach (var item in dictionary)
{
dataTable.Columns.Add(item.Key, typeof(string));
//keyList.Add(item.Key.ToString());
}
first = false;
}
//Adding values
if (dataTable.Columns.Count &gt; 0)
{
objArray = new object[dataTable.Columns.Count];
int i = 0;
foreach (var item in dictionary)
{
objArray[i] = item.Value;
++i;
}
dataTable.Rows.Add(objArray);
}
}
//Console.ReadKey();

}
#endregion Fetching user profile prop

#region Writing to CSV
//Writing to csv
log.Info("User profiles to CSV file in progress. . .");
Console.WriteLine("Writing user profiles to CSV file . . . ");
Console.WriteLine("");
WriteCSV(dataTable);

Console.ForegroundColor = ConsoleColor.Green;
log.Info("User profile import success .");
Console.WriteLine("User profile import success . . . !");
Console.ResetColor();
#endregion Writing to CSV

}
//Catch exceptions here, ex. NullReferenceException
catch (System.Exception ex)
{
log.Error("Error on retriving user profile", ex);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.ToString());
Console.ResetColor();
}

//getUserPropertiesCollection();


});

Console.ReadKey();

}

/// <summary>
/// Getting SharePoint User Profile Properties
/// </summary>
///
private static void getUserPropertiesCollection(string siteUrl)
{
using (SPSite site = new SPSite(siteUrl))
{
SPServiceContext context =
SPServiceContext.GetContext(site);
ProfileSubtypeManager psm = ProfileSubtypeManager.Get(context);
ProfileSubtype ps = psm.GetProfileSubtype(ProfileSubtypeManager.GetDefaultProfileName(ProfileType.User));
//Get the properties
ProfileSubtypePropertyManager pspm = ps.Properties;
foreach (ProfileSubtypeProperty profileSubtypeProperty in pspm.PropertiesWithSection)
{
Console.WriteLine(profileSubtypeProperty.Name);
}


}
}

/// <summary>
/// Write data table to Comma Seperated Value file
/// </summary>
/// Data Table
static void WriteCSV(DataTable dt)
{
//export CSV location
string exportCSVLocation = ConfigurationManager.AppSettings["ImportCSVLocation"].ToString();

try
{
log.Debug("Writing user profiles to CSV file. . .");
// Write sample data to CSV file
using (CsvFileWriter writer = new CsvFileWriter(exportCSVLocation))
{
CsvRow row = new CsvRow();

//Adding headers
foreach (DataColumn column in dt.Columns)
{
//Iterate Cells
row.Add(column.ToString());
}
// Writing headers
writer.WriteRow(row);

// Iterate rows
foreach (DataRow dr in dt.Rows)
{
//Iterate Cells
row = new CsvRow();
foreach (var item in dr.ItemArray)
{
if (item != null)
row.Add(item.ToString());
}
writer.WriteRow(row);
}
}
}
//Catch exceptions here, ex. NullReferenceException
catch (System.Exception ex)
{
log.Error("Error when writing to CSV file", ex);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.ToString());
Console.ResetColor();
}
}

/// <summary>
/// Reading CSV
/// </summary>
static void ReadCSV()
{
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader("ReadTest.csv"))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
foreach (string s in row)
{
Console.Write(s);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}


}

~~~~~~~~UserProperties.cs~~~~~~~~~~~~~~~~

class UserProperties
{
//Logging
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
/// Get User profiles prorpertise for the user accout name
/// </summary>
///
///
internal Dictionary GetUserProperties(string targetUser)
{
Dictionary dic = new Dictionary();
Microsoft.Office.Server.UserProfiles.UserProfile user;

try
{
log.Info("Resolving user properties for user : " + targetUser);

#region Getting user profile prop using SharePoint Server Object Model
string siteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite spSite = new SPSite(siteUrl);
var serviceContext = SPServiceContext.GetContext(spSite);
UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
ProfilePropertyManager profilePropMgr = new UserProfileConfigManager(serviceContext).ProfilePropertyManager;

// Retrieve all properties for the "UserProfile" profile subtype,
// and retrieve the property values for a specific user.
ProfileSubtypePropertyManager subtypePropMgr = profilePropMgr.GetProfileSubtypeProperties("UserProfile");
Microsoft.Office.Server.UserProfiles.UserProfile userProfile = userProfileMgr.GetUserProfile(targetUser);
IEnumerator userProfileSubtypeProperties = subtypePropMgr.GetEnumerator();
while (userProfileSubtypeProperties.MoveNext())
{
string propName = userProfileSubtypeProperties.Current.Name;
ProfileValueCollectionBase values = userProfile.GetProfileValueCollection(propName);
if (values.Count &gt; 0)
{
// Handle multivalue properties.
foreach (var value in values)
{
Console.WriteLine(string.Format("{0}: {1}", propName, value.ToString()));
log.Info("Resolved Property=&gt;" + propName + " Property value=&gt;" + values.ToString());
dic.Add(propName, value.ToString());
}
}
else
{
Console.WriteLine(propName + ": ");
log.Info("Retrieved Property name=&gt;" + propName + " Property value=&gt;");

dic.Add(propName, string.Empty);
}
}

});
#endregion

//Console.ReadKey(false);

}
catch (Exception ex)
{
log.Error("Error on retrieving user profile Properties", ex);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error on retriving profile properties");
Console.ResetColor();
}

return dic;
}


References
https://msdn.microsoft.com/en-us/library/office/jj163800.aspx
https://msdn.microsoft.com/en-us/library/office/jj163142.aspx#bkmk_GetChangeUP
http://sharepoint.stackexchange.com/questions/140192/how-to-set-update-user-profile-custom-property-value-programmatically

Comments

Popular posts from this blog

Turn off/ Hide Details panel/ Information Panel on modern SharePoint lists

Not always we require to show changes done by other which is a mandatory feature in SharePoint online.  What is details pane (aka. Information Pane)? Detail pane/ Information shows information regarding the document if you selected a one or its showing recent changes within a list or library. Follow link to Microsoft documentation about details pane. Bad news: Until Microsoft listen to User Voice , there is no straightforward way to enable disable this even you don't want. Good news: We could write a SharePoint framework extension to hack styles until Microsoft give us a permanent solution. How? I found this sample project (Inject CSS into modern SharePoint pages with React) which could reuse to our purpose. Thanks to Hugo for saving my time.  Steps to awesomeness:  Clone the project Resolve dependencies >  npm i Bundle >  gulp bundle --ship Package >  gulp package-solution --ship Upload package into SharePoint App catalog  

📢 Update -Top 10 Microsoft Teams questions from customers around the world

Over the last 4 months, we’ve traveled to 9 countries on Microsoft Ignite | The Tour meeting and speaking with users like you about Microsoft Teams. The insights and feedback at every location has been invaluable — Thank you. During our travels, there have been 10 questions that have repeatedly surfaced. Below are all of the questions — including the answers too, of course!   Can you restrict access to a specific channel in a team? What are best practices for governance, specifically around team creation, naming, and retention? Can I add guests to my team? If so, how? How does external access/federation work? How is this different to guest access? What functionalities do I get in a hybrid environment? Is Teams available for on-prem environments? How do I configure Direct Routing in Microsoft Teams? Why should I move from Skype for Business to Teams? How do I make this transition? I have existing SharePoint sites that I would like to bring into Teams. Can I do that? I need t

Eliminate Duplicates in Microsoft Flow and Azure Logic Apps

There is no straight forward method or Microsoft Flow action  to eliminate values in a collection like Microsft Excel (as of March 2019). This little hack will help you to eliminate/ remove duplicates and create a collection of unique values. Sample scenario: Need to send daily summarized notification to assigned approved with pending approval items. Sample workflow: Initialize an array Iterate collection of data and append items that are not there in the filtered array Side note: This won't be an option to consider if you too concerned about the performance of the workflow but for the time being its an option to consider.