K2 Role Manipulation using the SourceCode.Security.UserRoleManager.Management Namespace
Programmatic K2 Roles
If you ever wondered how to programmatically
without using K2 Workspace, the code sections below give you an example to execute these operations using the SourceCode.Security.UserRoleManager.Management namespace.
This is particularly useful when you script your K2 Processes deployment.
Let’s start
Crack open your favourite C# IDE
Make sure you add a reference to the following Assemblies:
SourceCode.Security.UserRoleManager.Management.dll
SourceCode.HostClientAPI.dll
Include the following code in your using directive
using SourceCode.Security.UserRoleManager.Management;
using SourceCode.Hosting.Client.BaseAPI;
Paste the following helper in your Program Class. This fetches an open connection to the K2 Host Server’s User Role Manager. You can also use a new instance of the SCConnectionStringBuilder to create your ConnectionString.
static UserRoleManager FetchManager(string K2HostServer)
{
UserRoleManager manager = new UserRoleManager();
manager.CreateConnection();
manager.Connection.Open(string.Format("Integrated=True;IsPrimaryLogin=True;Authenticate=True;EncryptedPassword=False;Host={0};Port=5555", K2HostServer));
return manager;
}
Crack open a connection to the server
// K2 Host Server
string K2HostServer = "BTE-SANDPIT";
// Get the Server
UserRoleManager server = FetchManager(K2HostServer);
Add a K2 Role (Create a K2 Role)
// Fill the Role Container
Role role = new Role("Some K2 Role we like to create using the K2 API"); role.Description = "Description";
role.IsDynamic = true;
... add the Users
// Add some Users
role.Include.Add(new UserItem(@"K2:ESSEXCCBTE\Administrator"));
role.Include.Add(new UserItem(@"K2:ESSEXCCBTE\arno.vanrooyen"));
// The below demonstrates how to add a non-K2 security item
//role.Include.Add(new UserItem(@"Ecc HOIS:mark"));
Use the server instance and execute the operation
// "Create"
server.CreateRole(role);
Update a K2 Role (Add/Remove users)
// "Read" / "Update"
server.GetRole(role.Name);
role.Description = "Updated Description";
server.UpdateRole(role);
Change User Items...
// Update Items
role.Exclude.Clear();
role.Include.Clear();
role.Include.Add(new UserItem(@"K2:ESSEXCCBTE\Administrator"));
server.UpdateRole(role);
Delete a K2 Role
// "Delete"
server.DeleteRole(role.Guid, role.Name);
Finishing off
The last thing you need to remember is to close the connection to the K2 Host Server. This can be done using the following code
server.DeleteConnection();
A final note: You might want to create a Helper Wrapper Class around the K2 Management Classes to unify all Management operations and encourage re-use of code.