Remove Attachments on SharePoint List Item using Angular

Ahamed Fazil Buhari
 
Senior Developer
December 4, 2017
 
Rate this article
 
Views
3807

Hello everyone,

In this article we will see how to delete attachments in SharePoint List Item using Angular. In my previous article we have seen, Get All Attachments From SharePoint List Item Using AngularJS and How To Handle Multiple File Selection And Validation On Input File Type Using AngularJS. Once we get all the files in the variable scope.attachedFile. We cannot upload attachment when we are updating some field in the item. To achieve this, we need to update item in separate and upload or remove file in separate. We can make use of promise $q in angular to upload file in list item once the item has been successfully created or updated.

Here I’ve created separate service for updating list item and uploading attachment in SharePoint list item. The service name is List_Context and Utilities service to get supporting components for CRUD header,

Utilities.js

 (function () {
     'use strict';
     var serviceId = 'Utilities';
 
     var Utilities = function () {
 
         var service = this;
         service.spHostUrl = _spPageContextInfo.siteAbsoluteUrl + _spPageContextInfo.webServerRelativeUrl;
 
         return {
             getRequestHeader: getRequestHeader,
             updateRequestHeader: updateRequestHeader,
             deleteRequestHeader: deleteRequestHeader
         };
 
         function getRequestHeader() {
             var getHeader = {
                 'headers': {
                     'accept': 'application/json;odata=verbose'
                 }
             };
             return getHeader;
         }
 
         function updateRequestHeader() {
             var updateHeader = {
                 'headers': {
                     "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                     'content-type': 'application/json;odata=verbose',
                     'accept': 'application/json;odata=verbose',
                     "IF-MATCH": "*",
                     "X-HTTP-Method": "MERGE"
                 }
             };
             return updateHeader;
         }
 
         function deleteRequestHeader() {
             var deleteHeader = {
                 'headers': {
                     "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                     'content-type': 'application/json;odata=verbose',
                     "IF-MATCH": "*"
                 }
             };
             return deleteHeader;
         }
     }
     var module = angular.module("Mainapp");
     module.factory(serviceId, Utilities);
 }());
 

List_Context.js

 (function () {
     'use strict';
     var serviceId = 'List_Context';
 
     var List_Context = function ($http, $q, Utilities) {
 
         return {
             getListData: getListData,
             updateListData: updateListData,
             checkFileExistsAndRemove: checkFileExistsAndRemove,
             uploadFileSP: uploadFileSP,
             getFileBuffer: getFileBuffer,
             deleteFile: deleteFile
         };
 
         function getListData(urlValue) {
             var deferred = $q.defer();
             $http.get(urlValue, Utilities.getRequestHeader())
                         .then(function (response) {
                             deferred.resolve(response.data.d);
                         }, function (error) {
                             deferred.reject(error);
                         });
             return deferred.promise;
         };
 
         function updateListData(listId, itemId, itemData, listName) {
             var deferred = $q.defer();
             var updateURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetById('" + listId + "')/Items" + '(' + itemId + ')';
             var entityFullName = getEntityTypeFullName(listName);
             var item = $.extend({
                 '__metadata': {
                     'type': entityFullName
                 }
             }, itemData);
             var jsonData = JSON.stringify(item);
 
             $http.post(updateURL, jsonData, Utilities.updateRequestHeader())
                         .then(function (response) {
                             deferred.resolve(response.data.d);
                         }, function (error) {
                             deferred.reject(error);
                         });
             return deferred.promise;
         };
 
         function checkFileExistsAndRemove(fileURL) {
             var deferred = $q.defer();
             var fullFileURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getFileByServerRelativeUrl('" + fileURL + "')";
             $http.get(fullFileURL, Utilities.getRequestHeader())
                         .then(function (response) {
                             deleteFile(fullFileURL)
                             .then(function (response) {
                                 deferred.resolve(response);
                             });
                         }, function (error) {
                             console.log('File does not exist');
                             deferred.reject(error);
                         });
             return deferred.promise;
         }
 
         function uploadFileSP(listName, itemID, bufferVal, fileName) {
             var urlValue = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + itemID + ")/AttachmentFiles/add(FileName='" + fileName + "')";
 
             $.ajax({
                 url: urlValue,
                 type: "POST",
                 data: bufferVal,
                 async: false,
                 processData: false,
                 headers: {
                     "accept": "application/json;odata=verbose",
                     "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                     "Content-Type": undefined
                 },
                 success: fileSuccess,
                 error: fileError
             });
             function fileSuccess(data) {
                 console.log('File Added Successfully.');
             }
             function fileError(error) {
                 console.log(error.statusText + "nn" + error.responseText);
             }
         }
 
         function getFileBuffer(file) {
             var deferred = $.Deferred();
             var reader = new FileReader();
             reader.onloadend = function (e) {
                 deferred.resolve(e.target.result);
             }
             reader.onerror = function (e) {
                 deferred.reject(e.target.error);
             }
             reader.readAsArrayBuffer(file);
             return deferred.promise();
         }
 
         function deleteFile(fileURL) {
             var deferred = $q.defer();
             $http.delete(fileURL, Utilities.deleteRequestHeader())
                          .then(function (response) {
                              console.log('Deleted the attachment.');
                              deferred.resolve(response);
                          }, function (error) {
                              deferred.reject(error);
                          });
             return deferred.promise;
         }
     };
 
     //Supporting function 
     function getEntityTypeFullName(listName) {
         return "SP.Data." + listName.replace(' ', '_x0020_') + "ListItem";
     }
 
     var module = angular.module("Mainapp");
     module.factory(serviceId, ['$http', '$q', 'Utilities', List_Context])
 }());
 

Main.js

 (function () {
     'use strict';
 
     var controllerId = 'Mycontroller';
     var app = angular.module("Myapp", []);
 
     var Mycontroller = function ($scope, $q, List_Context, Utilities) {
         function SaveData() {
             var updatingVals = {};
             updatingVals['Title'] = "TEST Title";
             var filesAdd = {};
             //Please refer previous article to know how to get attachment value in attachedFile scope variable
             //https://www.sharepointpals.com/post/Get-all-attachments-from-SharePoint-List-Item-using-AngularJS
             filesAdd = $scope.attachedFile;
             var listID = "BF6BCA2E5-12B5-452F-8EA6-B6789AF4CDEB";
             var listItemID = 10;
             var listName = "MyList";
             SP_WaitScreen();
             var promises = [];
             List_Context.updateListData(listID, listItemID, updatingVals, listName)
                     .then(function (value) {
                         //Please refer previous article to see how to get removeFile values - 
                         //https://www.sharepointpals.com/post/How-to-handle-multiple-file-selection-and-validation-on-input-file-type-using-AngularJS
                         angular.forEach($scope.removeFile, function (filePath, key) {
                             promises.push(List_Context.checkFileExistsAndRemove(filePath));
                         });
                     }, function (reason) {
                         SP_WaitScreen_Close();
                         window.open(window.parent.location.reload(true), "_parent", "");
                     });
         }        
 
         //OOTB Wait modal dailog
         function SP_WaitScreen() {
             SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
                 window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Working on it...', '');");
             });
         }
         function SP_WaitScreen_Close() {
             if (window.frameElement != null) {
                 if (window.parent.waitDialog != null) {
                     window.parent.waitDialog.close();
                 }
             }
         }
     }
     app.controller(controllerId, Mycontroller);
     app.config(['$compileProvider', function ($compileProvider) {
         $compileProvider.aHrefSanitizationWhitelist(/^s*(https?|file|blob):/);
     }]);
 });
 
 <script type="text/javascript" src="../../../../SiteAssets/js/Scripts/jquery.min.js"></script>
 <script type="text/javascript" src="../../../../SiteAssets/js/Scripts/jquery.SPServices-2014.02.min.js"></script>
 <script type="text/javascript" src="../../../../SiteAssets/js/Scripts/angular.min.js"></script>
 <script type="text/javascript" src="../../../../SiteAssets/js/sppals/Controllers/Main.js"></script>
 
 <!--Services-->
 <script type="text/javascript" src="../../../../SiteAssets/js/sppals/Services/List_Context.js"></script>
 <script type="text/javascript" src="../../../../SiteAssets/js/sppals/Services/Utilities.js"></script>
 <div id="divNew" ng-app="Myapp">
     <ng-form id="EditForm" name="EditForm">
         <div ng-controller="Mycontroller">         
                                 <div>Attach Memo:</div>
                                 <div>
                                     <span id="attach">
                                         <input id="uploadFileID" type="file" ng-file-model="files" />
                                                                                 
                                         <p class="attach-Text" ng-repeat="file in attachedFile">
                                             <a target="_blank" href="{{file.ServerRelativeUrl}}" ng-href="{{file.ServerRelativeUrl}}">{{file.FileName}}</a>                                             
                                             <a title='Click to Remove' ng-click="removeFile(attachedFile, $index)">
                                                 <img class="deleteIcon" src='../../../../SiteAssets/img/Delete_icon.png' />
                                             </a>
                                         </p>                                        
                                     </span>                               
                                 </div>
             <input type="button" id="btnSave" ng-click="SaveButtonClick()" title="Click to Save" value="Save" />
         </div>
     </ng-form>    
 </div>
 

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

How to Enable Enterprise Metadata and Keywords Settings in SharePoint Office 365 Lists Programmatically using CSOM C#

Sathish Nadarajan
 
Solution Architect
January 5, 2017
 
Rate this article
 
Views
5786

In this article, let us see how to enable Enterprise Metadata and Keywords Settings in SharePoint Office 365 Lists Programmatically using CSOM C#

To do that Manually, we need to go to the List settings, click on the below highlighted link as shown in the figure.

 

image

 

Select the Check Box.

 

image

 

The New column called “Enterprise Keywords” will be added to the list.

To do this through program, we need to do the reverse way. If we Add the column “Enterprise Keywords”, then the “Enterprise Keywords” settings will be enabled automatically.

Hence, the code to add the field to the list is as follows.

 namespace Sathish.Demo
 {
     using Microsoft.SharePoint.Client;
     using System;
 
     class Program
     {
         static void Main(string[] args)
         {
             EnableEnterpriseKeywords();
         }
 
         public static void EnableEnterpriseKeywords()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
             
             string siteUrl = "https://*******.sharepoint.com/sites/CommunitySite";
             string userName = "Sathish@******";
             string password = "******************";
 
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 try
                 {
                     Web web = clientContext.Web;
                     
                     clientContext.Load(web);
                     clientContext.Load(web.Lists);
                     clientContext.ExecuteQuery();
 
                     List list = web.Lists.GetByTitle("Documents");
 
                     if (!list.FieldExistsByName("Enterprise Keywords"))
                     {
                         var field = clientContext.Site.RootWeb.Fields.GetByInternalNameOrTitle("Enterprise Keywords");
                         list.Fields.Add(field);
                         clientContext.Load(list);
                     }
 
                      
 
                     clientContext.ExecuteQuery();
 
                 }
                 catch (Exception ex)
                 {
                     System.Console.ForegroundColor = ConsoleColor.Red;
                     System.Console.WriteLine("Exception Occured : " + ex.Message);
                     System.IO.File.AppendAllText("C:\Temp\Exception.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
                 }
             }
 
             System.Console.WriteLine("Completed....");
             System.Console.WriteLine("Press Any Key to Exit ....");
             System.Console.ReadLine();
         }
     }
 }
 

The output will be like this.

 

image

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Create Custom Service in AngularJS for CRUD Operations on SharePoint List

Ahamed Fazil Buhari
 
Senior Developer
October 11, 2016
 
Rate this article
 
Views
11767

In this article, we’ll look into the advantages and how to implement Custom Services in Angular. Before going further, please refer my previous articles on $http service in Angular. Here, I’ve implemented CRUD operations on SharePoint List using Angular HTTP service and having that in my own Custom service.

‘Why would we need to write a custom service?’ the answer is simple, Services are useful in various scenarios,

· Packaging Reusable Logic – we can have some logic (an algorithm or some piece of code that we need in several different controllers) in a container and we can use that in different places, it would avoid duplicating of code.

· Shared Data – If we want to share data between the controllers on different views, a service will be a great place to store data. Because Angular only instantiate a single instance of each service in an application.

· Complexity Is Reduced – Sometimes a controller would be too difficult to manage if we have so much code in it. So in that situation we can simplify the code and separate the responsibilities and give some burden to the service.

· Clean Maintainable Code – Organizing your code into services leads to cleaner, better defined components which means we have an application with more maintainable code.

In the following example, we will have SharePoint List Item CRUD operation in an Angular Custom Service named as, MyCustomService.js

 (function () { //IIFE 
 
     //RequestHeader for get,post,update,delete
     var requestHeader = {
         getHeader: {
             'headers': {
                 'accept': 'application/json;odata=verbose'
             }
         },
         postHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 'accept': 'application/json;odata=verbose'
             }
         },
         deleteHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 "IF-MATCH": "*"
             }
         },
         updateHeader: {
             'headers': {
                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                 'content-type': 'application/json;odata=verbose',
                 'accept': 'application/json;odata=verbose',
                 "IF-MATCH": "*",
                 "X-HTTP-Method": "MERGE"
             }
         }
     };
 
     //A service can have dependency on another service – Here we’ve used $http service
     var CRUD_SP = function ($http) {
 	 //Defining Function with parameter, 
         //same number of parameter we use when we invoke this function	
         var getListData = function (urlValue) {
             return $http.get(urlValue, requestHeader.getHeader)
 						.then(function (response) {
 						    return response.data.d.results;
 						});
         };
 
         var setListData = function (urlValue, data) {
             return $http.post(urlValue, data, requestHeader.postHeader)
 						.then(function (response) {
 						    return 'Created from Custom Service...';
 						});
         };
 
         var deleteListData = function (urlValue) {
             return $http.delete(urlValue, requestHeader.deleteHeader)
 						.then(function (response) {
 						    return 'Deleted from Custom Service...';
 						});
         };
 
         var updateListData = function (urlValue, data) {
             return $http.post(urlValue, data, requestHeader.updateHeader)
 						.then(function (response) {
 						    return 'Updated from Custom Service...';
 						});
         };
 
         //When someone invokes this CRUD_SP function
         //then it'll return an Object that is of CRUD_SP
         return {
             //Pick up the Public API
             //name: function_name to call
             getListData: getListData,
             setListData: setListData,
             updateListData: updateListData,
             deleteListData: deleteListData
         };
     };
 
     //Creating the reference to "myapp" which we defined in MyAngular.js and 
     //No 2nd parameter, bcz I'm not trying to create a Module
     //rest of the code goes above this module.
     var module = angular.module("myapp");
 
     //Registering our service, so that Angular will use this
     //There are various ways to Register the service
     //This is simple and straightforward way,
     //Make use of method called 'factory('Name of the service', function name that returs an object)'
     module.factory('CRUD_SP', CRUD_SP);
 
 }());
 

The above js file will be used as a Custom Service. The code written in our main JS file has been reduced and we can use this custom service in other places in our application. The main JS file code has been given below,

 (function () { //IIFE 
     //angular.module(,) in this second parameter is an array, 
     //earlier we had empty bcz we don't have any explicit dependencies,
     //
     var app = angular.module("myapp", []);
 
     //Add our new service in the controller parameter
     var MyController = function ($scope, CRUD_SP) {
 
         var urlVal = {
             url: _spPageContextInfo.webAbsoluteUrl + "/_api" + "/web/lists/GetByTitle('Phone')/Items"
         };
         //Function to call for Successful GET
         var onSuccessGet = function (data) {
             $scope.people = data;
             console.log(data);
         };
         //Function to call for Successful post,update,delete
         var onSuccess = function (data) {
             $scope.phonename = '';
             $scope.pplusing = '';
             $scope.newphonename = '';
             $scope.newpplusing = '';
             $scope.itemID = '';
             $scope.error = '';
             $scope.getItem();
             console.log(data);
         };
 
         var onError = function (reason) {
             $scope.error = "something went wrong";
         };
 
         $scope.getItem = function () {
             var geturlVal = urlVal.url + "/?$select=*";
             //using CRUD_SP custom service and calling function defined inside it
             CRUD_SP.getListData(geturlVal)
 				   .then(onSuccessGet, onError);
         }
 
         $scope.saveItem = function () {
             var createURL = urlVal.url;
             var data = {
                 //To Get __metadata->'type' value for the list, go to
                 //https://<site>/_api/web/lists/getbytitle('<List Name>')?$select=ListItemEntityTypeFullName
                 //from the xml, get the value inside <d:ListItemEntityTypeFullName> element
                 __metadata: { 'type': 'SP.Data.TestingListItem' },
                 Title: $scope.phonename,
                 People_x0020_using: $scope.pplusing
             };
 
             CRUD_SP.setListData(createURL, data)
                    .then(onSuccess, onError);
         }
 
         $scope.deleteItem = function () {
             var deleteURL = urlVal.url + '(' + $scope.itemID + ')';
             CRUD_SP.deleteListData(deleteURL)
 	    		.then(onSuccess, onError);
         }
 
         $scope.updateItem = function () {
             var updateURL = urlVal.url + '(' + $scope.itemID + ')';
             var updatedata = {
                 __metadata: { 'type': 'SP.Data.TestingListItem' },
                 Title: $scope.newphonename,
                 People_x0020_using: $scope.newpplusing
             };
 
             CRUD_SP.updateListData(updateURL, updatedata)
 	    		.then(onSuccess, onError);
         }
     };
 
     app.controller("MyController", MyController);
 }());
 
 

In the aspx page, we’re having buttons and text fields to update, delete and insert list items and HTML table to show the data.

 <script src="../SiteAssets/JS/Form JS/jquery-1.10.2.js"></script>
 <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
 
 <script src="../SiteAssets/JS/Form JS/MyAngular.js"></script>
 <!-- Make sure your service is defined after Main JS i.e MyAngular.js,
 bcz module has been defind in MyAngular.js!-->
 <script src="../SiteAssets/JS/Form JS/MyCustomService.js"></script>
 
 
 <div id="appDiv" ng-app="myapp">
     <div id="controllerDiv" ng-controller="MyController">
         <label ng-show="error" class="ng-hide">Error : {{error}}</label>
         <h2>Insert into List</h2>
         Phone Name : <input type="text" ng-model="phonename" />
         No. of People Usng : <input type="number" ng-model="pplusing" />
         <button type="button" ng-click="saveItem()">Save</button>
 
         <h2>Delete or Update List Item</h2>
         Enter Item ID : <input type="text" ng-model="itemID" />
         New Phone Name : <input type="text" ng-model="newphonename" />
         New No. of People Usng : <input type="number" ng-model="newpplusing" />
         <button type="button" ng-click="deleteItem()">Delete</button>
         <button type="button" ng-click="updateItem()">Update</button>
 
         <button type="button" ng-click="getItem()">Get Items</button>
         <div ng-show="people" class="ng-hide">
             <table id="userDetails" border="1px solid">
                 <thead>
                     <tr>
                         <th>Item ID</th>
                         <th>Phone Title</th>
                         <th>No. of ppl using</th>
                     </tr>
                 </thead>
                 <tbody>
                     <tr ng-repeat="ppl in people">
                         <td>{{ppl.ID}}</td>
                         <td>{{ppl.Title}}</td>
                         <td>{{ppl.People_x0020_using | number}}</td>
                     </tr>
                 </tbody>
             </table>
         </div>
     </div>
 </div>
 
 

clip_image002

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

How to Use Angular HTTP Services in SharePoint List

Ahamed Fazil Buhari
 
Senior Developer
October 10, 2016
 
Rate this article
 
Views
12761

Hello everyone, in this article we will look into the approach on how to Insert, Update and Delete SharePoint List Items using simple HTTP Service provided by AngularJS, please refer my previous article – Basics of AngularJS in SharePoint.

Let me just say few words about Services in AngularJS. A Service in Angular would performs a specific job, like providing the ability to communicate over HTTP or providing a timer or to log our actions etc. Already we’ve used one of the services -> $http and its method get() in my another article, “How to Get all Items in SharePoint List and Display it in Custom HTML table with Sorting using AngularJS”. Below you can find complete list of methods available for $http service.

· $http.get

· $http.post

· $http.put

· $http.delete

· $http.head

· $http.jsonp

· $http.patch

Where this Services fit in Angular framework,

clip_image001

Controllers are responsible for setup the Model and the View consumes the Model. Directives are an intermediary for Model and View.

Directives keep the Model and View separate, but allowing them to communicate indirectly and move data back and forth. For example, if any input value changes, then ng-model directive will push the value back into Model and vice versa.

And one of the many benefits of putting logic into that Service is that the logic will be easy to use anywhere else in the application. We never use a Service directly from a View, because View is about presentation and directives only. Mostly we use post, get and delete methods for CRUD operation on SharePoint list items. Below you can find the syntax for $http service methods

$http.post(‘/URL/’, data, requestHeader);

$http.get(url, [config-optional]);

$http.delete(url, [config-optional]);

Here, Config is nothing but a requestHeader which we use in REST API. In the below example you can find AngularJS $http service to Create, Update and Delete SharePoint List Item. To read the SharePoint List Item, I’ve explained that in my another article named as ‘’How to Get all Items from SharePoint List and Display it in Custom HTML table with Sorting using AngularJS”.

 

 <script src="../SiteAssets/JS/Form JS/jquery-1.10.2.js"></script>
 <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
 
 <script src="../SiteAssets/JS/Form JS/MyAngular.js"></script>
 
 <div id="appDiv" ng-app="myapp">
 	<div id="controllerDiv" ng-controller="MyController">
 		<label ng-show="error" class="ng-hide">Error : {{error}}</label>
 		
 		<h2>Insert into List</h2>		
 		<br /><br />
 		Phone Name : <input type="text" ng-model="phonename" />
 		<br /><br />
 		No. of People Usng : <input type="number" ng-model="pplusing" />
 		<br/><br />
 		<button type="button" ng-click="saveItem()">Save</button>
 		<br/><br/><br/>
 		
 		<h2>Delete or Update List Item</h2>		
 		<br /><br />
 		Enter Item ID :  <input type="text" ng-model="itemID" />
 		<br /><br />
 		New Phone Name : <input type="text" ng-model="newphonename" />
 		<br /><br />
 		New No. of People Usng : <input type="number" ng-model="newpplusing" />
 		<br/><br />		
 		<button type="button" ng-click="deleteItem()">Delete</button>
 		<button type="button" ng-click="updateItem()">Update</button>
     </div>
 </div>
 

In MyAngular.js file the following Angular script should be added,

 

 (function () { //IIFE 
     var app = angular.module("myapp", []);
     
     var MyController = function ($scope, $http) {               			
 		
 		var urlVal = {
 			url: _spPageContextInfo.webAbsoluteUrl + "/_api" + "/web/lists/GetByTitle('Phone')/Items"
 		};
 		//created json obj to keep track of requestHeader		
 		var requestHeader = {
 				getHeader: {
 					'headers': {
 						'accept': 'application/json;odata=verbose'
 					}
 				},
 				postHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            'accept': 'application/json;odata=verbose'
 					}
 				},				
 				deleteHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            "IF-MATCH":"*"
 					}
 				},
 				updateHeader: {
 					'headers': {
 						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
 			            'content-type': 'application/json;odata=verbose',
 			            'accept': 'application/json;odata=verbose',
 			            "IF-MATCH":"*",
 			            "X-HTTP-Method": "MERGE"
 			        }
 				},				
 			};
 			
 		var onSuccess = function(response) {
 				//refreshing all the text box to empty value
 				$scope.phonename = '';
 				$scope.pplusing	= '';
 				$scope.newphonename = '';
 				$scope.newpplusing	= '';
 				$scope.itemID	= '';
 				$scope.error = '';
 				console.log('working');	
 			};
 			
 		var onError = function(reason) {
 				$scope.error = "Could not fetch, something went wrong" + reason;
 			};
 		
 		//Save button click
 		$scope.saveItem = function() {		
 			var createURL = urlVal.url;
 			var data = {
 	   	        //To Get __metadata->'type' value for the list, go to
 //https://<site>/_api/web/lists/getbytitle('<List Name>')?$select=ListItemEntityTypeFullName
 	//from the xml, get the value inside <d:ListItemEntityTypeFullName> element
 				    __metadata: { 'type': 'SP.Data.TestingListItem' },
 				    Title: $scope.phonename,
 				    People_x0020_using: $scope.pplusing		    			    
 				};
 				         				
    	//UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);
 	//this function is used when the RequestDigest value won’t update nor exist  
 	           
 	       $http.post(createURL, data, requestHeader.postHeader)
 	        	.then(onSuccess, onError);  
 	    }   
 	    
         //Delete Button Click
 	    $scope.deleteItem = function() {
 			var deleteURL = urlVal.url + '(' + $scope.itemID + ')';	    		    	
 	    	$http.delete(deleteURL, requestHeader.deleteHeader)
 	    		.then(onSuccess, onError);
 	    }
 	    
         //Update Button Click
 	    $scope.updateItem = function() {
 	    	var updateURL = urlVal.url + '(' + $scope.itemID + ')';	 
 	    	var updatedata = {	   	        
 				    __metadata: { 'type': 'SP.Data.TestingListItem' },
 				    Title: $scope.newphonename,
 				    People_x0020_using: $scope.newpplusing			    			    
 				};
    	
 	    	$http.post(updateURL, updatedata, requestHeader.updateHeader)
 	    		.then(onSuccess, onError);
 	    }
 
     };
 
     app.controller("MyController", MyController);
 
 } ());
 
 

clip_image003

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

How to Get All Items from SharePoint List and Display it in Custom HTML table with Sorting using AngularJS

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Views
18257

Hello everyone, in this article we will look into the approach on how to get all the SharePoint List Items and showing that in a Custom page using HTML table. Here we’re using two important things from AngularJS, one is $scope object and another one is $http service. To know more about $scope object and other basic stuffs in AngularJS, please refer my previous article – Basics of AngularJS in SharePoint

About $http service: HTTP is a service that Angular provides, and it is an object with methods we can use to make HTTP calls. The methods are named after the HTTP methods, so the methods on this object are GET, POST, PUT, and DELETE.

 var MainController = function ($scope, $http) {
     $scope.user = $http.get('url/users/547226'); //wrong way, bcz its async so we won’t get the result immediately.
 };
 
 

Making use of Promise

As the name implies, the promise object is an object that promises to give us some result in the future, and that output might be the data that we need, or the result might be an error if the server was unreachable or unavailable or some issue. We need to call a then method on my promise and pass the then method a function that will be called in the future.

 var MainController = function ($scope, $http) {
     var promise = $http.get('/users/547226'); 
 	promise.then(function(response){
 		$scope.user = response.data;
 });
 };
 OR
 var MainController = function ($scope, $http) {
     var onSuccess = function(response) {
 	$scope.user = response.data;
     };
     var onError = function(reason) {
 	$scope.error = “Something went wrong”;
     };
 
     $http.get('/users/547226')
 	.then(onSuccess, onError); 
 };
 

.then – This method is called when the function is ready. Let’s explain the $http service with an example. Consider that we have a SharePoint list as shown below,

clip_image002

Here, I’ve created custom page and added this below HTML element in it.

 <div id="appDiv" ng-app="myapp">
     <div id="controllerDiv" ng-controller="MyController">
         {{error}}
 	Order By:
         <select ng-model="customOrderBy">
             <option value="Title">Asc - Title</option>
             <option value="-Title">Desc - Title</option>
             <option value="People_x0020_using">Asc - Ppl using</option>
             <option value="-People_x0020_using">Desc - Ppl using</option>
         </select>
         <br />
         <table id="userDetails" border="1px solid">
             <thead>
                 <tr>
                     <th>Phone Title</th>
                     <th>No. of ppl using</th>
                 </tr>
             </thead>
             <tbody>
                 <tr ng-repeat="ppl in people | orderBy:customOrderBy">
                     <td>{{ppl.Title}}</td>
                     <td>{{ppl.People_x0020_using | number}}</td>
                 </tr>
             </tbody>
         </table>
     </div>
 </div>
 

In my previous article I’ve explained about some very common directives like ng-app, ng-controller, ng-model in AngularJS. Here we’ve another useful directives ng-repeat and filter.

ng-repeat: ng-repeat="ppl in people" , ng-repeat is a lot like foreach loop in C#.

filters: In addition to directives, Angular also has the concept of filters. A filter is something that we invoke and pipe data through, by using the symbol | and then the name of the filter (number, currency, lowercase, uppercase etc.)

Basic format: expression | filterName:parameter

Name 
currency{{amount | currency:”USD$”}}
date{{startDate | date:’short’}}
filterppl in people | filter:Title
json{{ ppl | json }}
limitToppl in people | limitTo:10
lowercase, uppercase{{ ppl.name || uppercase }}
number{{ count | number }}
orderByppl in people | filter: searchTerm| orderBy: ‘Title’

Added the below script in my JS file,

 (function () { //IIFE 
 
     //Creating a Module
     var app = angular.module("myapp", []);
 
     var MyController = function ($scope, $http) {
 
         var json_listdata = {};
 
         var onSuccess = function (response) {
             //this result will be in json format, so we are getting the 'value' from the 'response.data'
             var json_values = response.data.value;
      //we assign it simply like shown below
 	     $scope.people = json_values;
             /*or we can iterate through all the items and assign it to our own jsom obj
             $.each(json_values, function (key, val) {
                 var jsonObj_Values = {};
                 jsonObj_Values["Title"] = val.Title;
                 jsonObj_Values["People Using"] = val.People_x0020_using;
 
                 json_listdata[val.ID] = jsonObj_Values;
             });
             //assigning the value into angular $scope element 
             $scope.people = json_listdata;
      */
         };
 
         var onError = function (reason) {
             $scope.error = "Could not fetch, something went wrong";
         };
 
         function getSPListItems() {
             var getURLVal = _spPageContextInfo.webAbsoluteUrl + "/_api" + "/web/lists/getbytitle('Phone')/Items?$select=*";
             //getURLVal, this only tells from which list and what items under what condition it should be fetched
             //$http.get
             $http.get(getURLVal)
 	          .then(onSuccess, onError);
         }
 
         getSPListItems();
 
     };
 
     //Registering the controller in the module
     app.controller("MyController", MyController);
 
 }());
 

And the output will be shown as below,

clip_image004

Based upon the Order By: dropdown value, the ordering in the table will differ. I hope, you got some idea about $http service and ng-repeat from this article.

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

How to Get the List of WSPs (Solutions) Installed in a SharePoint Farm using PowerShell

Sathish Nadarajan
 
Solution Architect
May 16, 2016
 
Rate this article
 
Views
12473

As Part of an analysis, I wanted the List of WSPs installed in my SharePoint farm. To get that, I was about to write a small function in PowerShell Script. The function is as follows.

 #############  Get All The Solutions in the Farm and their deployed WebApplications ############ 
 
 function GetSolution()
 {
     $script:Progress = "1,Entered"
     Write-Host "Entered into GetSolution Method" -ForegroundColor Yellow 
     Add-Content "$ProgressFile" "Entered into GetSolution Method"
     
     # Assign the CSV and XML Output File Paths
     $Solution_XML_Path = $scriptBase + "Reports-$LogTimeAvailableSolutions.xml"
     
     # Create the XML File Tags
     $xmlWriter = New-Object System.XMl.XmlTextWriter($Solution_XML_Path,$Null)
     $xmlWriter.Formatting = 'Indented'
     $xmlWriter.Indentation = 1
     $XmlWriter.IndentChar = "`t"
     $xmlWriter.WriteStartDocument()
     $xmlWriter.WriteComment('Solutions List')
     $xmlWriter.WriteStartElement('Solutions')
     $xmlWriter.WriteEndElement()
     $xmlWriter.WriteEndDocument()
     $xmlWriter.Flush()
     $xmlWriter.Close()
  
     
     # Get All the Solutions
     Add-Content "$ProgressFile" "Gathering All the Solutions from the Farm"
     
     $SolutionCollection = $farm.Solutions
     
     Add-Content "$ProgressFile" "Gathered All the Solutions from the Farm"
     
     if($SolutionCollection.Count -gt 0)
     {
         # Iterate through all the Solutions
         foreach($Solution in $SolutionCollection)
         {
             $tempContent = "Collecting the Information about the Solution : " + $Solution.DisplayName
             Add-Content "$ProgressFile" $tempContent
             
             # Get the deployed web applications
             $SPDeployedWebApps = $Solution.DeployedWebApplications
             
             # Create the Initial Solution Node
             $xmlDoc = [System.Xml.XmlDocument](Get-Content $Solution_XML_Path);
             $solutionNode = $xmlDoc.CreateElement("Solution")
             $xmlDoc.SelectSingleNode("//Solutions").AppendChild($solutionNode)
             $solutionNode.SetAttribute("Name", $Solution.DisplayName)
             
             Add-Content "$ProgressFile" "Iterate through the Installed Web Applications"
             # Iterate through all the Deployed Web Applications
             foreach($WebApplication in $SPDeployedWebApps)
             {
                 # write the output on XML File
                 
                 $webAppNameNode = $solutionNode.AppendChild($xmlDoc.CreateElement("WebApplication"));
                 $webAppNameNode.SetAttribute("Name", $WebApplication.DisplayName)
                 
                 $webAppURLNode = $webAppNameNode.AppendChild($xmlDoc.CreateElement("URL"));
                 $webAppURLTextNode = $webAppURLNode.AppendChild($xmlDoc.CreateTextNode($WebApplication.Url));
                 
                 $webAppDeploymentStateNode = $webAppNameNode.AppendChild($xmlDoc.CreateElement("Deployed"));
                 $webAppDeploymentStateTextNode = $webAppDeploymentStateNode.AppendChild($xmlDoc.CreateTextNode($Solution.DeploymentState));
                 
                 $xmlDoc.Save($Solution_XML_Path) 
             }
         }
      }
      
      Write-Host "Completed GetSolution Method" -ForegroundColor Green 
      Add-Content "$ProgressFile" "Completed GetSolution Method"
      $script:Progress = "1:Success"
      
      Write-Host "Please Find the Output XML file in the Path :" $Solution_XML_Path  -ForegroundColor Green 
 }
 
 ########### End of Method #################
 

Happy Coding,

Sathish Nadarajan.

Category : PowerShell, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Create a WebAPI to Add/Edit/Delete the data from a SharePoint List

Tarun Kumar Chatterjee
 
Net – Technology Specialist
March 29, 2016
 
Rate this article
 
Views
22424

Let’s first create a SharePoint list will have the following columns

clip_image001

In the list Title, Modified, Created, Created By & Modified By are the defaults, remaining site columns we have created only.

Now we will be creating few termsets that will be used by MMSData site column

Go to SiteSettings — > Term Store Management

Right Click on the Managed Metadata Service and create a new group named as “Test”, set the Group Managers & Contributors properly.

Right Click on the “Test” and Create New Term Set named as “TestTermSet”

Right click on the TestTermSet and Create Term named as “Term1”, “Term2” & “Term3”.

clip_image003

So, we are ready with the SharePoint list creation, will add some more data on the list

clip_image004

Now we will be creating an Asp.Net Web Application project named as “EmployeeWebAPI”

Select WebAPI & OK.

We will be fetching the data by using CSOM so, adding the references Mocrosoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime & Microsoft.SharePoint.Client.Taxonomy

To install System.Web.MVC in to our project need to execute the command

PM>Install-Package Microsoft.AspNet.Mvc -Version 5.0.0

Create a Model class named as “EmployeeModel.cs”, below is the code:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 
 namespace EmployeeWebAPITest.Models
 {
     public class EmployeeModel
     {
         public int ID { get; set; }
         public DateTime? DateCreated { get; set; }
         public DateTime DOB { get; set; }
         public string EmployeeAddress { get; set; }
         public string EmployeeName { get; set; }
         public string Title { get; set; }
         public string UserName { get; set; }
         public string Manager { get; set; }
         public string MMSData { get; set; }
         public string MMSName { get; set; }
         public string MMSGUid { get; set; }
 
     }
 }
 

Create a Model class to fetch Term data named as “MMSLookup.cs”, below is the code:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 
 namespace EmployeeWebAPITest.Models
 {
     public class MMSLookup
     {
         public string ID { get; set; }
         public string Name { get; set; }
     }
 }
 

Create another class within the Model folder named as “JsonpResult”, below is the code:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Web;
 using System.Web.Http.Results;
 using System.Web.Mvc;
 using System.Web.Script.Serialization;
 
 namespace EmployeeWebAPITest.Models
 {
     public class JsonpResult : JsonResult
     {
          public string CallbackFunction { get; set; }
         public Encoding ContentEncoding { get; set; }
         public string ContentType { get; set; }
         public object Data { get; set; }
 
         public JsonpResult(object data) : this(data, null) { }
         public JsonpResult(object data, string callbackFunction)
         {
             Data = data;
             CallbackFunction = callbackFunction;
         }
 
 
         public override void ExecuteResult(ControllerContext context)
         {
             if (context == null) throw new ArgumentNullException("context");
 
             HttpResponseBase response = context.HttpContext.Response;
 
             response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/x-javascript" : ContentType;
 
             if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
 
             if (Data != null)
             {
                 HttpRequestBase request = context.HttpContext.Request;
 
                 var callback = CallbackFunction ?? request.Params["callback"] ?? "callback";
                 var serializer = new JavaScriptSerializer();
                 response.Write(callback.ToString() + "(" + serializer.Serialize(Data).ToString() + ")");
 
             }
         }
     }
 }
 

For JavaScriptSerializer class you need to include System.Web.Extensions

Create another class named as “JsonpMediaTypeFormatter” within the Model folder, below is the code:

 using Newtonsoft.Json.Converters;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Net.Http.Formatting;
 using System.Net.Http.Headers;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web;
 using System.Web.Http;
 using System.Web.Script.Serialization;
 
 namespace EmployeeWebAPITest.Models
 {
     /// <summary>
     /// Handles JsonP requests when requests are fired with text/javascript
     /// </summary>
     public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
     {
         private string callbackQueryParameter;
 
         public JsonpMediaTypeFormatter()
         {
             SupportedMediaTypes.Add(DefaultMediaType);
             SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
 
             MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", DefaultMediaType));
         }
 
         public string CallbackQueryParameter
         {
             get { return callbackQueryParameter ?? "callback"; }
             set { callbackQueryParameter = value; }
         }
 
         public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
         {
             string callback;
 
             if (IsJsonpRequest(out callback))
             {
                 return Task.Factory.StartNew(() =>
                 {
                     var writer = new StreamWriter(stream);
                     writer.Write(callback + "(");
                     writer.Flush();
 
                     base.WriteToStreamAsync(type, value, stream, content, transportContext).Wait();
 
                     writer.Write(")");
                     writer.Flush();
                 });
             }
             else
             {
                 return base.WriteToStreamAsync(type, value, stream, content, transportContext);
             }
         }
 
 
         private bool IsJsonpRequest(out string callback)
         {
             callback = null;
 
             if (HttpContext.Current.Request.HttpMethod != "GET")
                 return false;
 
             callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];
 
             return !string.IsNullOrEmpty(callback);
         }
     }
 }
 
 

In Global.asax.cs within Application_Start() method add the below piece of code :

 GlobalConfiguration.Configure(WebApiConfig.Register);
 GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
 

Now create an employee controller named as “EmployeeController”

 using EmployeeWebAPITest.Models;
 using Microsoft.SharePoint.Client;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
 using System.Web.Http;
 using Newtonsoft.Json;
 using System.Web.Http.Cors;
 
 namespace EmployeeWebAPITest.Controllers
 {
     public class EmployeeController : ApiController
     {
         public HttpResponseMessage Options()
         {
             return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
         }
 
         [HttpGet]
         public JsonpResult GetEmployee(string filterSpan)
         {
             try
             {
                 using (ClientContext clientContext = new ClientContext("Site Collection URL"))
                 {
                     //The default network credential is nothing but the AppPool Account
                     clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
                     List<EmployeeModel> activities = null;
                     DataMangager objDataMangager = new DataMangager();
                     activities = objDataMangager.GetEmployeetDataFromHost(clientContext, filterSpan);
                     return new JsonpResult(activities.OrderBy(a => a.DateCreated).Reverse());
                 }
             }
             catch (Exception ex)
             {
                 return null;
             }
 
         }
         [HttpGet]
         public string GetMMSdata()
         {
 
             List<MMSLookup> terms = new List<MMSLookup>();
             try
             {
                 using (ClientContext clientContext = new ClientContext("Site Collection URL"))
                 {
                     //The default network credential is nothing but the AppPool Account
                     clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
                     DataMangager objDataMangager = new DataMangager();
                     terms = objDataMangager.GetTerms("TestTermSet", clientContext);
                 }
 
                 if (terms == null || terms.Count == 0) { throw new Exception("No terms fetched."); }
                 return JsonConvert.SerializeObject(terms);
             }
             catch (Exception ex)
             {
                 throw new Exception("Error fetching Terms." + ex.Message);
             }
         }
         public JsonpResult PostEmployee(List<EmployeeModel> lstClientActivity)
         {
             try
             {
                 List<Models.EmployeeModel> activities = null;
                 using (ClientContext clientContext = new ClientContext("Site Collection URL"))
                 {
                     //The default network credential is nothing but the AppPool Account
                     clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
                     DataMangager objDataMangager = new DataMangager();
                     activities = objDataMangager.AddEmployeeDataToHostBatch(clientContext, lstClientActivity, string.Empty);
                 }
                 return new JsonpResult(activities);
             }
             catch (Exception ex)
             {
                 throw new Exception("Error in create." + ex.Message);
             }
         }
 
         public JsonpResult PutEmployee(List<EmployeeModel> lstClientActivity)
         {
 
             var entities = new List<Models.EmployeeModel>();
             List<Models.EmployeeModel> activities = null;
             try
             {
                 using (ClientContext clientContext = new ClientContext("Site Collection URL"))
                 {
                     //The default network credential is nothing but the AppPool Account
                     clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
                     DataMangager objDataMangager = new DataMangager();
                     activities = objDataMangager.EditEmployeeDataOnHostBatch(clientContext, lstClientActivity, string.Empty);
                 }
                 return new JsonpResult(activities);
             }
             catch (Exception ex)
             {
                 throw new Exception("Error in edit." + ex.Message);
             }
         }
     }
 }
 

EmployeeController.cs is referring to DataManager class, here is the code snippet of DataManager class.

 using EmployeeWebAPITest.Models;
 using Microsoft.SharePoint.Client;
 using Microsoft.SharePoint.Client.Taxonomy;
 using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Globalization;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Web;
 using System.Xml;
 
 
 namespace EmployeeWebAPITest
 {
     public class DataMangager
     {        
         public  List<EmployeeModel> EditEmployeeDataOnHostBatch(ClientContext CSOMcontext, List<Models.EmployeeModel> input, string empname)
         {
             
 
             List<EmployeeModel> lstEmployeeModel = new List<EmployeeModel>();
             EmployeeModel objEmployeeModel = new EmployeeModel();
             if (input.Count < 1)
             {
                 throw new Exception("No records has been updated.");
             }
             Dictionary<string, string> columnNames = new Dictionary<string, string>();
             List list = null;
             string EmployeeDataListName = "Employee";
             
 
             try
             {
                 
                 list = CSOMcontext.Web.Lists.GetByTitle(EmployeeDataListName);
                 CSOMcontext.Load(list);
                 CSOMcontext.ExecuteQuery();
 
                 BuildColumnNameLookup(CSOMcontext, columnNames, list);
 
                 foreach (var item in input)
                 {
                     objEmployeeModel = new EmployeeModel();
                     ListItem oListItem;
                     oListItem = list.GetItemById(item.ID);
                     CSOMcontext.ExecuteQuery();
 
                     objEmployeeModel.ID = item.ID;
 
                     if (item.Manager != null)
                     {
                         User userTest = CSOMcontext.Web.EnsureUser(item.Manager);
                         CSOMcontext.Load(userTest);
                         CSOMcontext.ExecuteQuery();                        
                         objEmployeeModel.Manager = item.Manager;
                         oListItem[columnNames[Constants.Names.ManagerColumnName]] = userTest.Id.ToString() + ";#" + userTest.LoginName.ToString();
                         
                     }
 
                     if (item.Title != null)
                     {
                         oListItem[columnNames[Constants.Names.TitleColumnName]] = item.Title;
                         objEmployeeModel.Title = item.Title;
                     }
 
                     if (item.EmployeeName != null)
                     {
                         oListItem[columnNames[Constants.Names.EmployeeNameColumnName]] = item.EmployeeName;
                         objEmployeeModel.EmployeeName = item.EmployeeName;
                     }
 
                     if (item.EmployeeAddress != null)
                     {
                         oListItem[columnNames[Constants.Names.employeeaddressColumnName]] = item.EmployeeAddress;
                         objEmployeeModel.EmployeeAddress = item.EmployeeAddress;
                     }
                     if (item.DOB != null)
                     {
                         oListItem[columnNames[Constants.Names.dobColumnName]] = item.DOB;
                         objEmployeeModel.DOB = item.DOB;
                     }
                     
                     if (item.MMSData != null)
                     {
                         oListItem[columnNames[Constants.Names.MMSColumnName]] = string.Format("-1;#{1}|{0}", item.MMSGUid.Split((new string[] { "##" }), StringSplitOptions.None)[1], item.MMSName);
                         objEmployeeModel.MMSData = item.MMSData;
                         objEmployeeModel.MMSName = item.MMSName;
                         objEmployeeModel.MMSGUid = item.MMSGUid.Split((new string[] { "##" }), StringSplitOptions.None)[1];
                     }
 
                     oListItem.Update();
                     CSOMcontext.ExecuteQuery();
                     if (item.MMSData != null)
                     {
                         objEmployeeModel.MMSGUid = item.MMSGUid;
                     }
                     objEmployeeModel.UserName = item.UserName;
                     objEmployeeModel.DateCreated = item.DateCreated;
                     lstEmployeeModel.Add(objEmployeeModel);
                 }
 
 
             }
             catch (Exception ex)
             {
                 throw new Exception("Failed to update record." + ex.Message);
             }
             return lstEmployeeModel;
         }       
         public  List<EmployeeModel> AddEmployeeDataToHostBatch(ClientContext CSOMcontext, List<Models.EmployeeModel> input, string empname)
         {
             string EmployeeDataListName = "Employee";
             
             Dictionary<string, string> columnNames = new Dictionary<string, string>();
             List list = null;
             List<EmployeeModel> lstEmployeeModel = new List<EmployeeModel>();
             EmployeeModel objEmployeeModel = new EmployeeModel();
             try
             {
                 list = CSOMcontext.Web.Lists.GetByTitle(EmployeeDataListName);
                 CSOMcontext.Load(list);
                 CSOMcontext.ExecuteQuery();
 
                 BuildColumnNameLookup(CSOMcontext, columnNames, list);
                 ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
 
                 foreach (var item in input)
                 {
                     objEmployeeModel = new EmployeeModel();
                     ListItem oListItem;
                     oListItem = list.AddItem(itemCreateInfo);
                     User userTest = CSOMcontext.Web.EnsureUser(item.Manager);
                     CSOMcontext.Load(userTest);
                     CSOMcontext.ExecuteQuery();
                                         
                     oListItem[columnNames[Constants.Names.ManagerColumnName]] =  userTest.Id.ToString() + ";#" + userTest.LoginName.ToString();
                     objEmployeeModel.Manager = item.Manager;
                     oListItem[columnNames[Constants.Names.TitleColumnName]] = item.Title;
                     objEmployeeModel.Title = item.Title;
                     oListItem[columnNames[Constants.Names.EmployeeNameColumnName]] = item.EmployeeName;
                     objEmployeeModel.EmployeeName = item.EmployeeName;
                     oListItem[columnNames[Constants.Names.employeeaddressColumnName]] = item.EmployeeAddress;
                     objEmployeeModel.EmployeeAddress = item.EmployeeAddress;
                     oListItem[columnNames[Constants.Names.dobColumnName]] = item.DOB;
                     objEmployeeModel.DOB = item.DOB;
                    
                     oListItem[columnNames[Constants.Names.MMSColumnName]] = string.Format("-1;#{1}|{0}", item.MMSGUid.Split((new string[] { "##" }), StringSplitOptions.None)[1], empname);
                     objEmployeeModel.MMSData = item.MMSData;
                     objEmployeeModel.MMSName = item.MMSName;
                     
                     objEmployeeModel.MMSGUid = item.MMSGUid.Split((new string[] { "##" }), StringSplitOptions.None)[1];
                     oListItem.Update();
                     CSOMcontext.ExecuteQuery();
                     objEmployeeModel.MMSGUid = item.MMSGUid;
                     objEmployeeModel.DateCreated = DateTime.Now;
                     //objEmployeeModel.UserName = item.UserName;
                     lstEmployeeModel.Add(objEmployeeModel);
                 }
             }
             catch (Exception ex)
             {
                 throw new Exception("Failed to add new record." + ex.Message);
             }
             return lstEmployeeModel;
         }                
         public List<EmployeeModel> GetEmployeetDataFromHost(ClientContext CSOMcontext, string filterSpan)
         {
             string EmployeeDataListName = "Employee";
 
             //Name MMSCountry Activity Status Created Created By Modified Modified By
             Dictionary<string, string> columnNames = new Dictionary<string, string>();
 
             List<EmployeeModel> results = new List<EmployeeModel>();
             List list = null;
             Web web = null;
             try
             {
                 web = CSOMcontext.Web;
                 ListCollection lists = web.Lists;
                 CSOMcontext.Load(lists);
                 CSOMcontext.ExecuteQuery();
             }
             catch (Exception ex)
             {
                 throw new Exception("Unable to access host web at " + CSOMcontext.Url + "." + ex.Message);
             }
             try
             {
                 list = web.Lists.GetByTitle(EmployeeDataListName);
                 CSOMcontext.Load(list);
                 CSOMcontext.ExecuteQuery();
             }
             catch (Exception ex)
             {
                 throw new Exception("List " + EmployeeDataListName + " not found." + ex.Message);
             }
 
             BuildColumnNameLookup(CSOMcontext, columnNames, list);
 
             string fromDateFx = DateTime.Now.AddHours(-2).ToString("yyyy-MM-ddTHH:mm:ssZ");
             string toDateFx = DateTime.Now.AddDays(1).ToString("yyyy-MM-ddTHH:mm:ssZ");
 
             if (list != null && list.ItemCount > 0)
             {
                 CamlQuery camlQuery = new Microsoft.SharePoint.Client.CamlQuery();
                 if (filterSpan == "today")
                 {
                     camlQuery = CreateCamlDateQuery(fromDateFx, toDateFx);
                 }
 
                 ListItemCollection allItems = list.GetItems(camlQuery);
                 CSOMcontext.Load(allItems, items => items.Take(500));
                 CSOMcontext.ExecuteQuery();
 
                 foreach (ListItem item in allItems)
                 {
                     EmployeeModel emp = new EmployeeModel
                     {
                         ID = item.Id,
                         Title = "unknown",
                         EmployeeAddress = "unknown",
                         DOB = DateTime.MinValue,
                         EmployeeName = "unknown",
                         Manager = "unknown",
                         MMSData = "unknown",
                         DateCreated = DateTime.Now
 
                     };
                     try
                     {
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.dobColumnName]))
                         {
                             emp.DOB = Convert.ToDateTime(Convert.ToDateTime(item[columnNames[Constants.Names.dobColumnName]]).ToShortDateString());
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.createdColumnName]))
                         {
                             emp.DateCreated = Convert.ToDateTime(Convert.ToDateTime(item[columnNames[Constants.Names.createdColumnName]]).ToShortDateString());
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.employeeaddressColumnName]))
                         {
                             emp.EmployeeAddress = item[columnNames[Constants.Names.employeeaddressColumnName]].ToString();
                             emp.EmployeeAddress =  emp.EmployeeAddress.Substring(emp.EmployeeAddress.IndexOf("">") + 2, (emp.EmployeeAddress.IndexOf("</div>") - 2 - emp.EmployeeAddress.IndexOf("">")));
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.EmployeeNameColumnName]))
                         {
                             emp.EmployeeName = item[columnNames[Constants.Names.EmployeeNameColumnName]].ToString();
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.TitleColumnName]))
                         {
                             emp.Title = item[columnNames[Constants.Names.TitleColumnName]].ToString();
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.ManagerColumnName]))
                         {
                             emp.Manager = ((FieldUserValue)item[columnNames[Constants.Names.ManagerColumnName]]).LookupValue;
                         }
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.MMSColumnName]))
                         {
                             TaxonomyFieldValue mmsfield = (TaxonomyFieldValue)item[columnNames[Constants.Names.MMSColumnName]];
                             emp.MMSData = mmsfield.Label;
                             emp.MMSGUid = emp.MMSData.Split(':').Last() + "##" + mmsfield.TermGuid;
                             emp.MMSName = emp.MMSData;
                         }
 
                         if (item.FieldValues.ContainsKey(columnNames[Constants.Names.CreatedByColumnName]))
                         {
                             emp.UserName = ((FieldUserValue)item[columnNames[Constants.Names.CreatedByColumnName]]).LookupValue;
                         }
                         results.Add(emp);
 
                     }
                     catch { }
 
                 }
             }
 
             return results;
         }
         private  CamlQuery CreateCamlDateQuery(string fromDate, string toDate)
         {
             string camlString = String.Format("{0}n{1}n{2}n{3}n{4}",
                 "<View><Query><Where> <And><Geq>",
                 "<FieldRef Name='Created'/><Value Type='DateTime'>" + fromDate + "</Value>",
                 "</Geq><Leq><FieldRef Name='Created'/>",
                 "<Value Type='DateTime'>" + toDate + "</Value>",
                 "</Leq></And></Where></Query></View>");
             return new Microsoft.SharePoint.Client.CamlQuery() { ViewXml = camlString };//IncludeTimeValue='FALSE'
         }
         public  DateTime FirstDayOfWeek(DateTime date)
         {
             DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
             int offset = fdow - date.DayOfWeek;
             DateTime fdowDate = date.AddDays(offset);
             return fdowDate;
         }
         public DateTime LastDayOfWeek(DateTime date)
         {
             DateTime ldowDate = FirstDayOfWeek(date).AddDays(6);
             return ldowDate;
         }
         public  List<MMSLookup> GetTerms(string termSetName, ClientContext clientContext)
         {
             List<MMSLookup> mmsdata = new List<MMSLookup>();
             TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext);
             TermStore ts = tSession.GetDefaultSiteCollectionTermStore();
             TermSetCollection tsets = ts.GetTermSetsByName(termSetName, 1033);
             clientContext.Load(tSession);
             clientContext.Load(ts);
             clientContext.Load(tsets);
             clientContext.ExecuteQuery();
             TermSet tset = tsets[0];
             TermCollection terms = tset.GetAllTerms();//tset.GetTerms(lmi);   //
             clientContext.Load(terms);
             clientContext.ExecuteQuery();
 
 
             if (terms != null && terms.Count() > 0)
             {
                 foreach (var t in terms)
                 {
                     string[] termbits = t.PathOfTerm.Split(';');
                     
                     {
                         MMSLookup c = new MMSLookup();
                         
                         c.Name = t.PathOfTerm.Split(';').Last();
                        
                         c.ID = c.Name + "##" + t.Id.ToString();
                         mmsdata.Add(c);
                     }
                 }
             }
             return mmsdata;
         }
         private  void BuildColumnNameLookup(ClientContext CSOMcontext, Dictionary<string, string> columnNames, List list)
         {
 
             columnNames.Add(Constants.Names.dobColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.dobColumnName));
             columnNames.Add(Constants.Names.createdColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.createdColumnName));
             columnNames.Add(Constants.Names.employeeaddressColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.employeeaddressColumnName));
             columnNames.Add(Constants.Names.EmployeeNameColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.EmployeeNameColumnName));
             columnNames.Add(Constants.Names.ManagerColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.ManagerColumnName));
             columnNames.Add(Constants.Names.TitleColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.TitleColumnName)); 
             columnNames.Add(Constants.Names.MMSColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.MMSColumnName));
             columnNames.Add(Constants.Names.CreatedByColumnName, GetCSOMcolumnRef(CSOMcontext, list, Constants.Names.CreatedByColumnName));
         }
         private  string GetCSOMcolumnRef(ClientContext ctx, List list, string displayName)
         {
             Field fld = list.Fields.GetByTitle(displayName);
             ctx.Load(fld);
             ctx.ExecuteQuery();
             return fld.InternalName;
         }
 
     }
 }
 

DataManager.cs is referring to a Constant Class; here is the code snippet

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 
 namespace EmployeeWebAPITest
 {
     public class Constants
     {
         public class Names
         {
             public const string createdColumnName = "Created";
 
             public const string dobColumnName = "DOB";
 
             public const string employeeaddressColumnName = "EmployeeAddress";
 
             public const string EmployeeNameColumnName = "EmployeeName";
 
             public const string ManagerColumnName = "Manager";
 
             public const string MMSColumnName = "MMSData";
          
             public const string TitleColumnName = "Title";
 
             public const string CreatedByColumnName = "Created By";
            
         }
     }
 }
 

Within the App_Start folder in WebApiConfig.cs class add the following piece of code

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web.Http;
 
 namespace EmployeeWebAPITest
 {
     public static class WebApiConfig
     {
         public static void Register(HttpConfiguration config)
         {
             // Web API configuration and services
 
             // Web API routes
             config.MapHttpAttributeRoutes();
 
             config.Routes.MapHttpRoute(
                name: "GetEmployee",
                routeTemplate: "api/Employee/GetEmployee/{filterSpan}",
                defaults: new { controller = "Employee", action = "GetEmployee" }
          );
 
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
 }
 

Now build the solution & run

Here is the output of MMS data

clip_image006

Here is the output of Employee List data

clip_image008

HttpGet works fine in both IE & Chrome. The problem I have with HttpPost method in chrome but not in IE.

At the time of posting the employee data through Chrome it is throwing me the following error:

XMLHttpRequest cannot load http://<Domain Name>/WebAPITest/api/Employee/. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://<Domain Name>’ is therefore not allowed access.

As I have mentioned in the article: https://www.sharepointpals.com/post/How-to-achieve-the-Cross-domain-WebAPI-(GetPost)-call-using-Ajax-request, we need to follow the below steps to resolve the issue

Run the below commands in Package Manager Console

PM> Install-Package NuGet.Core

PM> Update-Package Microsoft.AspNet.WebApi –reinstall

PM> Install-Package Microsoft.AspNet.WebApi.Cors.ko -Version 5.0.0

In the EmployeeController class add the following attribute:

[EnableCors(origins: "*", headers: "*", methods: "*")]

Add the following piece of the line in web.config

 <system.webServer>
     <httpProtocol>
       <customHeaders>
         <add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
         <add name="Access-Control-Allow-Origin" value="*" />
         <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
         <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
       </customHeaders>
     </httpProtocol>
   </system.webServer>
 

Now the HttpPost from Chrome will be working properly.

As this WebAPI itself becomes a very lengthy article, so planning to write to display this WebAPI data into a Kendo grid which will be hosted within a custom SharePoint WebPart .

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

How to retrieve SharePoint List details by Content Query Webpart

Tarun Kumar Chatterjee
 
Net – Technology Specialist
February 26, 2016
 
Rate this article
 
Views
9109

Content search WebPart is used to fetch the data but it is fully depending on the Crawl. I mean to say, that the data will be available to the content search WebPart after crawl gets completed. In one of our requirement we had to fetch the data real time, so we decided to use Content Query WebPart.

Let see how we can fetch the data by using Content Query Webpart.

First let’s add 5 site columns named as EmpName, EmpEmail, EmpDept, EmpSalary & Emp Check

Create a list named as CQWebPartList

Add the 5 site columns to the newly created list & add few data into the list

clip_image002

Now create a SharePoint site page named as CQWebPartPage

Add a content query WebPart within the newly created page, Edit WebPart & add title as My Content Query.

Under query select the created list

clip_image004

Select the list type as below

clip_image006

Now export the content query WebPart

Create a sandbox solution

Add a module within the sandbox solution named as CQWebPartModule

Add the exported content query WebPart file under CQWebPartModule module

Go to the Style library — > XSL Style Sheet

Download the default main & Item Style XSL files named as: ContentQueryMain & ItemStyle

Rename the downloaded XSL file as CQMain & CQItemStyle respectively. Add the files to the solution under a newly created folder named as “Style Library”

Now open Content Query.webpart which we have added already under the module and modify the below properties to link with the XSL files

<property name="ItemXslLink" type="string" >/sites/Site1/Style Library/XSL Style Sheets/CQItemStyle.xsl</property>

<property name="MainXslLink" type="string" >/sites/Site1/Style Library/XSL Style Sheets/CQMain.xsl</property>

Add the following field mapping

<property name="CommonViewFields" type="string" >Title, Text;EmpName, Text;EmpEmail, Text;EmpDept, Text;Emp_x0020_Check, Text;EmpSalary</property>

Replace Elements.xml by the below code snippet

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Module Name="CQWebPartModule" Url="_catalogs/wp">

<File Path="CQWebPartModule\My Content Query.webpart" Url="My Content Query.webpart" >

<Property Name="Group" Value="Custom" />

</File>

</Module>

</Elements>

Now add the below template within CQItemStyle.xsl

 <xsl:template name="Employee-Details" match="Row[@Style='Employee-Details']" mode="itemstyle">
     <html>
       <table width="100%" cellspacing="4" cellpadding ="4">
         <xsl:if test="count(preceding-sibling::*)=0">
           <tr>
             <td width="20%" valign="top">
               <b>Title</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Name</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Email</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Department</b>
             </td>
             <td width="10%" valign="top">
               <b>Employee Salary</b>
             </td>
             <td width="10%" valign="top">
               <b>Employee Check</b>
             </td>
           </tr>
         </xsl:if>
         <tr>
           <td width="20%" valign="top">
             <xsl:value-of select="@Title" />
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpName" />
 
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpEmail" />
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpDept" />
           </td>
           <td width="10%" valign="top">
             <xsl:value-of select="@EmpSalary" />
           </td>
           <td width="10%" valign="top">
             <xsl:value-of select="@Emp_x005F_x0020_Check" />
           </td>
         </tr>
         
       </table>
     </html>
   </xsl:template>
 

The field names in these are very sensitive and if we miss _x005f in the field name will break it. Make sure to include the correct field names, which is different from internal name.

Refer the below examples for various fields.

Field NameXSL Field NameInternal Name
Vendor Description@Vendor_x005F_x0020_DescriptionVendor_x0020_Description
Go-live@Go_x005F_x002d_liveGo_x002d_live
IT HelpDesk #@IT_x005F_x0020_HelpDesk_x005F_x0020__x005F_x0023_IT_x0020_HelpDesk_x0020__x0023_

Use this in an itemstyle to output a header:

<xsl:if test="count(preceding-sibling::*)=0">

</xsl:if>

Use this in an itemstyle to output footer:

<xsl:if test="count(following-sibling::*)=0">

</xsl:if>

Add the below line of code in CQMain.xsl

<xsl:variable name="ItemStylePrefix" select="’Employee-‘" />

Rebuild the sandbox solution and deploy

Under the Style Library add the two modified XSL files

Now from the Site Page delete the WebPart and add it again

Under presentation select the Item style “Employee-Details”

clip_image008

Save the WebPart & the output will be looking like

clip_image010

 

Hope this artifact will help the basic use & implementation of Content query WebPart.

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

How to Execute CAML Query for More than One filtering dataset records in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
May 19, 2015
 
Rate this article
 
Views
12159

In one of the requirement, I was supposed to retrieve the records from a List by filtering on multiple records and Columns. i.e.,

I have a configuration List, on which the columns are Key, Category and Value.

Based on the Key and Category Pair, the Value needs to be retrieved. This we can execute with the basic CAML Query. But, in my case, I was supposed to retrieve the Values based on the multiple Key and Category Collection. i.e., on the page load, we will identify, what are the Keys and Categories used on this page and we need to fetch all the Values in a single query. Basically this is to reduce the multiple hits to the configuration list and reduces the execution time.

To be more clear, the input set will be Key{Key1, Key2, Key3} and Category{Cat1, Cat2, Cat3}. I need the records which has the above set of values alone. For this, we frame the CAML Query by string builder. But, there is another efficient way of doing this using LINQ.

 public List<ConfigListKeyBE> GetConfigKeyValueCollection(List<ConfigListKeyBE> objConfigListKeyBEList, string siteURL)
         {
             List<ConfigListKeyBE> objConfigListKeyBEListOutput = new List<ConfigListKeyBE>();
             try
             {
                 List<string> keyNames = (from k in objConfigListKeyBEList
                                          select k.KeyName).ToList();
 
                 List<string> categoryNames = (from k in objConfigListKeyBEList
                                               select k.CategoryName).ToList();
 
                 objConfigListKeyBEListOutput = GetConfigListKeyBE(siteURL, objConfigListKeyBEListOutput);
 
                 objConfigListKeyBEListOutput = (from p in objConfigListKeyBEListOutput
                                                 where keyNames.Contains(p.KeyName) && categoryNames.Contains(p.CategoryName)
                                                 select p).ToList();
 
                 return objConfigListKeyBEListOutput;
             }
             catch (Exception ex)
             {
                  
                 throw ex;
             }
             
         }
 
          
         public List<ConfigListKeyBE> GetConfigListKeyBE(string siteURL, List<ConfigListKeyBE> objConfigListKeyBEListOutput)
         {
             SPSecurity.RunWithElevatedPrivileges(delegate()
             {
                 using (SPSite site = new SPSite(siteURL))
                 {
                     SPWeb web = site.RootWeb;
                     SPList configList = web.Lists[LIST_CONFIGURATION];
                     if (configList != null)
                     {
                         if (configList.ItemCount > 0)
                         {
 
 
                             SPListItemCollection configListItemCollection = configList.GetItems();
 
 
 
                             if (configListItemCollection != null)
                             {
                                 if (configListItemCollection.Count > 0)
                                 {
                                     foreach (SPListItem item in configListItemCollection)
                                     {
                                         ConfigListKeyBE obj = new ConfigListKeyBE();
                                         obj.CategoryName = Convert.ToString(item[ConstantVariables.SC_CONFIGLIST_CONFIGUATIONCATEGORY]);
                                         obj.KeyName = Convert.ToString(item[ConstantVariables.SC_CONFIGLIST_TITLE]);
                                         obj.Value = Convert.ToString(item[ConstantVariables.SC_CONFIGLIST_CONFIGVALUE]);
                                         objConfigListKeyBEListOutput.Add(obj);
                                     }
 
 
                                 }
                             }
 
                         }
                     }
                 }
             });
             return objConfigListKeyBEListOutput;
         }
 

Here what I am doing is, first we retrieve all the List Items and apply a LINQ Query on top if for the required Key-Category collection.

 objConfigListKeyBEListOutput = (from p in objConfigListKeyBEListOutput
                                                 where keyNames.Contains(p.KeyName) && categoryNames.Contains(p.CategoryName)
                                                 select p).ToList();
 
 

Instead of writing many lines of code to frame the CAML Query, the above single line will do the magic for us. Moreover, we have a question like for the first time, retrieving all the records is an expensive process. I agree with that, but we can use the session or any other storing variable, so that for all the pageloads, we can use the same input data.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Configure List/Library Settings for Information Rights Management – SharePoint 2013

Sathish Nadarajan
 
Solution Architect
April 21, 2015
 
Rate this article
 
Views
11643

In this article, let us see, how to configure the Information Rights Management for a List / Library in SharePoint 2013.

1. Go to the List Settings

clip_image002

2. Under “Permissions and Management” Section, Click on the “Information Rights Management”

clip_image004

3. Give appropriate options and Click OK.

Note:

If the Information Rights Management link does not appear, IRM might not be enabled for your site. Contact your server administrator to see if it is possible to enable IRM for your site. The Information Rights Management link does not appear for picture libraries.

Happy Coding,

Sathish Nadarajan.

Category : SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment