Tuesday, July 26, 2016

Create document set in SharePoint Online with CSOM

It's very easy to create a document set in SharePoint Online (Office365) with csom. There is not really an API available at this moment, but by converting a folder we can achieve our goal.

If your DocumentSet content type contains other content types, you could end up with a yellow banner saying:
Content types that are available to this Document Set have been added or removed.  Update the Document Set.
If you see this banner, the content types under the new button aren't correct either. You can fix this by setting docset_LastRefresh and vti_contenttypeorder folder properties.

/// <summary>
/// Create documentset from folder
/// </summary>
/// <param name="ctx">SharePoint clientcontext</param>
/// <param name="libraryUrl">web relative document library url</param>
/// <param name="documentSetName">name for the new document set</param>
/// <param name="documentSetContentTypeId">content type of the new document set.
/// We assume that this content type is already binded to the document library.</param>
public ListItem CreateDocumentSet(ClientContext ctx, string libraryUrl, string documentSetName, string documentSetContentTypeId)
{
//get document library where we want to add the document set
var docLib = ctx.Web.GetListByUrl(libraryUrl);
//fetch stringId's from available contenttypes
docLib.EnsureProperties(l => l.ContentTypes.Include(c => c.StringId));
ctx.ExecuteQuery();
//add folder in library
var folderInfo = new ListItemCreationInformation
{
UnderlyingObjectType = FileSystemObjectType.Folder
};
docSet = docLib.AddItem(folderInfo);
//name field
docSet["FileLeafRef"] = documentSetName;
//contentTypeId: eg: 0x0120D520
docSet["ContentTypeId"] = documentSetContentTypeId;
//if you don't set file type, the icon will remain the regular folder icon and clicking the folder
//won't redirect you to document set welcomePage.
docSet["HTML_x0020_File_x0020_Type"] = "SharePoint.DocumentSet";
//IMPORTANT: if your document set content type contains other content types,
//you should update these properties as well. Otherwise a yellow banner will appear and
//under the 'New' button the content types won't be correct.
docSet.Folder.Properties["docset_LastRefresh"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss");
docSet.Folder.Properties["vti_contenttypeorder"] = string.Join(",", docLib.ContentTypes.ToList().Where(c => c.StringId.StartsWith(BuiltInContentTypeId.Document + "00")).Select(c => c.StringId));
//send changes to SharePoint.
docSet.Folder.Update();
docSet.Update();
ctx.ExecuteQuery();
return docSet;
}
cheers!

No comments:

Post a Comment