Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SharePoint Add-In Part to show news with Like button and comments from a blog.
<%@ Page Language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<WebPartPages:AllowFraming ID="AllowFraming" runat="server" />
<html>
<head>
<title></title>
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<!-- Include required references for the like button -->
<script type="text/javascript" src="/_layouts/15/SP.core.js"></script>
<script type="text/javascript" src="/_layouts/15/init.debug.js"></script>
<script type="text/javascript" src="/_layouts/15/reputation.js"></script>
<script type="text/javascript">
// Set the style of the client web part page to be consistent with the host web.
(function () {
'use strict';
var hostUrl = '';
if (document.URL.indexOf('?') != -1) {
var params = document.URL.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var p = decodeURIComponent(params[i]);
if (/^SPHostUrl=/i.test(p)) {
hostUrl = p.split('=')[1];
document.write('<link rel="stylesheet" href="' + hostUrl + '/_layouts/15/defaultcss.ashx" />');
break;
}
}
}
if (hostUrl == '') {
document.write('<link rel="stylesheet" href="/_layouts/15/1033/styles/themable/corev15.css" />');
}
})();
</script>
<%-- Blog News --%>
<script type="text/javascript">
var hostweburl;
var appweburl;
// Load the required SharePoint libraries
$(document).ready(function () {
//Get the URI decoded URLs.
hostweburl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl")
);
appweburl =
decodeURIComponent(
getQueryStringParameter("SPAppWebUrl")
);
blogweburl = "/sites/dev/blog";
bloglistname = "Posts";
// resources are in URLs in the form:
// web_url/_layouts/15/resource
var scriptbase = hostweburl + "/_layouts/15/";
// Load the js files and continue to the successHandler
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});
// Function to prepare and issue the request to get
// SharePoint data
function execCrossDomainRequest() {
// executor: The RequestExecutor object
// Initialize the RequestExecutor with the app web URL.
var executor = new SP.RequestExecutor(appweburl);
// Issue the call against the app web.
// To get the title using REST we can hit the endpoint:
// appweburl/_api/web/lists/getbytitle('listname')/items
// The response formats the data in the JSON format.
// The functions successHandler and errorHandler attend the
// sucess and error events respectively.
executor.executeAsync(
{
url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + bloglistname + "')/items?@target='" + hostweburl + "/blog'&$top=5",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
}
);
}
// Function to handle the success event.
// Prints the data to the page.
function successHandler(data) {
var jsonObject = JSON.parse(data.body);
var blogsNewsHTML = "";
var results = jsonObject.d.results;
for (var i = 0; i < results.length; i++) {
blogsNewsHTML = blogsNewsHTML + "<div>";
blogsNewsHTML = blogsNewsHTML + "<a href=\"" + hostweburl + "/blog/Lists/" + bloglistname + "/Post.aspx?ID=" + results[i].ID + "\" target=\"_blank\">" + results[i].Title + "</a>"; //Title
blogsNewsHTML = blogsNewsHTML + results[i].Body; //Content of the news
blogsNewsHTML = blogsNewsHTML + "<br>"
var date = new Date(results[i].PublishedDate); //Convert ISO date format
blogsNewsHTML = blogsNewsHTML + "Published " + date.toISOString().slice(0, 10); //Strip the end
blogsNewsHTML = blogsNewsHTML + "<br>";
blogsNewsHTML = blogsNewsHTML + "<span id=\"root-likesElement-1\"><span class=\"ms-comm-likesMetadata ms-metadata\"><span class=\"ms-comm-likesImgContainer\"><img src=\"/_layouts/15/images/LikeFull.11x11x32.png?rev=44\"></span><span id=\"likesCountElement" + results[i].ID + "\" class=\"ms-comm-likesCount ms-comm-reputationNumbers\">" + results[i].LikesCount + "</span></span><a href=\"javascript:;\" id=\"likesElement" + results[i].ID + "\" class=\"ms-secondaryCommandLink\">" + GetUserLiked(results[i].ID) + "</a></span>";
blogsNewsHTML = blogsNewsHTML + "&nbsp;&nbsp;&nbsp;"
blogsNewsHTML = blogsNewsHTML + "<a href=\"" + hostweburl + "/blog/Lists/" + bloglistname + "/Post.aspx?ID=" + results[i].ID + "\" target=\"_blank\"><b><span id=\"commentsElement" + results[i].ID + "\">" + results[i].NumCommentsId + "</span></b>&nbsp;" + "commentaire(s)</a>"; //Number of comments
blogsNewsHTML = blogsNewsHTML + "</div><br>";
//Debugging purposes
//blogsNewsHTML = blogsNewsHTML + "<button onclick=\"setLike(true, " + results[i].ID + ")\">Like</button><br>"
//blogsNewsHTML = blogsNewsHTML + "<button onclick=\"setLike(false, " + results[i].ID + ")\">Unlike</button><br>"
//blogsNewsHTML = blogsNewsHTML + "<button onclick=\"GetUserLiked(" + results[i].ID + ")\">User liked ?</button><br>"
}
$('#blogNews').append(blogsNewsHTML);
}
// Function to handle the error event.
// Prints the error message to the page.
function errorHandler(data, errorCode, errorMessage) {
document.getElementById("blogNews").innerText =
"Could not complete cross-domain call: " + errorMessage;
}
// Function to retrieve a query string value.
// For production purposes you may want to use
// a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
function setLike(likeFlag, itemId) {
SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js');
SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', UpdateLike(likeFlag, itemId));
});
}
function UpdateLike(likeFlag, itemId) {
var listId = "2a0990d8-236a-441a-a231-78899ed4822a"; //set list id and make sure rating is enabled in the list
var ctx = new SP.ClientContext(blogweburl); //retrieve the web containing the blog
Microsoft.Office.Server.ReputationModel.Reputation.setLike(ctx, listId, itemId, likeFlag);
ctx.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
//TODO move this logic to the RatingSuccess
$("#likesElement" + itemId).text(likeFlag ? "Unlike" : "Like");
if (likeFlag)
{
$("#likesCountElement" + itemId).text(parseInt($("#likesCountElement" + itemId).text()) + 1);
$("#likesElement" + itemId).attr("href", "javascript:setLike(false, " + itemId + ")");
}
else
{
$("#likesCountElement" + itemId).text(parseInt($("#likesCountElement" + itemId).text()) - 1);
$("#likesElement" + itemId).attr("href", "javascript:setLike(true, " + itemId + ")");
}
};
function RatingSuccess(sender, args) {
//alert('Rating updated successfully');
}
function RatingFailure(sender, args) {
//alert('Failed:' + args.get_message());
}
function GetUserLiked(itemId) {
var context = new SP.ClientContext(blogweburl);
var web = context.get_web();
var list = context.get_web().get_lists().getByTitle(bloglistname);
var item = list.getItemById(itemId);
//Retrieve current user ID
var currentUser = web.get_currentUser();
context.load(currentUser);
var userId;
context.executeQueryAsync(Function.createDelegate(this, function (success) {
userId = currentUser.get_id();
}));
var found = false;
context.load(item, "LikedBy", "ID", "LikesCount");
context.executeQueryAsync(Function.createDelegate(this, function (success) {
// Check if the user id of the current users is in the collection LikedBy.
var likedByUsers = item.get_item('LikedBy');
if (likedByUsers) {
for (var $i = 0, $j = likedByUsers.length; $i < $j; $i++) {
var likedByUser = likedByUsers[$i];
if (likedByUser.get_lookupId() === userId) {
found = true;
//Initialize the default value
$("#likesElement" + itemId).text("Unlike");
$("#likesElement" + itemId).attr("href", "javascript:setLike(false, " + itemId + ")");
}
}
}
if (!found) {
//Initialize the default value
$("#likesElement" + itemId).text("Like");
$("#likesElement" + itemId).attr("href","javascript:setLike(true, " + itemId + ")");
}
}))
}
</script>
</head>
<body>
<div>
<div><strong>Blog News</strong></div>
<div id="blogNews"></div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.