Programmatically Creating DNN Roles A Gotcha Moment!
This is just a quick blog post to hopefully share some helpful information. Recently when working on a DotNetNuke Authentication Provider for a client I was tasked with syncing roles from the external system into DNN. Simple enough right? We can just use the "RoleController" and the "AddRole" method to add the role to the system. Well, that is the process but it doesn't work 100% unless you specify specific items. The following sections show what I tried, and what actually works, along with a few notes.
My Starting Code
I think a logical starting point here would be to show what I used as my first attempt for adding a new role to the system.
RoleController oDnnRoleController = new RoleController;
RoleInfo oRole = new RoleInfo;
oRole.PortalId = this.PortalId;
oRole.RoleName = "MyRoleName";
oRole.IsPublic = false;
oRole.AutoAssignment = false;
oDnnRoleController.AddRole(oRole);
At first glance, this would seem just perfect right? Not so much, no error is generated, but the role is not added to the system.
The Fix
The fix was very simple, after digging through the code, and googling for a while to get the best solution. Simply set the RoleGroupID = -1 and it will work just fine. So my updated working code is as follows:
RoleController oDnnRoleController = new RoleController;
RoleInfo oRole = new RoleInfo;
oRole.PortalId = this.PortalId;
oRole.RoleName = "MyRoleName";
oRole.IsPublic = false;
oRole.AutoAssignment = false;
oRole.RoleGroupID = -1;
oDnnRoleController.AddRole(oRole);
Conclusion
I hope that this article helps someone else out looking to create DNN roles via Code. Feel free to share comments below.
Posted by Mitchel on Thursday, May 14, 2009
Name (required)
Email (required)
Website