I'm using Tridion 2013 and creating components within a folder in Tridion. Its possible these components may have the same name, which obviously Tridion does not allow.
I'm using the following code to check whether an item with a given name already exists, and if so return a unique title string:
protected string GetUniqueTitle(string title, string folderId)
{
return GetUniqueTitle(title, folderId, 1);
}
protected string GetUniqueTitle(string original, string folderId, int current)
{
var title = string.Format("{0} {1}", original, current);
var filter = new SearchQueryData
{
Title = title,
IsTitleCaseSensitive = false,
ItemTypes = new[] {ItemType.Component},
SearchIn = new LinkToIdentifiableObjectData {IdRef = folderId},
SearchInSubtree = false
};
var component = (ComponentData) _client.GetSearchResults(filter).FirstOrDefault();
if (component != null)
{
return GetUniqueTitle(original, folderId, current + 1);
}
return title;
}
This code is working fine, but I've noticed during testing that if I quickly create multiple components with the same name, using this method to get a unique title, _client.GetSearchResults(...)
will return null
for the last one created.
Presumably this is because GetSearchResults
uses Tridion's search index behind the scenes and this has not been populated quickly enough.
This is not likely to be a problem in practice, but it would be nice to be able to avoid it entirely.
So, my question is, is there another way to retrieve a component by name, or to check that a given name already exists within a folder?
I could simply try to create the component and catch the exception, but this would involve checking the exception message, which seems a bit hacky, as the Core Service always throws a WCF FaultException
.
Any help, as always, much appreciated.