Add choices to SPFieldChoice programatically in a Sandboxed solution

The other day I stumbled upon a weird behavior when developing a sandboxed solution. I was trying to add choices programatically to an SPFieldChoice field using the object model. After hours trying to debug the problem, looking at the ULS logs etc. I learned that is actually a known bug. There is a workaround though, you can modify the xml schema of the field to modify/add your choices.


var category = (SPFieldChoice)rootWeb.Fields["Category"];
var choices = new[] { "category one", "category two"};

var doc = new XmlDocument();
doc.LoadXml(category.SchemaXml);
var fieldNode = doc.SelectSingleNode("/Field");
if (fieldNode != null)
{
    var choicesnode = doc.SelectSingleNode("/Field/CHOICES");
    if (choicesnode != null)
    {
        fieldNode.RemoveChild(choicesnode);
    }

    var choicesElement = doc.CreateElement("CHOICES");

    foreach (string choice in choices)
    {
       var choiceElement = doc.CreateElement("CHOICE");
       choiceElement.InnerText = choice;
       choicesElement.AppendChild(choiceElement);
    }

    fieldNode.AppendChild(choicesElement);
    category.SchemaXml = doc.OuterXml;
    category.Update(true);
 }

You have to love SharePoint

Disable “Task has been Changed” Notifications

In Sharepoint 2010 when you have notifications turned on users receive notifications by default when tasks are created and when tasks change.

Depending on your workflow requirements this can result in users being flooded with too many notifications. To disable the “Change” notification but keep the original assignment notification you can follow the instructions in this post.

If you want to script it so you can deploy it part of a solution package, or as a powershell script then you can also use Object Model:

SPList workflowtasks = web.Lists["Tasks"];
workflowtasks.EnableAssignToEmail = true;
workflowtasks.Update();

//Disable Changed notifications
var alert = web.Alerts.Cast<SPAlert>().FirstOrDefault(i => i.List.ID == workflowtasks.ID && i.EventType == SPEventType.All);
if (alert != null)
{
 alert.EventType = SPEventType.Add;
 alert.Update(false);
}