Thursday, March 13, 2014

Creating a user with the SDL Tridion Core Service

I was at a new project this week creating a Tridion user for a developer in the team while discovering that the CME could not list the domain users. This can happen when the MTSuser does not have access to the domain. A simple Core Service tool helped out once again. This command line application creates a user, without lookup in the active directory. I needed only one user so I just ran it from Visual Studio. 

Other versions
This is for SDL Tridion 2013 SP1, for previous versions (Tridion 2011 and up) you might have to use another configuration name (basicHttp_2013 in this case) and replace the contents of the app.config with Tridion.ContentManager.CoreService.Client.dll.config. In the app.config you can update the url for the basicHttp_2013 endpoint to match the hostname of your Tridion Content Manager server. 

Code
using System;
using System.ServiceModel;
using Tridion.ContentManager.CoreService.Client;
namespace CoreServiceSandbox
{
internal class Program
{
private static void Main(string[] args)
{
var client = new CoreServiceClient("basicHttp_2013");
try
{
Console.WriteLine("The current user is {0}\n", client.GetCurrentUser());
UserData user = client.GetDefaultData(ItemType.User, null, new ReadOptions()) as UserData;
Console.Write("Username (domain\\username): ");
user.Title = Console.ReadLine();
Console.Write("Full name: ");
user.Description = Console.ReadLine();
Console.Write("Is Tridion administrator: ");
user.Privileges= ("yes".Equals(Console.ReadLine()) ? 1 : 0);
Console.WriteLine("\nCreating user...");
user = client.Create(user, new ReadOptions()) as UserData;
Console.WriteLine("Created user {0}\n Username {1}\n Description {2}\n Privleges {3}", user.Id, user.Title, user.Description, user.Privileges);
}
catch (FaultException<CoreServiceFault> e)
{
Console.WriteLine("Error; Core Service said: {0}; {1} ", e.Detail.ErrorCode, string.Join(", ", e.Detail.Messages));
}
catch (CommunicationException e)
{
Console.WriteLine("Error; Could not connect to the Core Service\n {0}\n {1}", e.Message, e.InnerException);
client.Abort(); //The channel is aborted and the resources released.
}
catch (TimeoutException e)
{
Console.WriteLine("Error; Could not connect to the Core Service\n {0}\n {1}", e.Message, e.InnerException);
client.Abort(); //The channel is aborted and the resources released.
}
catch (Exception e)
{
Console.WriteLine("Error; Could not connect to the Core Service\n {0}\n {1}", e.Message, e.InnerException);
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}

PowerShell
Before using the Visual Studio solution I tried to create the user with the tridion-powershell-modules, I could not get that one to work due to some error but it is the best way to do this task: It supports all Tridion versions and no Visual Studio and bespoke command line applications needed.