May 14, 2009

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.

tags: DNN Development
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.