SharePoint: Remove duplicated fields from a Content Type
After in-place upgrading one of our SharePoint applications, we had been faced with the fact that some content types comprised duplicated fields. In other words, within the several <ContentType> sections of a list’s schema, we could find the pair <FieldRef> nodes with identical identifiers and names. Schematically, it looked like the following:
<?xml version="1.0" encoding="utf-8"?> <List Name="SomeList" Title="Some List" BaseType="0" Url="Lists/SomeList" Type="100" Id="a5bba3b3-5b1d-4186-ada7-bbd82b17f76d" ...> <MetaData> <Views> ... </Views> <Fields> ... </Fields> <ContentTypes> ... <ContentType ID="0x0100078C8A39971A4532AB9C5EB6DCB388A3" Name="SomeContentType" ...> <FieldRefs> ... <FieldRef Name="SomeField" ID="{b986cd1a-8bd0-4072-93af-5c48571bbf56}" /> ... <FieldRef Name="SomeField2" ID="{6d245d53-63ef-4650-b676-6e4ee66dcda5}" /> ... <FieldRef Name="SomeField2" ID="{6d245d53-63ef-4650-b676-6e4ee66dcda5}" /> ... <FieldRef Name="SomeField" ID="{b986cd1a-8bd0-4072-93af-5c48571bbf56}" /> ... </FieldRefs> ... </ContentTypes> <Forms> ... </Forms> </MetaData> </List>
The reason of such duplication still isn’t clear for me, but I’ve figured out how to get rid of it 🙂 Below is a simple method for deleting the excess fields from a passed content type:
protected static void RemoveDuplicatedFields(SPContentType spContentType) { bool duplicationFound = false; // identify how many times every field encounter Dictionary<Guid, int> tmpDir = new Dictionary<Guid, int>(); foreach (SPFieldLink spFieldLink in spContentType.FieldLinks) if (!tmpDir.ContainsKey(spFieldLink.Id)) tmpDir.Add(spFieldLink.Id, 1); else { tmpDir[spFieldLink.Id]++; duplicationFound = true; } if (duplicationFound) // remove all excess mentions of fields foreach (KeyValuePair<Guid, int> keyValuePair in tmpDir) { int removeIterationCount = keyValuePair.Value - 1; for (int i = 0; i < removeIterationCount; i++) spContentType.FieldLinks.Delete(keyValuePair.Key); } }