Saturday, May 31st, 2008

Create Custom Policy programmatically



Answering a forum thread I had to do a bit of digging into how to create new Policies in code.

This post from Ethan helped point me in the right direction.   The requirement was to programmatically give users Full Control of a web application, the code snippet below shows how to achieve this.

SPWebApplication oWebApplication = SPWebApplication.Lookup(new Uri(“http://webappurl”)); SPPolicy policy = oWebApplication.Policies.Add(“domain\\username”, “MyCustomPolicy”);policy.PolicyRoleBindings.Add(oWebApplication.PolicyRoles.GetSpecialRole(SPPolicyRoleType.FullControl));oWebApplication.Update(); 

You may have noticed that the policy only allows for one username,  this is the case even though the UI gives you the option to enter multiple, only the first is stored.

  • Ven,
    The reason is probably due to you not setting any policy bindings, as in the post example:-

    policy.PolicyRoleBindings.Add(oWebApplication.PolicyRoles.GetSpecialRole(SPPolicyRoleType.FullControl));
  • Ven
    Hi,
    I am trying to get the users from the "Policy of Web Application" in Central Administration through Object Model

    and also trying to add users to the same Policy through object model. I am using the following code to achieve

    this. But I am getting an "Object Reference Not Set to an Instance of an Object" exception when I am trying to call

    the Update Method of the SPWebApplication object.
    Please help me. The strange thing happening here is,when I am trying to add the users to the WebApplication policy,

    the users are getting added to though the update fails. The next time when I debug the application, I do see the

    new users added though the update failed. Moreover, I am not able to see the newly added users in the "Policy For

    Web Application" section of the Central Administration. Can anyone please help me out. Here is the code which I am

    using to achieve this.

    SPFarm farm = SPFarm.Local;
    SPWebService service = farm.Services.GetValue("");
    foreach(SPWebApplication webApp in service.WebApplications)
    {
    if(webApp.Name == "My Web App")
    {
    webApp.ZonePolicies(SPUrlZone.Default).Add("username","displayname");
    webApp.Update(); // I am getting the Object Reference error at this line
    }
    }


    Please help me ASAP.
blog comments powered by Disqus