Sunday, January 26, 2014

Create and Assign Custom Permission Levels programmatically in SharePoint


Sometimes, we come across a business requirement, where in:
-     We need to create SharePoint sites on the fly (maybe using a site definition), which have their own unique permission and groups.
-     We might need to create a custom permission level for the contributors for this site, say which does not have the delete rights but all other Contributor rights as is.
-     Then we need to assign this custom permission level to Contributor group and remove the default ‘Contribute’ permission level from the site.

        /// *************************************************************************
        /// <summary>
        /// Creating & Assigning custom permission
        /// level to Contributor group of root site
        /// </summary>
        /// <param name="spWeb">SpWeb object</param>
        /// <param name="myGroup">Group on which the custom permission
        /// has to be applied</param>
        /// ************************************************************************
        private void CreateAssignCustomPermissionLevel(SPWeb spWeb, SPGroup myGroup)
        {          
            spWeb.AllowUnsafeUpdates = true;
            //Get the role definition collection for this SPWeb
            SPRoleDefinitionCollection sprdcoll = spWeb.RoleDefinitions;
           
            //Define the new custom RoleDefinition
            SPRoleDefinition roleDefinition = new SPRoleDefinition();
            roleDefinition.Name = "MyCustomRoleDefinition";
           
            //And then start giving all permisions that you want to give.
            roleDefinition.BasePermissions =
            SPBasePermissions.AddListItems
            | SPBasePermissions.EditListItems
            //| SPBasePermissions.DeleteListItems //Delete permission removed from this definition.
            | SPBasePermissions.ViewListItems
            | SPBasePermissions.OpenItems
            | SPBasePermissions.ViewVersions
            | SPBasePermissions.DeleteVersions
            | SPBasePermissions.CreateAlerts
            | SPBasePermissions.ViewFormPages
            | SPBasePermissions.BrowseDirectories
            | SPBasePermissions.ViewPages
            | SPBasePermissions.BrowseUserInfo
            | SPBasePermissions.UseRemoteAPIs
            | SPBasePermissions.UseClientIntegration
            | SPBasePermissions.Open
            | SPBasePermissions.EditMyUserInfo; 

            //Add role definition to spweb
            if (!spWeb.RoleDefinitions.Xml.ToString().Contains("MyCustomRoleDefinition"))
            {
                spWeb.RoleDefinitions.Add(roleDefinition);
                spWeb.Update();
            }          

            //Assign custom role definition to the contributor group
            SPRoleAssignment assignment = new SPRoleAssignment(myGroup);
            //Add custom role definition to the SPRoleAssignment
            assignment.RoleDefinitionBindings.Add(roleDefinition);
            //Add the custom RoleAssignment to the SPWeb.
            spWeb.RoleAssignments.Add(assignment);          

            //Once we have the custom permission level assigned to contributors group,
            //we need to remove the default 'Contribute' permission level from this web
            spWeb.RoleDefinitions.Delete("Contribute");
            spWeb.Update();
            spWeb.AllowUnsafeUpdates = false;
        }

This method can be placed in feature receiver, where this feature is activated when the site is created.

Sunday, January 19, 2014

Enable Item Scheduling through code in SharePoint 2010


Many a times we need to create lists or sites from object model and hence it is often required to enable scheduling on list. Following code will do 3 things that are required to item scheduling:
  1. Enable Content approval
  2. Enable Versioning
  3. Enable Scheduling

    Scheduling is dependent on both versions and content approval and should be enabled first.

    Scheduling feature is only available in publishing site.


     using (SPSite site = new SPSite("http://sharepoint2010/"))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList list=web.Lists["Documents"];
                        list.EnableModeration = true;
                        list.EnableMinorVersions = true;
                        list.Update();
                        Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list);
                    }
                }


    list.EnableModeration = true; code will be actually doing the setting shown below:


    list.EnableMinorVersions = true; this code will enable the minor versioning on the list as shown below:



    Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list); This code will actually enable scheduling on this list




    To disable Scheduling in the list we can use following command:

    Microsoft.SharePoint.Publishing.PublishingWeb.DisableScheduling(list);

    ###############################################################

    We can also make use of powershell script for the same

    $list= $SPList = Get-SPList -url "http://sharepoint2010/" -List Documents
    $list.EnableModeration=$true
    $list.EnableMinorVersions=$true
    # To enable Scheduling in the list
    [Microsoft.SharePoint.Publishing.PublishingWeb]::EnableScheduling($list)
    # To disable Scheduling in the list
    [Microsoft.SharePoint.Publishing.PublishingWeb]::DisableScheduling($list)

    Sunday, January 5, 2014

    Using exception handling scope to handle errors in client object model : SharePoint 2010


    While using client object model in SharePoint 2010, many a times we come across situations where in we call the
    ctx.ExecuteQuery() method and some error occurs on the server due to which we get a 'ServerException' which does not give us the opportunity to make corrections in the operation that we are trying to do.

    The ExceptionHandlingScope class models a try/catch behaviour for such situations.When we add the code within this scope,it is processed as if its present in a try/catch and gives the opportunity to correct the error in the catch/finally block.

    For eg. lets take an example where in we are trying to update the description of a list using managed client object model.If the list does not exist in the target site, it will throw an exception.Now, in the catch block of the exception handling scope , we can create the list in the site and then update its description.

    The code below demonstrates this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Client;

    namespace Sharepoint2010TestConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {

               using (ClientContext ctx = new ClientContext("http://br-pc-341:2222"))
                {
                    //Set up error handling
                    ExceptionHandlingScope xScope = new ExceptionHandlingScope(ctx);

                    using (xScope.StartScope())
                     {
                        using (xScope.StartTry())
                        {
                            //Try to update the description of a list named "Test List"
                            List testList = ctx.Web.Lists.GetByTitle("Test List");
                            testList.Description = "Test List Description";
                            testList.Update();
                        }
                        using (xScope.StartCatch())
                        {
                            //Fails if the list "Test List" does not exist
                            //So, we'll create a new list
                            ListCreationInformation testListCI = newListCreationInformation();
                            testListCI.Title = "Test List";
                            testListCI.TemplateType = (int)ListTemplateType.GenericList;
                            testListCI.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
                            List list = ctx.Web.Lists.Add(testListCI);
                        }
                        using (xScope.StartFinally())
                        {
                            //Try to update the list now if it failed originally
                            List testList = ctx.Web.Lists.GetByTitle("Test List");
                            if (testList.Description.Length == 0)
                            {
                                testList.Description = "Test List Description";
                                testList.Update();
                            }
                        }
                    }
                    //Execute the entire try-catch as a batch!
                    ctx.ExecuteQuery();

                    Console.WriteLine("Description Updated !!");
                }

            }
        }
    }


    This console application updates the description of the list named 'Test List'. If the list does not exist , the list is
    created in the catch block and then the description is updated.



    The list with the updated description can be seen on the sharepoint site:


    SharePoint / Office 365 Developer Patterns and Practices

    Server Error in '/' Application when activating "Nintex Forms" web app feature.

    Apparently "INSTALL-NFService" need to be run in SharePoint PowerShell to fix this problem.   When I installed Nintex Forms agai...