2

Get recurring event from calendar list using Angular JS

Getting recurring event from calendar list using Angular JS is some bit tricky.
I am going to implement through CEWP(Content editor web part) in SharePoint.

1. Create HTML file for display events description(Angular View)


<html ng-app="myApp">
	<head lang="en">
		<script src="jquery.min.js"></script> 
		<script src="angular.min.js"></script>
		<script type="text/javascript" src="main.js"></script> 
	</head>
	<body>
        <div ng-app="myApp" ng-controller="myCtrl">
            <div ng-repeat="result in results">   
                <div>{{result.Title}}</div>
                <div>{{result.Description}}</div>
                <div>{{result.StartTime}}</div>
                <div>{{result.Location}}</div>
            </div>
        </div>
	</body>
</html>

Give the reference of Jquery and Angular js from your SharePoint site.

If you want to display upcoming limited(suppose top 5) events then you can add condition which is inbuilt facility of Angular JS

Add condition(ng-if) in Angular repeat section

<div ng-repeat="result in results" ng-if="$index < 4">   

2. Now Create one JavaScript which will get all events from calendar event list and check event start date with current date and display only feature events only.


var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) 
{
    $scope.results = [];
	var currSiteUrl = _spPageContextInfo.siteAbsoluteUrl;
	var webUrl, calendarListName;
	webUrl= currSiteUrl;
	calendarListName='Events'; 	
	wsURL = webUrl + "/_vti_bin/Lists.asmx";	 
    $scope.request =
        "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> <soap:Body>" +
        "<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>" +
        "<listName>" + calendarListName+ "</listName>" +
        "<query>" +
        "<Query>" +
        "<Where>" +
           "<DateRangesOverlap>" +
           "<FieldRef Name='EventDate' />" +
           "<FieldRef Name='EndDate' />" +
           "<FieldRef Name='RecurrenceID' />" +
           "<Value Type='DateTime'><Year/></Value>" +
           "</DateRangesOverlap>" +
        "</Where>" +
        "</Query>" +
        "</query>" +
        "<queryOptions>" +
        "<QueryOptions>" +
            "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
        "</QueryOptions>" +
        "</queryOptions>" +
        "</GetListItems>" +
        "</soap:Body></soap:Envelope>";
 
	var results1 = [];
	$http({
        method: 'POST', 
        url: wsURL, 
        async: false,
        data: $scope.request, 
        headers: {
            'Content-Type': 'text/xml; charset=\"utf-8\; action="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer"'
        }
    })
    .success(function(xData, status, headers, config){       
        if (status === 200)
        {
             var root = $(xData);
                    root.find("listitems").children().children().each(function () {
						$this = $(this);
						var ids = $this.attr("ows_UniqueId").split(";");
						var rec = $this.attr("ows_fRecurrence");
						results1.push({
							"StartTime": $this.attr("ows_EventDate"),
							"EndTime": $this.attr("ows_EndDate"),
							"Title": $this.attr("ows_Title"),
							"Recurrence": (rec === "1" ? true : false),
							"Description": $this.attr("ows_Description"),
							"Location":$this.attr("ows_Location"),
							"Guid": ids[1],
							"Id": ids[0],
						});
                });
        }
	    var filtered_item = [];
	    for (var i = 0; i < results1.length; i++) 
		{
			var current_Time = new Date().getTime()
			var Start_Time = new Date(results1[i].StartTime).getTime();
			if (Start_Time  >= current_Time) {
				filtered_item.push(results1[i]);
			}
		}
      $scope.results =  filtered_item;
    })
    .error(function(data, status, headers, config){
        console.log('In Error');
        console.log(data);
    }); 
});

To get the recurrence event we have added parameter “ExpandRecurrence” with value “True” by which we can identify that event is recurrence or not.

In output you will get Title, Description, Start time and location of event. You can customize as per your requirement and apply css also.

3

Send Email through REST API in SharePoint

In this article i will explain you how to send E-Mails through REST API in SharePoint.

We can send E-Mails through REST API using SP.Utilities.Utility.SendEmail.

Here is code to send E-Mail using REST API in SharePoint

$.ajax({
        contentType: 'application/json',
        url: urlEmail,
        type: "POST",
        data: JSON.stringify({
                  'properties': {
                  '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                  'Body': 'Hello user.. You got mail from codeplayandlearn.wordpress.com',
                  'To' : { 'results': ['admin@codeplayandlearn.com'] },
                  'Subject': "E-Mail From REST API";
                }
            }),
        headers: {
                    "Accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
        success: function (data) {
                alert("Email Send Successful.");
                },
        error: function (err) {
                alert(err.responseText);
                }
        });

Here you don’t need to specify from E-Mail Id.

And make sure that To(Send to) E-Mail id should be E-Mail Id of any user from SharePoint Users.

And also make sure that metadata of Email should be

'type':'SP.Utilities.EmailProperties'

If this method not work or still you are getting error while sending E-Mails then try this method

Using separate function to send E-Mail from REST API


function processSendEmails() {
    var from = 'system@codeplayandlearn.com',
        to = 'member@codeplayandlearn.com',
        body = 'Dear member you got mail from Code Play and Learn',
        subject = 'Email from REST API';
    // Call sendEmail function
    sendEmail(from, to, body, subject);
}

function sendEmail(from, to, body, subject) {
    //Get the relative url of the site
    var siteurl = _spPageContextInfo.webServerRelativeUrl;
    var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': [to]
                },
                'Body': body,
                'Subject': subject
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function(data) {
            alert('Email Sent Successfully');
        },
        error: function(err) {
            alert('Error in sending Email: ' + JSON.stringify(err));
        }
    });
}

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', processSendEmails);
});

Here i have created separate function to send E-Mail in which i am passing information of E-Mails.

By using this methods you can send E-Mails through REST API in SharePoint.

If this blog helps you in understanding SharePoint please share and like this blog.

Happy coding..!!

Learn code while playing with it..!!

0

CRUD Operation with REST API in SharePoint

Overview of CRUD operation with REST API in SharePoint will be explained in this article.

 

SharePoint 2013 enables you to remotely interact with SharePoint sites by using REST. By using REST API you can interact with SharePoint site from any technology which can support REST API i.e. IPhone, Android, PHP, JAVA etc..

 

Now question is what is this REST API?

Full form of REST is Representational State Transfer (REST). This is service provide in SharePoint 2013. To perform all basic operation which can be perform using CSOM or JSOM.

 

So now you will ask that what is new in REST API?

REST API has obvious benefits for mobile applications that are written in non-Microsoft platforms, such as iOS and Android devices, and it’s also a useful resource for Windows 8 apps which are written in HTML5 and JavaScript which can interact with SharePoint site through REST API.

Now come to the point how to use REST API in SharePoint?

To use REST API you need to construct a RESTful HTTP request string using OData Standard (OData = Open Data Protocol)

 

 

Construction of REST API URL

Base URL

   http://<domain>/<site url>/_api/

Retrieve the lists from a SharePoint site

   http://<domain>/<site url>/_api/web/lists

Get a particular list by specifying its ID or Title

   _api/web/lists/getByTitle('ListName')/

In REST API you need to pass address of your site then add “/_api/lists/” and all list in site will be display. You can use other REST Client to perform REST Queries.To access any Site Collection you need to pass “_api/site” and to access any site then you need to pass “_api/web


 

Get Groups in site by using REST API

_api/Web/SiteGroups/GetById(IdOfGroup)

 

Get user by user id

_api/web/getuserbyid(UserId)

 

Remove particular user from group

executor.executeAsync({
  url: "<app web url>/_api/web/sitegroups(GroupId)/users/getbyid(UserId)",
  method: "POST",
  headers: { "X-HTTP-Method": "DELETE" },
  success: successEventHandler,
  error: errorEventHandler
});

 

Get all user in Site/Web

_api/web/siteusers

 

To get all groups of site

_api/web/sitegroups

Get all items in List

_api/web/lists/getByTitle('Task')/items

 

Option for filtering and sorting data in REST API

Option Purpose
$select Specifies which fields are included in the returned data.
$filter Specifies which members of a collection, such as the items in a list, are returned.
$expand Specifies which projected fields from a joined list are returned.
$top Returns only the first n items of a collection or list.
$skip Skips the first n items of a collection or list and returns the rest.
$orderby Specifies the field that’s used to sort the data before it’s returned.

 

Examples

_api/web/lists/getByTitle('Languages')/items?$select=Title,LanguageScope,LanguageType
_api/web/lists/getByTitle('Languages')/items?$filter=LanguageScope eq 'High'

 

Note: Multiple option can be combine using “&” operator

_api/web/lists/getByTitle('Languages')/items?$select=Title&$filter=LanguageScope eq 'High'&$top=2

 

Explanation:

This will get top 2 item Title whose Scope=’High’

 


Best way to use REST Call is AJAX.

Here is simple example of REST Call with AJAX

$.ajax({
  url: "http://<site url>/_api/web/Users",
  type: "GET",
  headers: { "content-type": "application/json;odata=verbose" },
  success: successEventHandler,
  error: errorEventHandler
});

 

Create New Web using REST API

 

Note: Here Type will be “POST” because we are putting data in SharePoint. Otherwise it will generate error.


$.ajax({
  url: "http://<site url>/_api/web/webs/add",
  type: "POST",
  data: "{ 'parameters': { '__metadata': { 'type': 'SP.WebCreationInformation' },
    'Title': 'NewMyWeb', 'Url': 'MyCustomWeb', 'WebTemplate': 'STS',
    'UseSamePermissionsAsParentSite': true } }",
  headers: { 
    "X-RequestDigest": "Digest value",
    "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose",
    "content-length": "Body Data Length"
  },
  success: successEventHandler,
  error: errorEventHandler
});

 

Delete Web using REST API

To delete any web we need to specify url for that particular web and make sure

“X-HTTP-Method”:”DELETE” 

otherwise delete operation will not perform


$.ajax({
  url: "http://<site url>/_api/web",
  type: "POST",
  headers: { 
    "X-RequestDigest": "Digest Value",
    "X-HTTP-Method": "DELETE"
  },
  success: successEventHandler,
  error: errorEventHandler
});

 

Hope now you will get enough idea to get start with REST API in SharePoint.

Please Like and share this blog and comment if you are stuck anywhere.

Happy Coding..!!
Learn code while playing with it..!!
3

Sharepoint Error “A type named ‘SP.Data.DemoYourListItemas’ could not be resolved by the model. When a model is available, each type name must resolve to a valid type.” While adding list item in list using REST API

Hello Developers..

Today while playing with REST API i got some mysteries error like “A type named ‘SP.Data.DemoListItemas’ could not be resolved by the model. When a model is available, each type name must resolve to a valid type.

After working on it i found solution and cause of due to which error occur.

Let me tell you that this error occur during inserting list item in list using REST API. While adding item in list we must pass “ListItemEntityTypeFullName” of list so that REST API can know type of list.

So now question is that how to find ListItemEntityTypeFullName of list.

You need to make REST query and fire in as url like:

http://SharePointFarm:1000/Tag/Site/_api/Web/Lists/GetByTitle(YourListNameWithApostophe)?$select=ListItemEntityTypeFullName

Run this REST url in browser. You will get ListItemEntityTypeFullName in output.

FireShot Capture -  - http___bidsp03_1000_student_StudentRecords__api_Web_Lists_GetByTitle('todol

Now add this list type in your REST Query.

var listurl = _spPageContextInfo.webAbsoluteUrl + “/_api/Web/Lists/GetByTitle(‘ListItem’)/Items”;
var data = {
__metadata: { ‘type’: ‘SP.Data.ListType‘ },
Title:’Test’,
}

$.ajax({
url: listurl ,
type: “POST”,
async : false,
headers: {
“accept”: “application/json;odata=verbose”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
“content-Type”: “application/json;odata=verbose”
},
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});

Now you will not get any error like this while adding item in list using REST API.

Happy Coding…!!