Tuesday 29 September 2015

Copy List Permission/RoleAssigment from Source List to Destination List SharePoint

public static void CopyListRoleAssignments(SPList sourceList, SPList destinationList)
        {
            //First check if the Source List has Unique permissions
            if (sourceList.HasUniqueRoleAssignments)
            {

                //Break List permission inheritance first
                destinationList.BreakRoleInheritance(true);

                //Remove current role assignemnts
                while (destinationList.RoleAssignments.Count > 0)
                {
                    destinationList.RoleAssignments.Remove(0);
                }


                //Copy Role Assignments from source to destination list.
                foreach (SPRoleAssignment sourceRoleAsg in sourceList.RoleAssignments)
                {
                    SPRoleAssignment destinationRoleAsg = null;

                    Get the source member object
                    SPPrincipal member = sourceRoleAsg.Member;

                    Check if the member is a user
                    try
                    {
                        SPUser sourceUser = (SPUser)member;
                        SPUser destinationUser = destinationList.ParentWeb.Users.GetByEmail(sourceUser.Email);
                        destinationRoleAsg = new SPRoleAssignment(destinationUser);
                    }
                    catch
                    { }

                    if (destinationRoleAsg == null)
                    {
                        //Check if the member is a group
                        try
                        {
                            SPGroup sourceGroup = (SPGroup)member;

                            SPGroup destinationGroup = destinationList.ParentWeb.SiteGroups[sourceGroup.Name];
                            destinationGroup.AddUser((SPUser)member);
                            destinationRoleAsg = new SPRoleAssignment(destinationGroup);

                        }
                        catch
                        { }
                    }

                    //At this state we should have the role assignment established either by user or group
                    if (destinationRoleAsg != null)
                    {

                        foreach (SPRoleDefinition sourceRoleDefinition in sourceRoleAsg.RoleDefinitionBindings)
                        {
                            try { destinationRoleAsg.RoleDefinitionBindings.Add(destinationList.ParentWeb.RoleDefinitions[sourceRoleDefinition.Name]); }
                            catch { }
                        }

                        if (destinationRoleAsg.RoleDefinitionBindings.Count > 0)
                        {
                            //handle additon of an existing  permission assignment error
                            try { destinationList.RoleAssignments.Add(destinationRoleAsg); }
                            catch (ArgumentException) { }
                        }

                    }

                }

               // Does not require list update
                destinationList.Update();
            }
            else
                //No need to assign permissions
                return;



        }

Copy List Item Permission/ Role Assignment SharePoint Server Object Model


        public static void CopyListItemsRoleAssignments(SPList sourceList, SPList destinationList)
        {
            foreach (SPListItem sourceListitem in sourceList.Items)
            {
                CopyListItemRoleAssignments(sourceListitem, destinationList.GetItemById(sourceListitem.ID));
            }

        }
        public static void CopyListItemRoleAssignments(SPListItem sourceListItem, SPListItem destinationListItem)
        {
            //First check if the Source List has Unique permissions
            if (sourceListItem.HasUniqueRoleAssignments)
            {

                Break List permission inheritance first
                destinationListItem.BreakRoleInheritance(true);
                destinationListItem.Update();

               // Remove current role assignemnts
                while (destinationListItem.RoleAssignments.Count > 0)
                {
                    destinationListItem.RoleAssignments.Remove(0);
                }
                destinationListItem.Update();

                //Copy Role Assignments from source to destination list.
                foreach (SPRoleAssignment sourceRoleAsg in sourceListItem.RoleAssignments)
                {
                    SPRoleAssignment destinationRoleAsg = null;

                    Get the source member object
                    SPPrincipal member = sourceRoleAsg.Member;

                    //Check if the member is a user
                    try
                    {
                        SPUser sourceUser = (SPUser)member;
                        SPUser destinationUser = destinationListItem.ParentList.ParentWeb.AllUsers[sourceUser.LoginName];
                        if (destinationUser != null)
                        {
                            destinationRoleAsg = new SPRoleAssignment(destinationUser);
                        }
                    }
                    catch
                    { }

                    ///Not a user, try check if the member is a Group
                    if (destinationRoleAsg == null)
                    {
                        Check if the member is a group
                        try
                        {
                            SPGroup sourceGroup = (SPGroup)member;
                            SPGroup destinationGroup = destinationListItem.ParentList.ParentWeb.SiteGroups[sourceGroup.Name];
                            if (destinationGroup != null)
                            {
                                destinationRoleAsg = new SPRoleAssignment(destinationGroup);
                            }
                        }
                        catch
                        { }
                    }

                    //At this state we should have the role assignment established either by user or group
                    if (destinationRoleAsg != null)
                    {

                        foreach (SPRoleDefinition sourceRoleDefinition in sourceRoleAsg.RoleDefinitionBindings)
                        {
                            try { destinationRoleAsg.RoleDefinitionBindings.Add(destinationListItem.ParentList.ParentWeb.RoleDefinitions[sourceRoleDefinition.Name]); }
                            catch { }
                        }

                        if (destinationRoleAsg.RoleDefinitionBindings.Count > 0)
                        {
                            handle additon of an existing  permission assignment error
                            try { destinationListItem.RoleAssignments.Add(destinationRoleAsg); }
                            catch (ArgumentException) { }
                        }

                    }

                }

               // Ensure item update metadata is not affected.
                destinationListItem.SystemUpdate(false);
            }
            else
                ///No need to assign permissions
                return;



        }

Copy Source Web Role Definition to Destination Web SharePoint Server Object Model

public static void CopyWebRoles(SPWeb sourceWeb, SPWeb destinationWeb)
        {

          // copy Source Web Role Definitions to the Destination Web
            foreach (SPRoleDefinition roleDef in sourceWeb.RoleDefinitions)
            {
                Skip WSS base permission levels
                if (roleDef.Type != SPRoleType.Administrator
                    && roleDef.Type != SPRoleType.Contributor
                    && roleDef.Type != SPRoleType.Guest
                    && roleDef.Type != SPRoleType.Reader
                    && roleDef.Type != SPRoleType.WebDesigner
                    )
                {
                    //handle additon of existing  permission level error

                    try
                    {
                        if (destinationWeb.HasUniqueRoleDefinitions)
                        {
                            destinationWeb.RoleDefinitions.BreakInheritance(true, false);
                            destinationWeb.RoleDefinitions.Add(roleDef);

                        }

                    }
                    catch (SPException) { }
                }
            }


        }

SharePoint 2013 Filter Items Using Rest API

 function GetProjects() {
                var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + projectListName + "')/items?" + "$filter=((substringof('" + user.get_title() + "',Members)) and (ProjectStatus+eq+'Open'))";
                $.ajax({
                    url: url,
                    type: "GET",
                    headers: { "accept": "application/json;odata=verbose" },
                    success: function (data) {
                       for (var i = 0; i < data.d.results.length; i++) {
                            var project = data.d.results[i].Title;
                          
                        }
                      
                    },
                    error: function (xhr) {
                        alert(xhr.status + ': ' + xhr.statusText);
                        console.log(xhr.status + ': ' + xhr.statusText);
                    }
                });
            }

-----------------------------------------------------------------
Filter on Date Fields
------------------------------------------------------------------




    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl +
            "/_api/lists/getbytitle('TimesheetEntry')/items?$filter=Date+gt+'" + FromDate + "' and Date+le+'" +ToDate + "'",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            if (data.d.results.length > 0) {
                $.each(data.d.results, function (i, item) {
                  var a=  data.d.results[i].Date;
                  var b=  data.d.results[i].User;
                });


            }
        },
        error: function (err) {
            console.log(JSON.stringify(err));

        }
    });

Get Current User Permission in Sharepoint Online Uisng REST API

function getCurrentUserPermission(userId) {
    $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + userId + ")/Groups",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        dataType: "json",
        async: true,
        success: function (data) {
            /* get all group's title of current user. */
            for (var i = 0; i < data.d.results.length; i++) {
                if (data.d.results[i].Title == "Users") {
                    groupName = data.d.results[i].Title
                }
                else if (data.d.results[i].Title == "Admin") {
                    groupName = data.d.results[i].Title;
                   
                }
                else if (data.d.results[i].Title == "Operation") {
                    groupName = data.d.results[i].Title;
                  }
            }
        }
    });
}

Create Group Using SharePoint 2013 REST API

function createSharepointGroup() {
    var groupName = [];
    groupName.push({ title: 'Admin', desc: "Admin Groups users in this group has full rights" });
    groupName.push({ title: 'Operation', desc: "Operation Group" });
    groupName.push({ title: 'Users', desc: "Users Group" });
    for (var i = 0; i < groupName.length; i++) {
        var spGroup = {
            "__metadata": {
                "type": "SP.Group"
            },
            "Title": groupName[i].title,
            "Description": groupName[i].desc,
        };

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteGroups",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(spGroup),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function (data) {
                //success(data);
            },
            error: function (data) {
                //failure(data);
            }
        });
    }

}