Search This Blog

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>


Friday, April 29, 2016

How to programmatically add delete modify item permissions in SharePoint 2013

Note: SPPrincipal can be either an SPUser or SPGroup Object


Breaking Inheritance
//specifies whether the item has unique security
//or inherits its role assignments from a parent object.
item.HasUniqueRoleAssignments

//Stops inheriting permissions from parent object
// if true, it will keep all existing users
// false, to remove all users
item.BreakRoleInheritance(true);

//Removes the local role assignments
//and reverts to role assignments from the parent object.
item.ResetRoleInheritance();



Adding Permissions to an item
//SPGroup group = web.Groups[0];
//SPUser user = web.Users[0];
//SPUser user2 = web.EnsureUser("mangaldas.mano");
//SPUser user3 = web.EnsureUser("Domain Users"); ;
//SPPrincipal[] principals = { group, user, user2, user3 };
public static void SetPermissions(this SPListItem item, IEnumerable principals, SPRoleType roleType)
{
 if (item != null)
 {

  foreach (SPPrincipal principal in principals)
  {
   SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
   SetPermissions(item, principal, roleDefinition);
  }
 }
}


public static void SetPermissions(this SPListItem item, SPUser user, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  SetPermissions(item, (SPPrincipal)user, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  SetPermissions(item, principal, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPUser user, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SetPermissions(item, (SPPrincipal)user, roleDefinition);
 }
}

public static void SetPermissions(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);

  roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
  item.RoleAssignments.Add(roleAssignment);
 }
}


Deleting all user Permissions from an item
public static void RemovePermissions(this SPListItem item, SPUser user)
{
 if (item != null)
 {
  RemovePermissions(item, user as SPPrincipal);
 }
}

public static void RemovePermissions(this SPListItem item, SPPrincipal principal)
{
 if (item != null)
 {
  item.RoleAssignments.Remove(principal);
  item.SystemUpdate();
 }
}


Removing specific roles from an item
public static void RemovePermissionsSpecificRole(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 if (item != null)
 {
  SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal);
  if (roleAssignment != null)
  {
   if (roleAssignment.RoleDefinitionBindings.Contains(roleDefinition))
   {
    roleAssignment.RoleDefinitionBindings.Remove(roleDefinition);
    roleAssignment.Update();
   }
  }
 }
}

public static void RemovePermissionsSpecificRole(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  RemovePermissionsSpecificRole(item, principal, roleDefinition);
 }
}


Updating or Modifying Permissions on an item
public static void ChangePermissions(this SPListItem item, SPPrincipal principal, SPRoleType roleType)
{
 if (item != null)
 {
  SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
  ChangePermissions(item, principal, roleDefinition);
 }
}

public static void ChangePermissions(this SPListItem item, SPPrincipal principal, SPRoleDefinition roleDefinition)
{
 SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principal);
 if (roleAssignment != null)
 {
  roleAssignment.RoleDefinitionBindings.RemoveAll();
  roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
  roleAssignment.Update();
 }
}



Create Groups Programmatically in SharePoint 2013

 The code below changes the built in associated groups by using the spWeb property bag directly, rather than the properties exposed by spWeb - e.g. spWeb.AssociatedGroups.Add(group), or spWeb.AssociatedOwnerGroup = group.

using Microsoft.SharePoint;
 
namespace DevHoleDemo
{
    public static class GroupsHelper
    {
        public enum AssociatedGroupTypeEnum { Owners, Members, Vistors };
 
        public static void AddGroups(SPWeb spWeb, bool copyUsersFromParent)
        {
            spWeb.BreakRoleInheritance(false);
            SPGroup owners = AddGroup(spWeb, AssociatedGroupTypeEnum.Owners, 
                             copyUsersFromParent);
            SPGroup members = AddGroup(spWeb, AssociatedGroupTypeEnum.Members, 
                             copyUsersFromParent);
            SPGroup vistors = AddGroup(spWeb, AssociatedGroupTypeEnum.Vistors, 
                             copyUsersFromParent);
            SPGroup myGroup = AddGroup(spWeb, "My Group", "An example group.", 
            null, null, null, false);
            SetAssociatedGroups(spWeb, new SPGroup[] { owners, members, vistors,
            myGroup });
        }
 
        public static void SetAssociatedGroups(SPWeb spWeb, SPGroup[] groups)
        {
            string formatString = "";
            object[] ids = new object[groups.Length];
            for (int i = 0; i < groups.Length; i++)
            {
                formatString += string.Format("{{{0}}};", i);
                ids[i] = groups[i].ID;
            }
            spWeb.Properties["vti_associategroups"] = string.Format(formatString.
            TrimEnd(new char[] 
           { ';' }), ids);
            spWeb.Properties.Update();
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, AssociatedGroupTypeEnum 
        associateGroupType, 
        bool copyUsersFromParent)
        {
            switch (associateGroupType)
            {
                case AssociatedGroupTypeEnum.Owners:
                    return AddGroup(spWeb, spWeb.Name + " Owners", "Use this group to 
                    give people full control permissions to the SharePoint site: {0}", 
                   "Full Control", "vti_associateownergroup", 
                    spWeb.ParentWeb.AssociatedOwnerGroup, copyUsersFromParent);

                case AssociatedGroupTypeEnum.Members:
                    return AddGroup(spWeb, spWeb.Name + " Members", "Use this group to 
                    give people contribute permissions to the SharePoint site: {0}", 
                    "Contribute", "vti_associatemembergroup", 
                    spWeb.ParentWeb.AssociatedMemberGroup, copyUsersFromParent);

                case AssociatedGroupTypeEnum.Vistors:
                    return AddGroup(spWeb, spWeb.Name + " Vistors", "Use this group 
                    to give people read 
                    permissions to the SharePoint site: {0}", "Read", 
                   "vti_associatevisitorgroup", 
                    spWeb.ParentWeb.AssociatedVisitorGroup, copyUsersFromParent);
                default:
                    return null;
            }
        }
 
        public static SPGroup AddGroup(SPWeb spWeb, string groupName, string 
        descriptionFormatString, string roleDefinitionName,string associatedGroupName,
        SPGroup parentAssociatedGroup, bool 
        copyUsersFromParent)
        {
            SPGroup owner = parentAssociatedGroup;
            if (associatedGroupName != "vti_associateownergroup")
            owner = spWeb.SiteGroups.GetByID(int.Parse(spWeb.Properties
                         ["vti_associateownergroup"]));
            spWeb.SiteGroups.Add(groupName, owner, null, 
                                 string.Format(descriptionFormatString, 
            spWeb.Name));
            SPGroup group = spWeb.SiteGroups[groupName];
            if (descriptionFormatString.IndexOf("{0}") != -1)
            {
                SPListItem item = spWeb.SiteUserInfoList.GetItemById(group.ID);
                item["Notes"] = string.Format(descriptionFormatString, 
                string.Format("<a href=\"{0}\">{1}</a>", spWeb.Url, spWeb.Name));
                item.Update();
            }
            if (roleDefinitionName != null)
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
                SPRoleDefinition roleDefinition = spWeb.RoleDefinitions
                [roleDefinitionName];
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                spWeb.RoleAssignments.Add(roleAssignment);
            }
            if (copyUsersFromParent && parentAssociatedGroup != null)
                foreach (SPUser user in parentAssociatedGroup.Users)
                    group.AddUser(user);
            if (associatedGroupName != null)
            {
                spWeb.Properties[associatedGroupName] = group.ID.ToString();
                spWeb.Properties.Update();
            }
            spWeb.Update();
            return group;
        }
    }
}

Wednesday, April 20, 2016

Event Receivers - SharePoint 2013

An event receiver has a set of base classes that can contains one or more methods known as event handlers that are executed automatically by SharePoint in response to events such as adding or deleting item to a list/library. You can use event handlers for the different operations on different lists, document libraries and content types.


Types of Event Receivers:


  1. Synchronous - Events are executed before the action is executed on the content database.

         Events ending with -ing are named as Synchronous Event Receivers
         Ex. Item Deleting,Item Adding.
    2.  A Synchronous - Events are executed after the action is executed on the content database.

         Events ending with -ed are named as Synchronous Event Receivers
         Ex. Item Deleted,Item Added.

Different Base Classes in Event Receivers:

     There are totally 5 base classes in SharePoint 2010,
  1. SPItemEventReceiver - Event at List item Level.
  2. SPListEventReceiver - Event at List Level.
  3. SPFeatureEventReceiver - Event activation and Deactivation at list level.
    1. FeatureInstalled: Right after feature is installed.
    2. FeatureActivated: Right after feature activation through “Site Settings” or otherwise.
    3. FeatureDeactivated: Right after feature deactivation through “Site Settings” or otherwise.
    4. FeatureUninstalled: Before feature is uninstalled.
  4. SPEmailEventReceiver :Event to send mail to list
  5. SPWebEventReceiver : Event at Web Site Level.(Site added,site deleted,etc..)
Disabling and Enabling the event Receiver

If we are modifying/updating the same List item using event receiver,then the event receiver is triggered
 again and again.So you have to prevent it from firing before you update changes to the list item. 
We can implement this functionality using EnableEventFiring attribute to true/false.

Example:
   public override void ItemAdded(SPItemEventProperties properties)
    {
        //will disable the event receiver
        EventFiringEnabled = false;
        
        //do some action on list like update List.Update()
 
        //will enable the event receiver
        EventFiringEnabled = true;
    }

Best practice is to set Disable EventFiring method right before any update action and Enable EventFiring
 method right after updating action has been completed.