Monday, April 13, 2009

Creating K2 Environment Fields with Environment Library API

I know that you can use a deployment package to move environment settings to different servers, but I wanted to see if I can create them programmatically. The process of creating Environment Fields can be a time consuming and tedious task, especially if you have a large number of fields. Typically in a real-world project, a list of Fields are already defined in a functional document somewhere, so to have a utility which can create fields from a list in a text file for example could be a big time saver. At the time of this writing, documentation on how to do this kind of thing was rather scarce, hence this post ;-)

The trick is to get a new instance of an Environment Field since is doesn’t have a new() constructor, you have to get a new instance by using the CreateFieldInstance() method of the EnvironmentFieldType class.

Steps:

  1. Create a new EnvironmentSettingsManager Instance and Connect to the K2 Server using the ConnectToServer() method of the EnvironmentSettingsManager instance.
  2. Create a new EnvironmentTemplateCollection Instance and a new EnvironmentInstanceCollection Instance.
  3. Select the Environment Template to use (e.g. Default Template) and select the Environment to use (e.g. Development)
  4. Get a handle on the EnvironmentFieldType you want to use by calling the EnvironmentSettingsManager.EnvironmentFieldTypes.GetItemByFriendlyName("Miscellaneous Field")
  5. Get a new EnvironmentField instance by calling CreateFieldInstance() method of the EnvironmentFieldType instance.
  6. Set the properties of the EnvironmentField instance
  7. Add the Field to the EnvironmentFieldCollection of the Environment Instance with the Add(newField) method of the EnvironmentFieldCollection
  8. Call the SaveUpdate() method of the EnvironmentField

Code:

EnvironmentInstance ei = new EnvironmentInstance();
ei = eic.GetItemByName("Development");
esm.ChangeEnvironment(ei.EnvironmentId);
EnvironmentFieldType eft = esm.EnvironmentFieldTypes.GetItemByFriendlyName("Miscellaneous Field");
EnvironmentField ef = (EnvironmentField)eft.CreateFieldInstance();
ef.FieldName = "DeonTestField";
ef.FieldDescription = "Deon Test Field";
ef.DisplayName = "DeonTestField";
ef.Value = "Some Value in Here";
efc = new EnvironmentFieldCollection(ei);
efc = ei.EnvironmentFields;
efc.Add(ef);
ef.SaveUpdate();

0 comments: