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 linkto 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 projectResolve dependencies > npm iBundle > gulp bundle --shipPackage > gulp package-solution --shipUpload package into SharePoint App catalog and deploy. You could find package under SharePoint folder.A…

PowerApps Delegation warning

Warning:Delegation warning. This part "Filter" of this formula might not work correctly on large datasets. The data source might not be able to process the formula and might return an incomplete data set. Your application might not return correct results or behave correctly if the data set is incomplete
"Working with large datasets requires using data sources and formulas that can be delegated" - PowerApps 










Solution!!!500 is the default number of records to pull, but you can change this number for an entire app. 

By altering the number of delegation queries (not recommended), you will be able to pull items up to 2000 (as of 2018). 
On the File tab, select App settings.Find Experimental features, change the Data row limit for non-delegable queries setting from 1 to 2000.










Data sources that will help with delegation:Common Data Service

Microsoft Ignite Community (FREE) Events #MSIgnite

If you around Microsoft Ignite 2018, don't miss below community (FREE) events. 

Microsoft Ignite Welcome Reception

When: Monday, 5:30p – 7:30pm

Where: Exhibit Hall

Details: Kick off Ignite the right way with Monday’s welcome reception where you can chat with Microsoft experts, see demos, see old friends and make new ones over food and drinks.

PowerShell Community Social

When: Monday, 7:00p – 7:30p

Where: Community Central (OCCC West Hall)

Details: Come have a drink and meet Jeffrey Snover and PowerShell MVPs like Jaap Brasser, Aleksandar Nikolic, and Aaron Nelson immediately following the welcome reception.

Data & AI Community Social

When: Tuesday, 9:00a – 10:00a

Where: Community Central (OCCC West Hall)

Details: Do you do that Voodoo? Well, you can at the Data & AI Community Social. Eric Boyd and Rohan Kumar, along with MVPs Cathrine Wilhelmsen and Melody Zacharias will be there with Voodoo donuts and nitrogen cold brew coffee.

Microsoft Teams Community Social

When: Tuesday, …