Search This Blog

Thursday, May 12, 2016

Delete Roles from Site Permission programmatically

OBJECTIVE

How to remove Roles for:  single user, all users, groups or everybody.

The following is a variable used in the code:
-          Web: the SPWeb object of the sub site you want to manage.

1)       REMOVE ALL ROLES
2)       REMOVE ALL ROLES ONLY FOR USERS
3)       REMOVE ALL ROLES ONLY FOR GROUPS
4)       REMOVE SINGLE USER ROLES
5)       REMOVE A SPECIFIC ROLE DEFINITION FOR EVERYBODY
6)       REMOVE A SPECIFIC ROLE DEFINITION FOR A USER

 1) REMOVE ALL ROLES 

SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
{
    SPRoleAssColn.Remove(i);
}

2) REMOVE ALL ROLES ONLY FOR USERS 

       SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
       for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
       {
             SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
              System.Type t = roleAssignmentSingle.Member.GetType();
              if(t.Name=="SPUser")
                SPRoleAssColn.Remove(i);
}

3) REMOVE ALL ROLES ONLY FOR GROUPS 

       SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
       for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
       {
             SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
              System.Type t = roleAssignmentSingle.Member.GetType();
              if(t.Name=="SPGroup")
                SPRoleAssColn.Remove(i);
}

4) REMOVE SINGLE USER ROLES:     

        private void RemoveUserRoles(SPUser user)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                SPPrincipal wUser = (SPPrincipal)user;
                if (roleAssignmentSingle.Member.ID == wUser.ID)
                {
                    SPRoleAssColn.Remove(i);
                }
            }
        }

5) REMOVE SPECIFIC ROLE DEFINITION FOR EVERYBODY:
Ex. Remove the Read permission from all the people or groups 

        private static void RemoveSpecificRole(SPRoleType RoleSPWeb Web)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                for (int j = roleAssignmentSingle.RoleDefinitionBindings.Count -1; j>=0; j--)
                {
                    SPRoleDefinition roleDefinitionSingle = roleAssignmentSingle.RoleDefinitionBindings[j];
                    if (roleDefinitionSingle.Type == Role)
                    {
                        roleAssignmentSingle.RoleDefinitionBindings.Remove(roleDefinitionSingle);
                        roleAssignmentSingle.Update();
                    }
                }
            }
        }


6) REMOVE SPECIFIC ROLE DEFINITION FOR A USER:
Ex. Remove the Contribute permission to a specific user. 

        private static void RemoveSpecificRoleForUser(SPUser user, SPRoleType RoleSPWeb Web)
        {
            SPRoleAssignmentCollection SPRoleAssColn = Web.RoleAssignments;
            for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
            {
                SPRoleAssignment roleAssignmentSingle = SPRoleAssColn[i];
                SPPrincipal wUser = (SPPrincipal)user;
                if (roleAssignmentSingle.Member.ID == wUser.ID)
                {
                     for (int j = roleAssignmentSingle.RoleDefinitionBindings.Count; j>=0; j--)
                    {
                        SPRoleDefinition roleDefinitionSingle = roleAssignmentSingle.RoleDefinitionBindings[j];
                        if (roleDefinitionSingle.Type == Role)
                        {
                            roleAssignmentSingle.RoleDefinitionBindings.Remove(roleDefinitionSingle);
                            roleAssignmentSingle.Update();
                        }
                    }
                }
            }
        }

PeopleEditor To SPFieldUserValueCollection

OBJECTIVE

To programmatically copy people selected from an asp.net People Editor to a SPFieldUserValueCollection
 field.

SPECIFICATION
The People Editor can contain multiple people, and allow Users and Groups selection.

SOLUTION
// myPeopleEditor is a PeopleEditor object in my asp.net form.

..
Item[“MyUserField”] = GetPeople(myPeopleEditor, Web);
..


private SPFieldUserValueCollection GetPeople(PeopleEditor people, SPWeb web)
{
  SPFieldUserValueCollection values = new SPFieldUserValueCollection();
  if (people.ResolvedEntities.Count > 0)
  {
    for (int counter = 0; counter < people.ResolvedEntities.Count; counter++)
    {
        PickerEntity user = (PickerEntity)people.ResolvedEntities[counter];
        switch ((string)user.EntityData["PrincipalType"])
        {
          case "User":
            SPUser webUser = web.EnsureUser(user.Key);
            SPFieldUserValue userValue = new SPFieldUserValue(web, webUser.ID, webUser.Name);
            values.Add(userValue);
          break;
 
          case "SharePointGroup":
            SPGroup siteGroup = web.SiteGroups[user.EntityData["AccountName"].ToString()];
            SPFieldUserValue groupValue = new SPFieldUserValue(web, siteGroup.ID, siteGroup.Name);
            values.Add(groupValue);                        
          break;
        }
      }
    }
    return values;
  }

ECMAScript – Get Current Web ID

OBJECTIVE

To programmatically obtain the Current Web ID, with JavaScript Client Object Model.

NEEDS EXAMPLE
One wants to open a Page inside a SharePoint popup, and pass in query string the current Web ID.

SOLUTION
In this example it retrieves one list by Title from the Root Web.

<input onclick="javascript:init();" type="button" value="Task Selector"/>
<SharePoint:ScriptLink ID="ScriptLink1" Name="sp.js" runat="server" OnDemand="true" Localizable="false" />

<script type="text/ecmascript">
    var options;
        function portal_openModalDialog(pageUrl) {
            options = SP.UI.$create_DialogOptions();
            options.width = 600;
            options.height = 400;
            options.url = pageUrl;
            options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
            SP.UI.ModalDialog.showModalDialog(options);
        } 

        function CloseCallback(result, target) {
            location.reload(true);
        }

        function init()
        {
            var context = new SP.ClientContext.get_current();
            this.Web = context.get_web();
            context.load(this.Web);
            context.executeQueryAsync(Function.createDelegate(thisthis.onSuccess),
                Function.createDelegate(thisthis.onFail));
        }

        function onSuccess(sender, args)
        {
            portal_openModalDialog("http://myserver/Pages/default.aspx?WebID=" + this.Web.get_id());
        }

        function onFail(sender, args) {
            alert('Failed:' + args.get_message());
        }
</script>

ECMAScript - How to get lists

OBJECTIVE

To show different ways to retrieve lists:
  1)       RETRIVING CURRENT LIST
   2)       RETRIVING LIST BY ‘TITLE’
  3)       RETRIVING LIST BY ‘ID’
  4)       RETRIVING ALL LISTS 
   5)       RETRIVING A SINGLE PROPERTY FROM LISTS


1) RETRIVING CURRENT LIST
When you are working with lists (ex by Ribbon Button), sometime it is necessary to know the current list 
by client side.
If you are working with the standard view, you can use it:

  var list = SP.ListOperation.Selection.getSelectedList();

Instead if you are working in datasheet, you may have some problems. At the following link it is suggested 
a workaroundhttp://msdn.microsoft.com/en-us/library/ff410971.aspx.



2) RETRIVING LIST BY ‘TITLE’
In this example it retrieves one list by Title from the Root Web.


<script type="text/ecmascript">

    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');    

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb(); 
        this.list = myweb.get_lists().getByTitle('ListTitle'); //Edit the title
        clientContext.load(list);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetList), Function.createDelegate(this
getFailed));
    }

    function GetList() {
            alert(list.get_title() + ': ' + list.get_id().toString());
    }
   
    function getFailed() {
        alert('Failed.');
    }
</script>



3) RETRIVING LIST BY ‘ID’
In this example it retrieves one list by Id from the Root Web.

<script type="text/ecmascript">

    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');

    function initialize() {
        var value = SP.ListOperation.Selection.getSelectedList();  
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        this.myweb = siteColl.get_rootWeb();
        this.list = myweb.get_lists().getById('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'); //Edit the ID
        clientContext.load(list);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetList), Function.createDelegate(this
getFailed));
    } 

    function GetList() {
        alert(list.get_title() + ': ' + list.get_id().toString());
    } 

    function getFailed() {
        alert('Failed.');
    } 

</script>



4) RETRIVING ALL LISTS
In this example it retrieves all the lists in the Root Web

<script type="text/ecmascript">
   
    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');    

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb(); 
        this.lists = myweb.get_lists();
        clientContext.load(lists);
        clientContext.executeQueryAsync(Function.createDelegate(this, GetLists), Function.createDelegate(this,
 getFailed));
    }

    function GetLists() {
        var listEnumerator = lists.getEnumerator();
        while (listEnumerator.moveNext()) {
            list = listEnumerator.get_current();
            alert(list.get_title());
        }
    }

    function getFailed() {
        alert('Failed.');
    }
</script>



5) RETRIVING A SINGLE PROPERTY FROM LISTS
When you retrieve a list or a collection of list, you can choice what properties you want.  In this example 
it retrieves the ID for all the lists in the root web.
<script type="text/ecmascript">
    
    SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');    

    function initialize() {
        var clientContext = new SP.ClientContext();
        var siteColl = clientContext.get_site();
        myweb = siteColl.get_rootWeb(); 
        this.lists = myweb.get_lists();
        clientContext.load(lists, 'Include(Id)');
        clientContext.executeQueryAsync(Function.createDelegate(this, GetLists), Function.createDelegate(this
getFailed));
    }

    function GetLists() {
        var listEnumerator = lists.getEnumerator();
        while (listEnumerator.moveNext()) {
            list = listEnumerator.get_current();
            alert(list.get_id());
        }
    }
  
    function getFailed() {
        alert('Failed.');
    }   
</script>

Wednesday, May 11, 2016

SharePoint 2013: Filtering and Sorting of List Data using AngularJS and REST-API

This article explains how to filter and sort in SharePoint List data using Angular JS /REST-API. I used the REST API to talk to SharePoint and get the data from the list. I am not going to discuss much about the REST services since many folks have already done great work on explaining REST API services.

In this article we just see that we have first created an Angular Controler with the name "spCustomerController." We have also injected $scope and $http service. The $http service will fetch the list data from the specific columns of the SharePoint list. $scope is a glue between a Controller and a View. It acts as execution context for expressions. Angular expressions are code snippets that are usually placed in bindings such as {{ expression }}.we’ll be looking at a way tosort and filter our tabular data. This is a common feature that is always useful so let’s look at what we’ll be building and dive right into the code

Solution

We will implement on a Sample Application and try to get the data from the SharePoint list, bind the table and apply sort and filter to our tabular data.

Our application will allow us to:
  • Show a table of data (ng-repeat)
  • Sort by ascending or descending columns (orderBy)
  • Filter by using a search field (filter)
These are three common functions in any application and Angular lets us implement these features in a very simple way. Let’s set up our sample application’s HTML and Angular parts and then look at how we can sort and filter.

















<%@ Register TagPrefix="WpNs0" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<meta name="WebPartPageExpansion" content="full" />
<meta name="ProgId" content="SharePoint.WebPartPage.Document" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Angular JS</title>
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<SharePoint:CssRegistration Name="default" runat="server"/>
<style>  
table, td, th {  
    border: 1px solid green;  
}  
  
th {  
    background-color: green;  
    color: white;  
}  
</style>  
<script type="text/javascript" src="../SiteAssets/JS/Scripts/JQueryv1.10.3.js"></script>  
<script type="text/javascript" src="../SiteAssets/JS/Scripts/angular.min.js"></script>  

  
<script type="text/javascript">  
      
    var myAngApp = angular.module('SharePointAngApp', []);  
    myAngApp.controller('spCustomerController', function ($scope, $http) {  
        $http({  
            method: 'GET',  
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getByTitle('Country')/items?$select=Title,CountryCode,SortOrder,Created,Modified ",  
            headers: { "Accept": "application/json;odata=verbose" }  
        }).success(function (data, status, headers, config) {  
            $scope.customers = data.d.results;  
             $scope.mySortFunction = function(  
                customer)  
            { //Sorting Iteam  
                if (isNaN(customer[$scope.sortExpression]))  
                    return customer[$scope.sortExpression];  
                return parseInt(customer[$scope.sortExpression]);  
            }  
        }).error(function (data, status, headers, config) {  
         
        });  
    });  
      
  
</script>  
  
<h1> Angular JS SharePoint 2013 REST API !!</h1>
</head>

<body>

<form id="form1" runat="server">
<ZoneTemplate></ZoneTemplate></form>


<div ng-app="SharePointAngApp" class="row">
    <div ng-controller="spCustomerController" class="span10">
    <div style="background-color:fuchsia;border: thick;border-color:fuchsia;width:555px">
     <div class="span10">  
                    Sort by:  
                    <select ng-model="sortExpression">  
                        <option value="Title">Title</option>  
                            <option value="Employee">CountryCode</option>  
                                <option value="Company">SortOrder</option>  
                                
                                    </select>  
                </div>  
  
                <br/> Search By Any:  
                <input type="text" ng-model="search.$" />  
                <br/>  
                <br/> 
    </div>
     
                
        <table class="table table-condensed table-hover">
            <tr>
            
                <th>Title</th>
                <th>CountryCode</th>
                <th>SortOrder</th>
               <th>Created</th>
               <th>Modified</th>
               


            </tr>
           <tr ng-repeat="customer in customers | orderBy:mySortFunction | filter:search">
                <td>{{customer.Title}}</td>
                <td>{{customer.CountryCode}}</td>
                <td>{{customer.SortOrder}}</td>
                 <td>{{customer.Created}}</td>
                  <td>{{customer.Modified}}</td>
                  

            </tr>
        </table>
    </div>
</div>
</body>

</html>



Angular JS + Rest API + Getting List Data in SharePoint 2013

This article explains how to get the data from a SharePoint List using Angular JavaScript and the REST API. I used the REST API to talk to SharePoint and get the data from the list. I am not going to discuss much about the REST services since many folks have already done great work on explaining REST API services.

In this script we just see that we have first created an Angular Controller with the name "spCustomerController". We have also injected $scope and $http service. The $http service will fetch the list data from the specific columns of the SharePoint list. $scope is a glue between a Controller and a View. It acts as execution context for Expressions. Angular expressions are code snippets that are usually placed in bindings such as {{ expression }}.



<%@ Register TagPrefix="WpNs0" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<meta name="WebPartPageExpansion" content="full" />
<meta name="ProgId" content="SharePoint.WebPartPage.Document" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Angular JS</title>
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<SharePoint:CssRegistration Name="default" runat="server"/>
<style>
table, td, th {
    border: 1px solid green;
}
 
th {
    background-color: green;
    color: white;
}
</style>
<script type="text/javascript" src="../SiteAssets/JS/Scripts/JQueryv1.10.3.js"></script>
<script type="text/javascript" src="../SiteAssets/JS/Scripts/angular.min.js"></script>

 
<script type="text/javascript">
     
    var myAngApp = angular.module('SharePointAngApp', []);
    myAngApp.controller('spCustomerController', function ($scope, $http) {
        $http({
            method: 'GET',
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getByTitle('Country')/items?$select=Title,CountryCode,SortOrder,Created,Modified ",
            headers: { "Accept": "application/json;odata=verbose" }
        }).success(function (data, status, headers, config) {
            $scope.customers = data.d.results;
        }).error(function (data, status, headers, config) {
       
        });
    });
     
 
</script>
 
<h1> Angular JS SharePoint 2013 REST API !!</h1>
</head>

<body>

<form id="form1" runat="server">
<ZoneTemplate></ZoneTemplate></form>


<div ng-app="SharePointAngApp" class="row">
    <div ng-controller="spCustomerController" class="span10">
        <table class="table table-condensed table-hover">
            <tr>
           
                <th>Title</th>
                <th>CountryCode</th>
                <th>SortOrder</th>
               <th>Created</th>
               <th>Modified</th>
             


            </tr>
            <tr ng-repeat="customer in customers">
                <td>{{customer.Title}}</td>
                <td>{{customer.CountryCode}}</td>
                <td>{{customer.SortOrder}}</td>
                 <td>{{customer.Created}}</td>
                  <td>{{customer.Modified}}</td>
                 

            </tr>
        </table>
    </div>
</div>
</body>

</html>