How To

Creating VCard File

This is an example of how you might go about creating a VCard file from a Data source in Data Sync. In this example we are going to use the Empty Data source with Project Automation Item events.

In Project Automation we need to Open a Text File, Write each VCard entry and then Close the File.

Add a using for the System.IO namespace as we need to work with files.

using System.IO;

Create a class variable for the .NET Framework StreamWriter class.

private StreamWriter sw;

In the BeforeSynchronisation method we need to open the file for writing and setup the StreamWriter instance.

We also need a Filename and since this example uses the Properties collection on the Empty Datasource were going to extract the filename from this collection by first creating a Dictionary and returning the Filename property value.

public override void BeforeSynchronisation(ProjectAutomationCompareResult compareResult)
{
    var pDict = DataSourceB.Properties.ToDictionary(k => k.Name);
		
    sw = new StreamWriter(pDict["Filename"].Value, false);            
}

Next we need to close the file when were all finished, so implement the file close in the End method.

public override void End(ProjectAutomationResult result)
{
    if(sw != null)
    {
        sw.Close();
        sw.Dispose();
    }
}

Now for the fun part for each row in the ADD change set we need to write out the VCard data. Here we use the BeforeAddItem Item Event to write each VCard Entry to the file.

public override void BeforeAddItem(object sender, DataCompareItemInvariant item, object identity)
{		
    sw.WriteLine("BEGIN:VCARD");
    sw.WriteLine("VERSION:3.0");
    sw.WriteLine("N:{0};{1};;;", GetValue(item, "LastName"), GetValue(item, "FirstName"));
    sw.WriteLine("FN:{0} {1}", GetValue(item, "FirstName"), GetValue(item, "LastName"));
    sw.WriteLine("EMAIL;type=INTERNET;type=WORK;type=pref:{0}", GetValue(item, "Email"));
    sw.WriteLine("TEL;type=WORK;type=pref:{0}", GetValue(item, "PhoneNumber"));
    sw.WriteLine("END:VCARD");				
}

We use a little helper method to get the column value from the DataCompareItemInvariant item object.

private string GetValue(DataCompareItemInvariant item, string name) 
{
    var value = item.SourceRow.Get(name);
    if(value != null)
    {
        return DataSchemaTypeConverter.ConvertTo<string>(value.BeforeColumnValue);	
    }
    return string.Empty;	
}

Download VCard Demo Project