Wednesday, January 4, 2012

Setting BCS Secondary Fields Programmatically in SharePoint 2010

Phew, that was quite a battle. I have been writing some code to import values from a CSV file into some custom lists in SharePoint (I realise that there are, of course, plenty of other ways to import into SharePoint, such as using PowerShell or a third party app., but specific needs call for special handling), and one of the requirements is to import data into External Columns in the SharePoint list.

Original this process used the GetSecondaryFieldNames() method of the SPBusinessDataField instance to get the internal names of each of the secondary fields, and then combined each of those with the internal name of the SPBusinessDataField to create the displayname value for each secondary field. The list item fields could then be set using these displayname values.

This worked fine in the dev environment... but of course the real workd is different! Researching the failure of this process on the target machine showed that the display names for the secondary fields did not contain the values from the GetSecondaryFieldNames() call (PowerShell allowed me to easily view the Schema XML for the fields in the list, saving the need for a tool like SharePoint Manager).

So, my solution was to seek the secondary field by enumerating through all fields in the list, seeking the field whose:
  • "DisplayName" property value starts with the internal name of the related external data field
  • "BdcField" property value matches a string value returned by GetSecondaryFieldNames()
This lets me find the required secondary BCS field, and gived me the GUID for use in later populating that field with a value. I then make sure to cache this GUID, meaning on the next pass through this part of the code I can use the cached value rather than re-enumerating all the fields once again.

No comments: