Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create folder structure in SDL Tridion 2011 SP1 using Core Service

Tags:

c#

tridion

I am using the Core Service on Tridion 2011. I want to create a folder structure, and then create a component in that structure.

Example: Path of folder structure: /ABCD/DEFG/aaaaa

If the folder exists, we need not create folder. If it doesn't exist we have to create it and create component in it.

I know how to create the component in a folder having URI.

like image 839
Patan Avatar asked Mar 28 '12 09:03

Patan


2 Answers

The following is the code I use when I need to Get or Create Folders with SDL Tridion's CoreService. It's a simple recursive method that checks for the existence of the current folder. If it doesn't exist, it goes into GetOrCreate the parent folder and so on until it finds an existing path. On the way out of the recursion, it simply creates the new Folders relative to their immediate parent.

Note: this method does not check the input folderPath. Rather, it assumes it represents a valid path.

private FolderData GetOrCreateFolder(string folderPath, SessionAwareCoreServiceClient client)
{
    ReadOptions readOptions = new ReadOptions();

    if (client.IsExistingObject(folderPath))
    {
        return client.Read(folderPath, readOptions) as FolderData;
    }
    else
    {
        int lastSlashIdx = folderPath.LastIndexOf("/");
        string newFolder = folderPath.Substring(lastSlashIdx + 1);
        string parentFolder = folderPath.Substring(0, lastSlashIdx);
        FolderData parentFolderData = GetOrCreateFolder(parentFolder, client);
        FolderData newFolderData = client.GetDefaultData(ItemType.Folder, parentFolderData.Id) as FolderData;
        newFolderData.Title = newFolder;

        return client.Save(newFolderData, readOptions) as FolderData;
    }
}
like image 130
Mihai Cădariu Avatar answered Sep 30 '22 11:09

Mihai Cădariu


I would use IsExistingObject - passing in the WebDAV URL - to see if the Folder already exists. If it returns false, you can go ahead and create the folder.

Edit: Here's some quick pseudo code...

string parentFolderId = @"/webdav/MyPublication/Building%20Blocks";

var client = GetCoreServiceClient();

if (!client.IsExistingObject(parentFolderId + "/AAA"))
{
   var folder = client.GetDefaultData(2, parentFolderId);
   folder.Title = "AAA";
   client.Save(folder);
   // Create the other folders and components here
}
like image 44
Peter Kjaer Avatar answered Sep 30 '22 11:09

Peter Kjaer