private static void TryApplyFieldValue()

in Mail2Bug/WorkItemManagement/TFSWorkItemManager.cs [476:520]


        private static void TryApplyFieldValue(WorkItem workItem, string key, string value)
        {
            try
            {
                // Take the default value from the workItem - use empty string if it's null
                var field = workItem.Fields[key];
                var defaultFieldValue = field.Value ?? "";

                if (value == null)
                {
                    Logger.ErrorFormat("Attempting to set the value of {0} to null", key);
                    return;
                }

                if ((field.FieldDefinition.FieldType == FieldType.Html) && (!value.StartsWith("<html")))
                {
                    value = value.Replace("\n", "<br>");
                }

                field.Value = value;

                // If this value is not valid, try to "guess" the value from the allowed values list
                if (!field.IsValid)
                {
                    Logger.WarnFormat("'{0}' is an invalid value for {1}. Trying to find approximate value.", value, key);

                    var approximateValue = GetApproximateAllowedValue(field, value);
                    Logger.InfoFormat("Approximate value is {0}", approximateValue);

                    field.Value = approximateValue;
                }

                // Couldn't approximate the value either - give up
                if (!field.IsValid)
                {
                    Logger.ErrorFormat("Attempt to set field value of {0}; reverting to default {1}", key, defaultFieldValue);

                    field.Value = defaultFieldValue;
                }
            }
            catch (FieldDefinitionNotExistException ex)
            {
                Logger.ErrorFormat("Exception caught while trying to set value of field '{0}'\n{1}", key, ex);
            }
        }