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)
// 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("\"", "\"\""));
          firstColumn = false;
        row.LineText = builder.ToString();

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();
    while (Profiles.MoveNext())
         UserProfile profile = (UserProfile)Profiles.Current;
         CsvRow row = new CsvRow();


Happy Coding ppl ...

No comments:

Post a Comment