Tuesday, March 20, 2012

How to Use "Add To All Content Types" When Creating List Columns with Code

The "Add To All Content Types" functionality can be achieved using the "AddFieldAsXml" method with the "AddToAllContentTypes" option, see below

   SPList currentList = currentWeb.Lists["DocLib"];
   SPField newField = currentList.Fields.CreateNewField(SPFieldType.Text.ToString(), "New Field2");
   currentList.Fields.AddFieldAsXml(newField.SchemaXml, true, SPAddFieldOptions.AddToAllContentTypes);
   currentList.Update();

I found this code and an excellent explanation on this blog http://blogs.microsoft.co.il/blogs/davidbi/archive/2009/01/22/sharepoint-add-a-spfield-to-all-the-content-types-in-a-splist.aspx

Tuesday, March 13, 2012

Fixing the Elements.xml file causing a deployment error

Here is the error that I got:
Error occurred in deployment step 'Activate Features': Operation is not valid due to the current state of the object
This occurs when you rename your namespace without also updating the "class" value in the Elements.xml file.

Here are the contents of the Elements.xml file:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="108">
    <Receiver>
      <Name>EmailReciever</Name>
      <Type>EmailReceived</Type>
      <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
      <Class>MyNameSpace.MyProject.MyClass</Class>
      <SequenceNumber>10000</SequenceNumber>
    </Receiver>
  </Receivers>
</Elements>


Here is the Feature's code:
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace MyNameSpace.MyProject
{

 public class MyClass : SPEmailEventReceiver
 {
  public override void EmailReceived(SPList list, SPEmailMessage emailMessage, String receiverData)
  {
   base.EmailReceived(list, emailMessage, receiverData);
  }
 }
}


The error occurs when the "class" value is not exactly "Namespace" dot "ClassName"  I've highlighted the pieces above, that make up the "class" value.  Since 2-part namespaces are common I've used that as an example.