.NET King Logo Comments on: Creating SharePoint Permission levels programmatically (C#)
Skip Navigation Links
Home
Weblog
How to... (video)
Articles
About us
Contact us
0 Items in Video cart!

Creating SharePoint Permission levels programmatically (C#) (1/24/2009)

Imagine you are asked to create a custom permission level for all the sites in a MOSS/WSS site collection. I mean one of these things that you see in the below screen capture! Sounds silly, because you can easily click on the "Add a Permission Level" and finish the job. Now imagine that sites do not inherit the permission levels and you have only 200 sites in the site collection. Now it sounds like a nightmare.

Now here are the magic C# words to break the spell! Your code should automate this step.

Here are some important considerations.
1. You have 200 sites and there is no guarantee that all sites are following the same role inheritance setting. In better word some sites may inherit the roles and some don't. It is obvious that you cannot and you don't need to create this role in the sites that they inherit.
2. You have to create this role in the root website of the site collection.

Take a look at this code.

    SPWeb myWeb = mySite.AllWebs[i];
    if (myWeb.HasUniqueRoleDefinitions || myWeb.IsRootWeb)
    {
 
        try
        {
            MessageBox.Show(myWeb.Title);
            myWeb.AllowUnsafeUpdates = true;
            SPRoleDefinition rd = new SPRoleDefinition();
            rd.BasePermissions = SPBasePermissions.ManageLists |

            SPBasePermissions
.CancelCheckout |

SPBasePermissions.AddListItems
| SPBasePermissions.EditListItems |

SPBasePermissions.DeleteListItems;
      rd.Name = "Custom role 01";
      myWeb.RoleDefinitions.Add(rd);
      myWeb.Update();
  }
  catch (Exception ex)
  {
            MessageBox.Show(ex.Message, myWeb.Title);
  }
}

 Don't forget to import:
using Microsoft.SharePoint;

Cheers
Alireza


By: raj  
Hi Alireza
thanks a lot for sharing excellent code. I am having small question. can you explain how i can update existing site role. For example there is a custom role "publisher" in my sitecollection. now i have to add one more permission like "Edit page".

How to achieve this using code.

Please explain and help me.

thanks in advance
Raj
URL:  
By: Codeprizm  
Thanks for that
URL:  
By: samantha  
thank you very much
URL: http://www.google.com  
Your name:
Email:
URL:
Comments:
 

 -