Recently, I was working on a project where we wanted to create SharePoint fields using the .NET client object model (CSOM). You can easily find examples on the internet on how to create a text field, but we had a lot of trouble to find out how to create a calculated field.
Calculated fields can be created in a number of flavors. The following code snippet generates a calculated field that will show employee data as follows:
Karine Bosch (id 82176)
string formula = "<Formula>=FirstName& \" \" &LastName& \" (id: \" &EmployeeID& \" \"</Formula>" + "<FieldRefs>" + "<FieldRef Name='FirstName' />" + "<FieldRef Name='LastName' />" + "<FieldRef Name='EmployeeID' />" + "</FieldRefs>"; string schemaCalculatedField = "<Field ID='<GUID>' Type='Calculated' Name='FullName' StaticName='FullName' DisplayName='Full Name' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>" + formula + "</Field>"; Field fullNameField = demoList.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddInternalNameHint); clientContext.ExecuteQuery();
You can read more on how to create other type of fields using CSOM here.
To learn how to provision a calculated field, I created this type of field in a blank site through the UI of SharePoint. Then I saved the site as template. This saves the site as a .wsp and stores it in the Solution gallery. From there you can download it and import it in Visual Studio.
Once the .wsp imported, you will notice that all fields, content types, list instances and other elements that make up your site are translated into CAML and features:
Click on the elements.xml in the Fields folder to see the definition of all fields.