Search This Blog

Friday, May 27, 2016

Sharepoint Client Object Model: sites, roles, lists, documents, AD users and permissions


Recently I had my very first encounter with Sharepoint, and I cannot say it was a pleasant meeting. I was doing a proof of concept for a customer to manipulate Sharepoint from code using the new Sharepoint 2010 Client Object Model. Not that this is a particular unpleasant job in itself and neither is the API particulary bad (although definitelyodd), but the MSDN documentation about the Client Object Model is far from self-explanatory, and lacks the – for me, at last –  most crucial part of educational material: simple how-to examples.
Most examples found elsewhere are either based on older API’s, incomplete and sometimes completely wrong. And you have to roam about half the internet to get pieces of code together. So I thought it would be a good idea to cobble together pieces from the POC into a comprehensive blog post with what I’ve learned, hoping to save other people the same quest.
Be aware that I learned this all just in the past few days so things are pretty crude at times. I am by no means a Sharepoint wizard - nor am I planning on becoming one :-).  The idea is just to show how it’s done. I think there are a lot of people out there who know how to do things better and more efficient than me: it just they don’t blog about it ;-)
This code was used to talk to a Sharepoint foundation on a domain controller outside the domain on which I actuallyran the code.
Things covered in this post
  • Create a site
  • Retrieve a site by title
  • Retrieve a role by Role type
  • Retrieve a Sharepoint principal by Active Directory user or group name
  • Retrieve a document library by name
  • Retrieve a document library template by name
  • Create a document library and set permissions
  • Create a folder in a document library
  • Upload a file to a document library
  • Download a file from a document library
  • List all folders or files in a document library
Setting the stage
It started out making a “Sharepointhelper” class. The basics of this thing is a follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;
using File = Microsoft.SharePoint.Client.File;

namespace TestSharepoint
{
  public class SharepointHelper
  {
    private ClientContext clientContext;
    private Web rootWeb;

    public SharepointHelper(string url, string username, string password)
    {
      clientContext = new ClientContext(url);
      var credentials = new NetworkCredential(username, password, "domain");
      clientContext.Credentials = credentials;
      rootWeb = clientContext.Web;
      clientContext.Load(rootWeb);
    }
  }
}
Creating the object should go like this:
var sh = new SharepointHelper("http://yourserver", "aUser", "hisPassword");
aUser must be a user with enough rights to perform sharepoint administration. I used the domain admin username and password and I assure you – that works ;-)
Create a site
public void CreateSite(string siteDescription, string siteTitle, string siteUrl)
{
  rootWeb = rootWeb.Webs.Add(new WebCreationInformation
    {
      Description = siteDescription,
      Title = siteTitle,
      Url = siteUrl,
      UseSamePermissionsAsParentSite = false
    });
  clientContext.ExecuteQuery();
}
Usage sample: 
sh.Create("My site description", "MySite", "mysiteurl");
Retrieve a site by title
public Web GetWebByTitle(string siteTitle)
{
  var query = clientContext.LoadQuery(
    rootWeb.Webs.Where(p => p.Title == siteTitle));
  clientContext.ExecuteQuery();
  return query.FirstOrDefault();
}
Usage sample: 
var w = sh.GetWebByTitle("MySite");
Retrieve role by Role type
private RoleDefinition GetRole(string siteTitle, RoleType rType)
{
  var web = GetWebByTitle(siteTitle);
  if (web != null)
  {
    var roleDefs = web.RoleDefinitions;
    var query = clientContext.LoadQuery(
        roleDefs.Where(p => p.RoleTypeKind == rType));
    clientContext.ExecuteQuery();
    return query.FirstOrDefault();
  }
  return null;
}
Usage sample: 
var r = sh.GetRole("MySite", RoleType.Contributor);
will get you the contributor role.Retrieve a Sharepoint principal by Active Directory user or group name
Now this one took me a very long time. For some reason there is a static Utility.SearchPrincipals method that gets you a PrincipalInfo object, but you can never get to get a Principal object that you can use for setting permissions. I spent a long time scratching my head how to get around this before I found there is another way:
public Principal GetPrincipal(string name)
{
  if (web != null)
  {
    try
    {
      var principal = web.EnsureUser(name);
      clientContext.Load(principal);
      clientContext.ExecuteQuery();
      if (principal != null)
      {
        return principal;
      }
    }
    catch (ServerException){}
  }
  return null;
}
Usage sample: 
var g = sh.GetPrincipal("MyUserGroup");
var u = sh.GetPrincipal("MyUser");
This will, as you can see, get you either a user group’s principal or a single user’s principal. Since I was looking for agroup’s principal it never occurred to me to try the “EnsureUser” method. If you don’t know what a Principal is – neither do I (at least not exactly) but I of think it as a descriptor of a user’s or group's credentials.
Retrieve a document library by name
public List GetDocumentLibrary(string siteTitle, string libraryName)
{
  var web = GetWebByTitle(siteTitle);
  if (web != null)
  {
    var query = clientContext.LoadQuery(
         web.Lists.Where(p => p.Title == libraryName));
    clientContext.ExecuteQuery();
    return query.FirstOrDefault();
  }
  return null;
}
Usage sample: 
var g = GetDocumentLibrary("MySite", "myDocumentLibrary");
Retrieve a document library template by name
public ListTemplate GetDocumentLibraryTemplate(Web web, string name)
{
  ListTemplateCollection ltc = web.ListTemplates;
  var listTemplates = clientContext.LoadQuery(
    ltc.Where(p => p.InternalName == name));
  clientContext.Load(ltc);
  clientContext.ExecuteQuery();
  return listTemplates.FirstOrDefault();
}
Usage sample: 
var t = sh.GetDocumentLibraryTemplate(web, "doclib");
This will get you the template for the document library type.Create a document library and set permissions
Now this was what I actually had to prove in the POC, and you can see this as it uses a lot of the previous samples:
public bool CreateDocumentLibrary(string siteTitle, string libraryName, 
                                  string libraryDescription, string userGroup)
{
  var web = GetWebByTitle(siteTitle);
  if (web != null)
  {
    // First load all the list
    var lists = web.Lists;
    clientContext.Load(lists);
    clientContext.ExecuteQuery();

    // Create new lib based upon the doclib template
    var newList = lists.Add(new ListCreationInformation
      {
        Title = libraryName,
        Description = libraryDescription,
        TemplateType = 
          GetDocumentLibraryTemplate(web, "doclib").ListTemplateTypeKind
      });
    clientContext.ExecuteQuery();

    // Override default permission inheritance
    newList.BreakRoleInheritance(true, false);
    // Get principal for usergroup and the contributor role
    var principal = GetPrincipal(userGroup);
    var role = GetRole(siteTitle, RoleType.Contributor);
    
    // Add the role to the collection.
    var collRdb = new RoleDefinitionBindingCollection(clientContext) {role};
    var collRoleAssign = newList.RoleAssignments;
    collRoleAssign.Add(principal, collRdb);

    clientContext.ExecuteQuery();
    
    return true;
  }
  return false;
}
Usage sample: 
var result = sh.CreateDocumentLibrary("MySite", "myDocumentLibrary",
                                      "A very nice library", "MyUserGroup");
Which will create a document library “myDocumentLibrary” in “MySite” with a contributor role for “MyUserGroup”. Like I said, it’s pretty crude still here and there, but you get the idea
Create a folder in a document library
public void CreateFolder( string siteTitle, string libraryName, string folder)
{
  var list = GetDocumentLibrary(siteTitle, libraryName);
  if (list != null)
  {
    var folders = list.RootFolder.Folders;
    clientContext.Load(folders);
    clientContext.ExecuteQuery();
    var newFolder = folders.Add(folder);
    clientContext.ExecuteQuery();
  }
}
I'll skip the usage sample here, as I suppose it's pretty self-explanatory now.Upload a file to a document library
public void UploadDocument( string siteTitle, string libraryName, string fileName )
{
  var web = GetWebByTitle(siteTitle);
  var fInfo = new FileInfo(fileName);
  var targetLocation = string.Format("{0}/{1}/{2}", web.ServerRelativeUrl, 
     libraryName, fInfo.Name);
  
  using (var fs = new FileStream(fileName, FileMode.Open))
  {
    File.SaveBinaryDirect(clientContext, targetLocation, fs, true);
  }
}
Usage sample: 
var result = sh.UploadDocument("MySite", "myDocumentLibrary",
                              @"c:\temp\sample.png");
This will upload the file c:\temp\sample.png as "sample.png" in the "myDocumentLibrary" library.Download a file from a document library
What goes up must come down, eh? This one is a bit odd, as it strips the directory name of the target file and tries to find the file in Sharepoint with it, but it works, so what:
public void DownloadDocument(string siteTitle, string libraryName, 
                             string fileName)
{
  var web = GetWebByTitle(siteTitle);
  var fInfo = new FileInfo(fileName);

  var source = string.Format("{0}/{1}/{2}", web.ServerRelativeUrl, 
                                            libraryName, fInfo.Name);
  var spFileInfo = File.OpenBinaryDirect(clientContext, source);
  using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
  {
    spFileInfo.Stream.CopyTo(fs);
  }
}
Usage sample: 
sh.DownloadDocument("MySite", "myDocumentLibrary",
                     @"c:\temp\sample.png");
will search for the file "sample.png" in "myDocumentLibrary" and try to download that to c:\tempListing files or folders in a document library
And finally:
public List<File> ListFiles(string siteTitle, string libraryName)
{
  var list = GetDocumentLibrary(siteTitle, libraryName);
  var files = list.RootFolder.Files;
  clientContext.Load(files);
  clientContext.ExecuteQuery();
  return files.ToList();
}

public List<Folder> ListFolders(string siteTitle, string libraryName)
{
  var list = GetDocumentLibrary(siteTitle, libraryName);
  var folders = list.RootFolder.Folders;
  clientContext.Load(folders);
  clientContext.ExecuteQuery();
  return folders.ToList();
}
and if you don’t mind, I’ll skip the usage samples here as well.

Save Update Delete Sorting ,Paging,Searching from SharePoint Rest API With Angular JS

Aspx Code :

<%-- _lcid="1033" _version="15.0.4420" _dal="1" --%>
<%-- _LocalBinding --%>
<%@ Page language="C#" MasterPageFile="~masterurl/default.master"    Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" meta:progid="SharePoint.WebPartPage.Document"  %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
<SharePoint:ListItemProperty Property="BaseName" maxlength="40" runat="server" __designer:Preview="MVcRam2" __designer:Values="&lt;P N=&#39;Property&#39; T=&#39;BaseName&#39; /&gt;&lt;P N=&#39;MaxLength&#39; T=&#39;40&#39; /&gt;&lt;P N=&#39;InDesign&#39; T=&#39;False&#39; /&gt;&lt;P N=&#39;ID&#39; ID=&#39;1&#39; T=&#39;ctl00&#39; /&gt;&lt;P N=&#39;Page&#39; ID=&#39;2&#39; /&gt;&lt;P N=&#39;TemplateControl&#39; R=&#39;2&#39; /&gt;&lt;P N=&#39;AppRelativeTemplateSourceDirectory&#39; R=&#39;-1&#39; /&gt;"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
<script src="../../SiteAssets/Scripts/angular.min.js"></script>
<script src="../../SiteAssets/Scripts/jquery-1.11.2.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
<script src="http://code.angularjs.org/1.4.8/angular-resource.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>

<script src="Js/UserTest.js" type="text/javascript"></script>
<meta name="GENERATOR" content="Microsoft SharePoint" />
<meta name="ProgId" content="SharePoint.WebPartPage.Document" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="CollaborationServer" content="SharePoint Team Web Site" />
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
<SharePoint:DelegateControl runat="server"
ControlId="SmallSearchInputBox" __designer:Preview="&lt;div class=&quot;ms-webpart-chrome ms-webpart-chrome-fullWidth &quot;
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
<SharePoint:ProjectProperty Property="Description" runat="server" __designer:Preview="" __designer:Values=""/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<style>
table, td, th {
    border: 1px solid red;
}

th {
    background-color: Gray;
    color: white;
}
</style>


  <div ng-app="SharePointAngApp" class="row">



    <div ng-controller="spCustomerController" >
     <div  >
              <br/> Search Employee:
                <input type="text" ng-model="search.$" style="width:400px"  ng-change="mysearch()"/>
               <!-- OR-- <input ng-model="query" style="width:250px" type="text"/> ->>
                <p>Number of Items: {{results.length}}</p>
     
     <!-- angular Js Code-->
       <br>
    </br>
   </div>
        <table >
            <tr>
                <th>
                 <a href="" ng-click="order('Title')">Title</a>
                </th>
                <th>
                 <a href="" ng-click="order('Employee')">Employee</a>
                </th>
                <th>
                 <a href="" ng-click="order('Company')">Company</a>
                </th>
                <th>
                 <a href="" ng-click="order('ID')">ID</a>
                </th>
                <th>Action
             
                </th>              
            </tr>
            <tr ng-repeat="customer in customers  |orderBy:predicate:reverse |filter:paginate|filter:search">
                <td>{{customer.Title}}</td>
                <td>{{customer.Employee}}</td>
                <td>{{customer.Company}}</td>
                <td>{{customer.ID}}</td>
                <td><input type="button" id="Idedit" value="Edit" ng-readonly='!($index == eEditable)' data-ng-click="getByDataID(customer.Id)"/>
                <input type="submit" id="Delete" value="Delete" data-ng-click="Delete(customer.Id)"/></td>
             </tr>
        </table>
       <pagination total-items="totalItems" ng-model="currentPage"
             max-size="3" boundary-links="true"
             items-per-page="numPerPage" class="pagination-sm">
       </pagination>
     <br> </br>
     
         <table style="margin-left:5px">
    <!--  <tr style="visibility:hidden">
            <td>Id:</td>
            <td>
                <input type="text" id="txtItemId"  data-ng-model="customer.ID" disabled="TRUE"/>
            </td>
        </tr>  -->
       <tr >
       <td>Title</td>
       <td><input type="text" id="txttitle"  data-ng-model="customer.Title" width="10px" />
       </td>
       </tr>
    <tr><td>
Employee</td>
<td>
<input type="text" id="txtemployee"  data-ng-model="customer.Employee" width="10px"/></td>
</tr>
<tr>
<td>Company</td>
 <td><input type="text" id="txtcompany"  data-ng-model="customer.Company" width="10px" />
        <input type="text" id="txtItemId"  data-ng-model="customer.ID" style="visibility:hidden"/>
        </td>
      </tr>
    <tr><td>
      <input type="submit" id="btnsave" value="Save" data-ng-click="Save()"/>
    </td>
<td>
<input type="submit" value="Update" id="btnupdateval" data-ng-click="Update()"/>

       <input type="reset" value="Clear" data-ng-click="ClearFields()"/>
</td></tr>
</table>
    </div>
 

</div>
 <br>
 </br>
   
</asp:Content>


JS Code

// ANGular Js Are Used 
  var myAngApp = angular.module('SharePointAngApp', ['ui.bootstrap', 'ngResource']);  
      myAngApp.controller('spCustomerController', function ($scope, $http) { 
       // var url= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('UserTest')/items?$select=Title,Employee,Company,ID"; 
       //alert("Ram");
        $( "#btnupdateval" ).prop( "disabled", true );
         $( "#pageTitle" ).css( "display",'none');
        
         $scope.eEditable= -1;
        $http({  
            method: 'GET',  
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('UserTest')/items?$select=Title,Employee,Company,ID",  
            headers: { "Accept": "application/json;odata=verbose" }  
        }).success(function (data, status, headers, config) {  
            $scope.customers = data.d.results;
            $scope.totalItems = $scope.customers.length;  
        $scope.numPerPage = 5;
        $scope.currentPage = 1; 
        $scope.paginate = function (value) {  
          var begin, end, index;  
            begin = ($scope.currentPage - 1) * $scope.numPerPage;  
            end = begin + $scope.numPerPage;  
            index = $scope.customers.indexOf(value);  
            return (begin <= index && index < end);  
       };  
          
           // var a= $scope.customers;
        }).error(function (data, status, headers, config) {  
         
        }); 
       
     
    //$scope.customers = [];
     $scope.getByDataID = function (customer) { 
     var customerId= customer;
      $.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/getitembyid("+customerId+")/?$select=Title,Employee,Company,ID",
              type: "GET",
              headers: 
              {
                    "Accept": "application/json;odata=verbose",
                    "content-type": "application/json; odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            
               },
              success: function(data){
                      $( "#btnupdateval" ).prop( "disabled", false );
                      $scope.customer=data.d;
                         $('#txtItemId').val(data.d.Id);
                $('#txttitle').val(data.d.Title);
                $('#txtcompany').val(data.d.Employee);
                $('#txtemployee').val(data.d.Company);
                  $( "#btnsave" ).prop( "disabled", true );
                                 
                            },
              error: function(err){
                                alert("Error while fetching list item: " + JSON.stringify(err));
                            }

          });
       };
      $scope.Save = function () { 
             $.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items",
              type: "POST",
              data: JSON.stringify
               ({
                    '__metadata': {'type': 'SP.Data.UserTestListItem' },
       "Title": $scope.customer.Title,
       "Employee":$scope.customer.Employee,
       "Company":$scope.customer.Company               }),
              headers: {
                    "Accept": "application/json;odata=verbose",
                     "content-type": "application/json; odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            },
              success: function(data){
                              alert("Item added successfully!");
                            },
              error: function(err){
                                alert("Error while adding item: " + JSON.stringify(err));
                            }
          });

      };
      
      $scope.Update = function () {
           $.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items("+$scope.customer.ID+")",
              type: "POST",
              data: JSON.stringify({
                       
                       '__metadata': {'type': 'SP.Data.UserTestListItem' },
                          "Title": $scope.customer.Title,
             "Employee":$scope.customer.Employee,
             "Company":$scope.customer.Company
                          }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item updated successfully!");
                            },
              error: function(err){
                                alert("Error while updating item: " + JSON.stringify(err));
                            }

          });

      };
      $scope.Delete= function (customer) { 
       var customerId=customer;
       $.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items("+customerId+")",
              type: "POST",
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "DELETE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item deleted successfully!");
                            },
              error: function(err){
                                alert("Error while deleting item: " + JSON.stringify(err));
                            }

          });
    }; 
    $scope.ClearFields= function ()
        {
       $( "#btnsave" ).prop( "disabled", false );
        $scope.customer="";
   };
  // Sorting For 
   $scope.predicate = 'name';
   $scope.reverse = true;
   $scope.order = function (predicate) {
               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
               $scope.predicate = predicate;
           };  

  $scope.mysearch = function() {
            alert('Ram');
          };  
/// 
    }); 
    
  
// End Of Angular Js





Pagination with AngularJS and your API

// main.js (function() { 'use strict'; angular.module('app') .controller('MainCtrl', ['$scope', '$http', function($scope, $http) { $scope.main = { page: 1, take: 15 }; $scope.loadPage = function() { // You could use Restangular here with a route resource. $http.get('api/v2/users?page=' + main.page + '&take=' + main.take).success(function(data){ // users from your api $scope.main.users = data.users; // number of pages of users $socpe.main.pages = data.pages; }); }; $scope.nextPage = function() { if ($scope.main.page < $scope.main.pages) { $scope.main.page++; $scope.loadPage(); } }; $scope.previousPage = function() { if ($scope.main.page > 1) { $scope.main.page--; $scope.loadPage(); } }; }]); }); // main.tpl.html <ul> <li ng-repeat='user in users'>{{ user.email }}</li> </ul> <button ng-click='previousPage()'>Previous<button> <button ng-click='nextPage()'>Next<button>

Get All Of Specific Column in TD and TR Using Rest Api

</style>
<script type="text/javascript">

$(document).ready(function(){
   GetListItems();
});
function GetListItems()  
    var strHtml ="";
    var Increment=0;
    var tbl=$("#GetItems");
    var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('NGOPortals')/items"; 
    $.ajax 
    ({ 
        url: url, 
        type: "GET", 
        headers: 
        { 
            "Accept": "application/json;odata=verbose", 
            "Content-Type": "application/json;odata=verbose",
           
        }, 
        success: function(data)  
        { 
                strHtml +='<tr>';
            $.each(data.d.results, function(key, item) 
            {
                                if(Increment%6 == 0)
                                {
                                                                                strHtml +='<td>';
                                                                                                               
                                }
                                 strHtml +="<div><a href="+item.URL.Url.toString()+" target=\"_blank\">"+item.URL.Description.toString()+"</a></div>";
                                 Increment =Increment +1;
                                 
                if(Increment%6 == 0)
                                {
                                                                                strHtml +='</td>';                           
                                }

             
             
             
            });
             strHtml +='</tr>';
            $("#GetItems>tbody").html(strHtml);
             //var rowCount = $('#GetItems tr').length;
            // alert(rowCount); 
            $("#GetItems").show();
            
       
        }, 
        error: function(data)  
        { 
            //alert("Failed to get list items."); 
        } 
    }); 
  
}
</script>

Saturday, May 21, 2016

Angular Js 1.0 With Rest API In SharePoint 2013 and Angular JS 2.0


Include HTML in Single Page Application

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="IncudeHTMl.aspx.cs" Inherits="AjaxApp.Angular_Js.IncudeHTMl" %>

<!DOCTYPE html>

<html>
   <head>
      <title>Angular JS Includes</title>
   
       <script src="../Script/angular.min.js"></script>
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
       
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
       
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
     
   </head>
   <body>
     
      <h2>AngularJS Sample Application</h2>
     
      <div ng-app = "mainApp" ng-controller="studentController">
         
          <Div style="background-color:azure">
         <div ng-include = "'/Angular%20Js/main.html'"></div>
         <div ng-include = "'/Angular%20Js/Students.html'"></div>

          </Div>
       
          <br />
          <br />
<div style="background-color:aqua">
 <div ng-controller="studentController1" >
         
         <div ng-include = "'/Angular%20Js/main1.html'"></div>
         <div ng-include = "'/Angular%20Js/Students1.html'"></div>
      </div>

</div>
       
     <div style="background-color:gray">
  <div ng-controller = "shapeController">
            <p>{{message}} <br/> {{type}} </p>
         </div>
         
          <div ng-controller = "circleController">
            <p>{{message}} <br/> {{type}} </p>
         </div>
       
         <div ng-controller = "squareController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

     </div>    
         
 </div>
     
      <script>
          var mainApp = angular.module("mainApp", []);
          mainApp.controller('studentController', function ($scope) {
              $scope.student = {
                  firstName: "Mahesh",
                  lastName: "Parashar",
                  fees: 500,

                  subjects: [
                     { name: 'Physics', marks: 70 },
                     { name: 'Chemistry', marks: 80 },
                     { name: 'Math', marks: 65 },
                     { name: 'English', marks: 75 },
                     { name: 'Hindi', marks: 67 }
                  ],

                  fullName: function () {
                      var studentObject;
                      studentObject = $scope.student;
                      return studentObject.firstName + " " + studentObject.lastName;
                  }
              };
          });
         //var mainApp1 = angular.module("mainApp1", []);
          mainApp.controller('studentController1', function ($scope) {
              $scope.Ram = {
                  firstName: "Ram",
                  lastName: "Vinay",
                  fees: 6666,

                  subjectsRam: [
                     { name: 'Physics', marks: 70 },
                     { name: 'Chemistry', marks: 80 },
                     { name: 'Math', marks: 65 },
                     { name: 'English', marks: 75 },
                     { name: 'Hindi', marks: 67 }
                  ],

                  fullName: function () {
                      var studentObject;
                      studentObject = $scope.Ram;
                      return studentObject.firstName + " " + studentObject.lastName;
                  }
              };
          });

          mainApp.controller("shapeController", function ($scope) {
              $scope.message = "In shape controller";
              $scope.type = "Shape";
          });

          mainApp.controller("circleController", function ($scope) {
              $scope.message = "In circle controller";
          });

          mainApp.controller("squareController", function ($scope) {
              $scope.message = "In square controller";
              $scope.type = "Square";
          });
      </script>
     
   </body>
</html>


Angular JS Click header link to sort, input into filter text to filter























<html>
 <head>
   <title> Angular JS table sort and filter example </title>
 
   
     <script src="../Script/angular.min.js"></script>

   <script>
       var app = angular.module('MyForm', []);
       app.controller('myCtrl', function ($scope) {
           $scope.predicate = 'name';
           $scope.reverse = true;
           $scope.order = function (predicate) {
               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
               $scope.predicate = predicate;
           };
       });
   </script>
   <style>
     .odd {
       background-color: antiquewhite;
       color: #008b8b;
     }
     td th {
       height: 30px;
       min-width: 100px;
     }
     thead {
       background-color: darkcyan;
       color: white;
       height: 30px;
     }
   </style>
 </head>
 <body ng-app="MyForm" ng-controller="myCtrl">
   <h3>List students</h3>
   <div ng-init=" students = [
            {name: 'Kevin', age: 25, gender: 'boy'},
            {name: 'John', age: 30, gender: 'girl'},
            {name: 'Laura', age: 28, gender: 'girl'},
            {name: 'Joy', age: 15, gender: 'girl'},
            {name: 'Mary', age: 28, gender: 'girl'},
            {name: 'Peter', age: 95, gender: 'boy'},
            {name: 'Bob', age: 50, gender: 'boy'},
            {name: 'Erika', age: 27, gender: 'girl'},
            {name: 'Patrick', age: 40, gender: 'boy'},
            {name: 'Tery', age: 60, gender: 'girl'}
           ] ">
     <pre>Click header link to sort, input into filter text to filter</pre>
     <hr />
     <table class="table table-striped">
       <thead>
         <tr>
         
           <th>
             <a href="" ng-click="order('name')">Name</a>
           </th>
           <th><a href="" ng-click="order('age')"> Age</a> </th>
           <th><a href="" ng-click="order('gender')">Gender</a> </th>
         </tr>
       </thead>
       <tbody>
         <tr>
         
           <td> <input type="text" ng-model="search.name" /></td>
           <td> <input type="text" ng-model="search.age" /> </td>
           <td><input type="text" ng-model="search.gender" /> </td>
         </tr>
         <tr ng-repeat="user in students | orderBy:predicate:reverse | filter:search" ng-class-odd="'odd'">
         
           <td>{{ user.name}}</td>
           <td>{{ user.age}}</td>
           <td>{{ user.gender}}</td>
         </tr>
       </tbody>
     </table>
   </div>
 </body>
 </html>

Validation With Angular JS

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Aj.aspx.cs" Inherits="AjaxApp.Angular_Js.Aj" %>

<!DOCTYPE html>

<html>
   <head>
      <title>Angular JS Forms</title>
       <script src="../Script/angular.min.js"></script>
     
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
       
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
       
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
     
   </head>
   <body>
     
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "studentController">
       
         <form name = "studentForm" novalidate>
            <table border = "0">
               <tr>
                  <td>Enter first name:</td>
                  <td><input name = "firstname" type = "text" ng-model = "firstName" required>
                     <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
                        <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>Enter last name: </td>
                  <td><input name = "lastname"  type = "text" ng-model = "lastName" required>
                     <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
                        <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
                     <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
                        <span ng-show = "studentForm.email.$error.required">Email is required.</span>
                        <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>
                     <button ng-click = "reset()">Reset</button>
                  </td>
                  <td>
                     <button ng-disabled = "studentForm.firstname.$dirty &&
                        studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
                        studentForm.lastname.$invalid || studentForm.email.$dirty &&
                        studentForm.email.$invalid" ng-click="submit()">Submit</button>
                  </td>
               </tr>

            </table>
         </form>
      </div>
     
      <script>
          var mainApp = angular.module("mainApp", []);
          mainApp.controller('studentController', function ($scope) {
              $scope.reset = function () {
                  $scope.firstName = "Mahesh";
                  $scope.lastName = "Parashar";
                  $scope.email = "MaheshParashartutorialspoint.com";
              }
              $scope.reset();
          });
      </script>
   </body>
</html>