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 ...
No comments:
Post a Comment