Programmatically copying custom content type and columns from one web to another

Posted by BeraCim on Stack Overflow See other posts from Stack Overflow or by BeraCim
Published on 2010-05-10T05:24:33Z Indexed on 2010/05/10 5:28 UTC
Read the original article Hit count: 441

Hi all:

I'm experiencing a very stubborn problem when copying custom content type and its columns from one web to another within the same site. Basically, this is the code that I have:

foreach (SPField field in existingWeb.Fields)
{
    if (!destinationWeb.Fields.ContainsField(field.Title))
    {
        destinationWeb.Fields.AddFieldAsXml(field.SchemaXml);
        destinationWeb.Update();
    }
}

foreach (SPContentType existingWebCt in destinationWeb.ContentType)
{
    SPContentType newContentType = new SPContentType(existingWebCt.Parent, destinationWeb.ContentTypes, existingWebCt.Name);
    foreach (SPFieldLink fieldLink in existingWebCt.FieldLinks)
    {
        SPField sourceField = existingWebCt.Fields[fieldLink.Id];
        if (destinationWeb.Fields.ContainsField(sourceField.Title))
        {
            SPFieldLink destinationWebFieldLink = new SPFieldLink(destinationWeb.Fields[sourceField.Title]);
            newContentType.FieldLinks.Add(destinationWebFieldLink);
        }
    }
}

existingWeb and destinationWeb are 2 webs within the same site. The code runs fine. But the problem is that in the SITE Content Type screen (under site settings), when I click the custom column link in the custom content type, I got an error saying:

Invalid field name {UID}.

The UID is the same UID as the custom column in the existing site. I checked with my web settings after completion. I can see the custom list (which I created with an item for testing purpose), but the custom column is gone from the view (though the actual data is still there... just have to check the box to get it to display). But I think that is less important... more of fyi.

I've also gotten a variety of different exceptions should I copy things wrongly. Google has failed to help me out on this one.

Does anyone know what I'm missing in order to get that link to work again?

Thanks.

© Stack Overflow or respective owner

Related posts about sharepoint

Related posts about sharepoint2007