static void ImportTemplate(List list, List<TaxonomyField> taxonomyFields)
{
// Load TermSet for each field
Dictionary<string, TermSetLookup> termSetsByInternalName
= GetTermSetsByInternalName(taxonomyFields);
// Load the Excel file
Dictionary<string, ExcelRow> excelRowsByUrl = GetExcelRowsByUrl(termSetsByInternalName);
// STEP 3: Update the list items
List<string> fieldNames = taxonomyFields.Select(f => f.InternalName).ToList();
fieldNames.Add("ServerUrl");
ProcessListItems(list, fieldNames,
delegate(ListItem listItem)
{
// Does the CSV file contain a row matching this list item?
ExcelRow excelRow;
if (!excelRowsByUrl.TryGetValue((string)listItem["ServerUrl"], out excelRow))
return; // no it does not
excelRow.Processed = true;
bool updated = false;
foreach (KeyValuePair<string, Guid> pair in excelRow.Pairs)
{
TaxonomyField taxonomyField = taxonomyFields.First(f => f.InternalName == pair.Key);
TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue();
// (to clear the tag, you would specify the empty GUID here)
taxonomyFieldValue.TermGuid = pair.Value.ToString();
TaxonomyFieldValue oldValue = (TaxonomyFieldValue)listItem.FieldValues[taxonomyField.InternalName];
if (oldValue == null || oldValue.TermGuid != taxonomyFieldValue.TermGuid)
{
taxonomyField.SetFieldValueByValue(listItem, taxonomyFieldValue);
updated = true;
}
}
if (updated)
{
Log("Updating item: " + listItem["ServerUrl"]);
listItem.Update();
}
Program.clientContext.ExecuteQuery();
}
);
// Were any items missed?
Log("");
List<ExcelRow> missedRows = excelRowsByUrl.Values.Where(row => !row.Processed).ToList();
if (missedRows.Count > 0)
{
Log("Failed to match these rows");
foreach (ExcelRow row in missedRows)
Log(" " + row.ListItemUrl);
}
}