This was a triumph.
I'm making a note here: HUGE SUCCESS.

Search This Blog

Monday, November 3, 2014

IT'S OVER NINE THOUSAAAAAAAAAAND!!!!

Actually, it's already over ten thousand by now, but I just couldn't let a title like that slip away! :D

It has been quite a while since I made a new post. Fear not, I will post something SharePoint-related soon. My work has the priority here, but if I can find some spare time then I will continue writing on the new post. Sneak peek: calendar overlays combined with checkboxes!

Let's give you guys a short update about my project, to inform you about what it is exactly that I'm so busy with.
Currently, I'm mainly creating and improving workflows using Nintex. Also in general I'm improving some of my scripts and the CSS of my project, along with some extra's to make it more user friendly. Most of my work goes to those workflows, I need to test them over and over again to make sure there is absolutely no error at all, since it is my intention to make them work properly from the start and then never have to change them again (unless there are major changes required). And other than that, I'm now also learing VBA.

Hopefully I'll be able to finish these workflows soon and when I have some spare time left I'll come back to entertain you all with a new post. Stay tuned!

Monday, June 16, 2014

Sorry for my absence!

I have been neglecting my blog lately and I just wanted to pop in to tell you all that I'll try to get back more often!

For the past month I have been learning C# and so far I managed to create a WinForm tool that allows me to synchronize the members of groups in the API with groups in the SharePoint environment. So, basically, when I connect to the API and I see that there are new members in a group called "HR employees", but those new members are not yet in the corresponding SharePoint group, then I can just select the new members and synchronize them. They then get added to the corresponding SharePoint group for the HR employees. Same goes for when I need to remove members: if a user no longer is present in the API group (I keep saying group, but I believe it's called a resource) but still is present in the corresponding SharePoint group, then it means I need to remove that user from the SharePoint group.

This all works really neat now, I'm even using a background worker and a progress bar!

So anyway. I'll be back sometime soon, currently still learning C# and trying to make tools for practice.
Until next time!

Wednesday, March 5, 2014

Live notifications from new items in lists/libraries to which current user is subscribed, using JavaScript in SharePoint 2013

Warning! Long post! 
Screenshots can be found at the end of the post. Take your time to read everything.
----------------

So the past six days I've been working on a notification script for our SharePoint intranet.
At first I didn't even know where to start, so I asked a question on Stack Exchange. After getting some inspiration from the answers I received (thanks you guys!) I decided I should just give it a try.

I wanted a script that would show a notification in the top right corner of the page whenever a new item was added to a certain list or library.
I also wanted to give users the ability to "subscribe" to a list or library, and hence let them see only notifications whenever a new item was added to a list or library to which they were subscribed, so I also made a script to handle the subscribing.

These are the two scripts I've written: notification.js and subscribe-to-list-or-library.js.
Both scripts are working in the latest versions of Google Chrome, Mozilla Firefox and Internet Explorer.

Since I don't want to put too much comments in the code, I just decided to explain both scripts first and then provide you with the code. So please take some time to read how these scripts work and what steps they contain, and then take a look at the code. It will be a lot easier to understand the code when you read the explanation about it first.

Script: subscribe-to-list-or-library.js

This script has the following features:
  • subscribe to a list or library by clicking a button named "subscribe"
  • unsubscribe from a list or library by clicking a button named "unsubscribe"
  • be subscribed to multiple lists or libraries
  • receive live notifications whenever a new item was added to one or more lists or libraries to which a user is subscribed
Do note that it's possible to subscribe to a list or library from any sub site. So for example, you can subscribe to list X on sub site A, and library Y on sub site B, and receive notifications from list X and library Y while browsing content on sub site C. I tried explaining this as easy as I could, so there you have it.
Also, regarding the buttons: there is no such thing as a button to subscribe and another button to unsubscribe. They are one and the same button. Actually it's not even a button. It's a div element disguised as a button. I just change the text inside the div based on whether or not a user is subscribed. If a user is, then the text in the div will be "unsubscribe". If a user is not, then it will be "subscribe". Simple as that.

Steps on how this script works

First of all, you need to provide a button (a div, actually, but I'll call it a button) on a page that has a web part of a list or library.  The button contains two other elements, one div that will hold either the text "subscribe" or "unsubscribe", and one hidden div that will hold the name of the list or library a user should be able to subscribe to. This name has to be correct and is case sensitive.
And now for the steps. Keep in mind that part of the script runs as soon as the page has loaded, and certain functions only run on the click of a button.

On page load:
  • Find all elements that have a class named "subscrButton" (these are the subscribe buttons), and for each element, store the name of the list/library in a variable, as well as the text from the first div (which contains either "subscribe" or "unsubsribe").
  • Still in the "for each" statement: get all list items from a list named "Subscribed users", and for each row in that list, check if the current user is in that row and if he/she is subscribed to a list/library with the same name as the one stored in a variable.
    • If true, set a boolean named "inList" to true.
    • If false, set a boolean named "inList" to false.
  • If the boolean named "inList" is false, then set the innerHTML of the first div to "subscribe".
  • If the boolean named "inList" is true, then set the innerHTML of the first div to "unsubscribe".
So that part of the code is only to check whether or not a user is already subscribed to a list or library, and set the correct text to the button.Next comes the actual subscribe/unsubscribe functionality.

On button click:
  • Store the name of the list or library linked to that button, in a variable.
  • Store the name of the page on which the user clicked the button, in a variable.
  • Store the path to the sub site in which the page with the button that the user clicked on is located, in a variable.
  • Store the text of the button ("subscribe" or "unsubscribe") in a variable.
  • If the text of that variable equals "unsubscribe":
    • Set the innerHTML of the button that was clicked to "subscribe".
    • Check the "Subscribed users" list and look for the row that contains both the name of the user and the name of the list/library from which the users wants to unsubscribe.
      • If the row has been found, set another variable named "listIDDel" to the ID of the current row that matches the name of the user and the name of the list/library.
    •  Update the "Subscribed users" list by deleting the row that has the id matching "listIDDel" (and thus, removing the user from the "Subscribed users" list).
    • After the user has successfully been deleted from the "Subscribed users" list, run some functions named "runInOtherFile" and "runDeleteInOtherFile" which are both located in notification.js. I'll explain the use of these later.
  • If the text of that variable equals "subscribe":
    • Set the innerHTML of the button that was clicked to "unsubscribe".
    • Update the "Subscribed users" list by making a new item with the following values: the name of the user, name of the list/library, url of the page, path to the sub site.
    • After the user has successfully been added to the "Subscribed users" list, run a function named "runInOtherFile" which is located in notification.js. I'll explain the use of this one later.

Script: notification.js

This script has the following features:
  • Send a notification whenever a new item was added to a list or library to which a user is subscribed

A minor down side: the script does not keep track of which items were added to certain lists or library since the last time a user logged on. So it's not possible to store notifications somewhere about new items and greet a user with a list of all the new items that were added since the last time he/she logged in. This script is for live notifications, nothing else.

It also won't show a globe with a number on top of it saying "you have x new notifications" like on Facebook, I'm not keeping track of that. While I might be able to add such functionality to this script, this will be for another time.

Steps on how this script works

The script will contain two types of code. One that will run only on page load, and one that will run every five seconds.

On page load:
  • Check the "Subscribed users" list and look for rows that contain both the name of the user and the name of any list/library to which a user is subscribed.
    • For each row in that list: check if the user is in the row. If he/she is, raise the value of a counter by 1 and push the current row to an array. We then push the content of that array to another array, which will act as a container array (multidimensional array, actually).
  • If the counter equals 0, meaning no rows matching the current user were found, nothing will happen and the notification script will stop.
  • If the counter is not 0, meaning one or more occurences of the current user were found in the "Subscribed users" list, we will do a loop. For each item in the multidimensional array:
    • Store a unique session in the session.
    • Set an interval of five seconds for a function named "repeatEvery5Seconds".
Every five seconds:
  • The function "repeatEvery5Seconds" will run for each item in the multidimensional array, storing the following values in variables: the name of the user, name of the list/library, url of the page, path to the sub site, name of the session item. 
  • The function "repeatEvery5Seconds" will trigger another function named "fetchCurrentListStatus". 
    • The function "fetchCurrentListStatus" will check each list or library to which a user is subscribed to, and push each row to an array.
      • If the length of the array is null or 0, the list will be considered empty and an empty session variable will be set.
      • If the length of the array is not null or not 0:
        • If there is a session item present for the current list and if that session item is not empty, then reset that session item to a new value matching the array and run a function named "itemChange".
        • Else if there is a session item present for the current list and if that session item is null or 0, then reset the session item to a new value matching the array and run a function named "itemChange". 
        • If the length of the array matches the length of the session item, then that indicates no changes were made.
    • The function "itemChange" will run when called.
      • If the length of the array is smaller than the length of the session item, then this means that an item was deleted from the list/library. The session item will then be updated, and will contain the same value as the array.
      • Else if the length of the array is larger than the length of the session item, then this means that a new item was added to the list/library.
        • We will then compare all elements in the array with all elements in the session item, and if we find the one that is not present in the session storage, we will search for that item in the list/library and fetch its name. 
          • We then create a div that will be our notification, and we will give it a text containing the name of the new item and a link to the page on where the user can find it. After five seconds, the notification will be removed.
        • We then check if the session item matches the array. If not, set the session item to match the value of the array. 
Only when called by "subscribe-to-list-or-library.js": 
  • The function "runInOtherFile":
    • Will run with a timeout of one second, and will replace the array that was made on page load and that holds the list of all the lists/libraries to which a user is subscribed. Since the user decided to unsubscribe from a list/library, this array needs to be updated. This function will do so be checking the "Subscribed users" list again.
  • Yhe function "runDeleteInOtherFile":
    • For each item (array) in the multidimensional array, check if there is an item that matches the name of the list from which the user wanted to subscribe. If there is, then find the corresponding session item and set its value to nothing. And then we will remove the item from the multidimensional array (by using the split function).

There you have it. That was just the explanation about the scripts. I tried to write it as short as possible. Nest step: setting up the necessary lists and buttons.

Prerequisites 

Before you can actually use the scripts, you'll need to set up some things first. Like a list where you will store your subscribed users, and buttons for each list/library you want to have your users subscribe to.

Create a list for your subscribers

You need to make a simple list at the top site level named "Subscribed users". If you want my code to work straight away, then I suggest you use that name.

Your will then need to make three new columns for your list: ListLibID, PageURL and SubsiteURL. I originally used to store the GUID of a list/library in the ListLibID column, but after several problems with that in different browsers I decided to just use the name of a list or library instead of the GUID. That was also the main reason on why I also needed a column to save the subsite in (required to call the list across sub sites).

Make sure your list named "Subscribed users" is allowed to be edited by everyone, meaning everyone should have edit permissions. You can change the settings of the view of the list so that it is only visible to you or not visible at all (use the filter for this, set some impossible filter so no item will ever be shown but will still be present in the list).That way you can avoid users sneaking around and trying to meddle with the list. I just used CSS to hide that particular list and the list itself from the site content, so nobody ever finds it.

Create buttons for your lists/libraries

Now that you have your list ready, it is time to make some buttons. You'll only need to make these for list or libraries of which you want users to be able to subscribe to.

On the page that holds the web part of the list/library of which users should be able to subscribe to, place the following code directly above the code from the web part:
<div class="buttonContainer">
   <div class="subscrButton">
      <div class="subscrButtonTitle"></div>
      <div class="innerSubscr" style="display: none;">
         List or library name here​​
      </div>
   </div>
</div>

In case you want it, here's the CSS of the button above (note: not identical to the style as seen in screenshots!):
.buttonContainer {
 position: relative;
}
.subscrButton {
 background-color: white;  
 border: 1px solid rgb(185, 184, 184);
 font-family: "Segoe UI Semilight","Segoe UI","Segoe", Tahoma,
               Helvetica,Arial,sans-serif;
 color: #0066CC;
 text-align: center;
 z-index: 100;
 position: absolute;
 right: 0;
 padding: 3px 10px 5px 10px;
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px;
 border-radius: 5px;
 opacity: 0.8;
}

Add references to the scripts

I suggest you just put a reference to the scripts in your master page. For example:
<!--SPM:<sharepoint:scriptlink id="scriptLink12" language="javascript" 
 localizable="false"  ondemand="false" runat="server"
 name="~sitecollection/Style Library/Scripts/subscribe-to-list-or-library.js">
-->
<!--SPM:<sharepoint:scriptlink id="scriptLink13" language="javascript" 
 localizable="false" ondemand="false" runat="server"
 name="~sitecollection/Style Library/Scripts/notification.js">
-->

Make sure your master page and your scripts are checked in.

Now, for the most interesting part, the actual code.

The code

subscribe-to-list-or-library.js

SP.SOD.executeOrDelayUntilScriptLoaded( 'SP.UserProfiles.js', 
   "~sitecollection/Style%20Library/Scripts/jquery.SPServices-2013.01.min.js");
SP.SOD.executeFunc('SP.js', 'SP.ClientContext');

var firstDiv;
var inList = new Boolean(); 
inList = false;
var listIDDel;
var SURL = $().SPServices.SPGetCurrentSite();
var PURL = window.location.pathname;
var LLID;
var USER = $().SPServices.SPGetCurrentUser({ 
 webURL: "", 
 fieldName: "Title", 
 fieldNames: {}, 
 debug: false
});

$("#content").find($("div.subscrButton")).each(function(){
 LLID = this.childNodes[1].innerHTML.replace(/[\u200B]/g, ''); 
 firstDiv = this.childNodes[0].innerHTML.replace(/[\u200B]/g, '');
 $().SPServices({
  operation: "GetListItems",
  async: false,     
  webURL: 'https://your-site-here.com/',
     listName: 'Subscribed users',
  completefunc: function (xData, Status) {
   $(xData.responseXML).find("z\\:row, row").each(function() {
    if (($(this).attr("ows_Title") == USER) 
        && ($(this).attr("ows_ListLibID") == LLID)) {
     inList = true;
    }
   });
  }
 });

 if (inList == false) {
  this.childNodes[0].innerHTML = 'SUBSCRIBE';
 }
 else if (inList == true) {
  this.childNodes[0].innerHTML = 'UNSUBSCRIBE';
  inList = false;
 }
});

$("div.subscrButton").click(function(){ 
 LLID = this.childNodes[1].innerHTML.replace(/[\u200B]/g, ''); 
 firstDiv = this.childNodes[0].innerHTML.replace(/[\u200B]/g, '');
 console.log(firstDiv);
 if (firstDiv == "UNSUBSCRIBE") {
  this.childNodes[0].innerHTML = 'SUBSCRIBE';
  console.log('User "' + USER + '" wants to unsubscribe. ');
  
  $().SPServices({
   operation: "GetListItems",
   async: false,     
   webURL: 'https://your-site-here.com/',
      listName: 'Subscribed users',
   completefunc: function (xData, Status) {
    $(xData.responseXML).find("z\\:row, row").each(function() {
     if (($(this).attr("ows_Title") == USER) 
         && ($(this).attr("ows_ListLibID") == LLID)) {
      listIDDel = $(this).attr("ows_ID");
     }
    });
   }
  });
         
  $().SPServices({
   operation: 'UpdateListItems',
   webURL: 'https://your-site-here.com/',
   listName: 'Subscribed users',
   updates: '<batch onerror="Continue" precalc="True">' + 
              '<method cmd="Delete" id="1">' +
              '<field name="ID">'+ listIDDel +'</field>' +
              '<field name="Title">'+ USER +'</field>' +
              '<field name="ListLibID">'+ LLID +'</field>' +
              '<field name="PageURL">'+ PURL +'</field>' +
              '<field name="SubsiteURL">'+ SURL +'</field>' +
              '</method>' +
           '</Batch>',
   completefunc: function(xData, Status) {
      console.log('User "'+USER+'" is now removed from the subscribers list.'); 
   }
  });

  runInOtherFile();
  runDeleteInOtherFile(LLID);

 }
 else if (firstDiv == "SUBSCRIBE") {
  this.childNodes[0].innerHTML = 'UNSUBSCRIBE';
  console.log('User "'+USER+'" wants to subscribe. ' + 
              'Adding user to subscribers list now.');
  
  $().SPServices({
   operation: 'UpdateListItems',
   webURL: 'https://your-site-here.com/',
   listName: 'Subscribed users',
   updates: '<batch onerror="Continue" precalc="True">' + 
              '<method cmd="New" id="1">' +
              '<field name="Title">'+ USER +'</field>' +
              '<field name="ListLibID">'+ LLID +'</field>' +
              '<field name="PageURL">'+ PURL +'</field>' +
              '<field name="SubsiteURL">'+ SURL +'</field>' +
              '</method>' +
           '</batch>',
   completefunc: function(xData, Status) {
    console.log('User "'+USER+'" has been added to the subscribers list.');  
      }
  }); 
  runInOtherFile();
 }
});

notification.js

var USER = $().SPServices.SPGetCurrentUser({ 
 webURL: "", 
 fieldName: "Title", 
 fieldNames: {}, 
 debug: false
});

var currentViewUser;
var currentViewLLIB;
var currentViewPURL;
var currentViewSURL;
var currentViewCOUNT;
var counter = 0;
var tempArr;
var itemArray = new Array();
var itemArrayContainer = new Array();
var itemArrayReplaced = new Array();
var itemArrayContainerReplaced = new Array();


console.log('Notification script has been loaded! Starting script now...'
          + '\n--------------------------------------------------------');
runOnLoad();

function runOnLoad() {
 $().SPServices({
  operation: "GetListItems",
  async: false,        
  webURL: 'https://your-site-here.com/',
     listName: 'Subscribed users',
  completefunc: function (xData, Status) {
   $(xData.responseXML).SPFilterNode("z:row").each(function() {
    if ($(this).attr("ows_Title") == USER) {
     counter++;
     itemArray[counter] = new Array($(this).attr("ows_Title"), 
                          unescape($(this).attr("ows_ListLibID")), 
                          $(this).attr("ows_PageURL"), 
                          $(this).attr("ows_SubsiteURL"), counter);
     itemArrayContainer.push(itemArray[counter]);
    }
   });
  }
 });
}

if (counter != 0) {   
 for (var j = 0; j < itemArrayContainer.length; j++) {
  sessionItem = "sessionItem" + (j + 1);
  sessionStorage.setItem(sessionItem, "");
 }
 function repeatEvery5Seconds() {
  for (var i = 0; i < itemArrayContainer.length; i++) {
   currentViewUser = itemArrayContainer[i][0];
   currentViewLLIB = itemArrayContainer[i][1]; 
   currentViewPURL = itemArrayContainer[i][2];
   currentViewSURL = itemArrayContainer[i][3];
   currentViewCOUNT = "sessionItem" + itemArrayContainer[i][4];
   fetchCurrentListStatus(currentViewLLIB, currentViewCOUNT);
  }
 }
 var t = setInterval(repeatEvery5Seconds,5000);
}
else {
 console.log('User "'+currentViewUser+'" is not in the subscribers list. '
             + 'Notifications will not be shown.');
}

function fetchCurrentListStatus(currentViewLLIB, currentViewCOUNT) {
 var listItemArray = new Array();
 var listItemArrayBackup = new Array();

 $().SPServices({
  operation: "GetListItems",
  async: false,     
  crossDomain: true,
  webURL: currentViewSURL,
     listName: currentViewLLIB,
  completefunc: function (xData, Status) {
   $(xData.responseXML).find("z\\:row, row").each(function() {
    var rowData = $(this).attr("ows_ID");
    listItemArray.push(rowData);
    listItemArrayBackup.push(rowData); 
   });
  }
 });
        
 if (listItemArray.length == null || listItemArray.length == 0) {
  console.log('List is empty.');
  sessionStorage.setItem(currentViewCOUNT, listItemArray);
 }
 else if (listItemArray.length != null || listItemArray.length != 0) {
  console.log('Server list: \t\t"' + listItemArray + '"');
  if ( sessionStorage.getItem(currentViewCOUNT).length != 0 
    || sessionStorage.getItem(currentViewCOUNT) != 0 
    || sessionStorage.getItem(currentViewCOUNT) != "" ) {
   tempArr = sessionStorage.getItem(currentViewCOUNT).split(",");
   console.log('Session list: \t\t"' + tempArr + '"');
   itemChange();
  }
  else if (sessionStorage.getItem(currentViewCOUNT).length == 0 
        || sessionStorage.getItem(currentViewCOUNT) == 0 
        || sessionStorage.getItem(currentViewCOUNT) == "" ) {
   sessionStorage.setItem(currentViewCOUNT, listItemArray);
   tempArr = sessionStorage.getItem(currentViewCOUNT).split(",");
   console.log('Session list: \t\t"' + tempArr + '"');
   itemChange();
  }
  if (tempArr.length == listItemArray.length) {
   console.log('No new item was added in the past 5 seconds.'
             + '\n--------------------------------------------------------'); 
  }
 }

 function itemChange() {
  if (listItemArray.length == tempArr.length) {}
  else if (listItemArray.length < tempArr.length) {
   console.log('An item was deleted. Now updating session storage.');
   sessionStorage.setItem(currentViewCOUNT, listItemArray);  
  }
  else if (listItemArray.length > tempArr.length) {
   console.log('An item has been added. Now updating session storage.'); 
   var array1 = listItemArray;
   var array2 = tempArr;
   var index;
   for (var i=0; i<array2 .length="" i="" if="" index=""> -1) {
           array1.splice(index, 1);
       }
   }
   var currentItemName;
   var newListItemArray = new Array(); 

   for (var i = 0; i < array1.length; i++) {
       var currentItem = array1[i];
     $().SPServices({
        operation: "GetListItems",
        ID: currentItem,
        async: false,
     crossDomain: true,
     webURL: currentViewSURL,
        listName: currentViewLLIB,
        completefunc: function (xData, Status) {
          $(xData.responseXML).SPFilterNode("z:row").each(function() {
             if ($(this).attr("ows_ID") == currentItem) {
                currentItemName = $(this).attr("ows_LinkFilename"); 
             }
          newListItemArray.push(currentItemName);
          });
       }
    });
   }

   var div = document.createElement("div");
   div.style.width = "auto";
   div.style.height = "21px";
   div.style.background = "#F7F7F7";
   div.style.color = "#3C82C7";
   div.style.border = "1px solid #d7d6d8";
   div.style.float = "right";
   div.style.padding = "5px";
   div.style.borderBottomLeftRadius = "4px";
   div.innerHTML = 'A document named "' + currentItemName 
                  + '" was added to <a href="' + currentViewPURL + '">' 
                  + currentViewLLIB + '</a>.';
   div.className = "notification";
   document.getElementById("notificationArea").appendChild(div);
   $(document.getElementsByClassName("notification")).hide();
   $(document.getElementsByClassName("notification")).fadeIn(1500);
   setTimeout(function() { 
    $(document.getElementsByClassName("notification")).fadeOut(1500);
    document.getElementById("notificationArea").removeChild(div);
   }, 5000);
   
   if (tempArr != listItemArray) {
    sessionStorage.setItem(currentViewCOUNT, listItemArrayBackup);
   }
  }
 }
}

function runInOtherFile() {
 console.log('Now running "runInOtherFile()". ');
 counter = 0;
 setTimeout(function() { 
 itemArrayContainerReplaced.length = 0;
  $().SPServices({
   operation: "GetListItems",
   async: false,        
   webURL: 'https://your-site-here.com/',
      listName: 'Subscribed users',
   completefunc: function (xData, Status) {
    $(xData.responseXML).SPFilterNode("z:row").each(function() {
     if ($(this).attr("ows_Title") == USER) {
      counter++;
      itemArrayReplaced[counter] = new Array($(this).attr("ows_Title"), 
                                   unescape($(this).attr("ows_ListLibID")), 
                                   $(this).attr("ows_PageURL"), 
                                   $(this).attr("ows_SubsiteURL"), counter);
      itemArrayContainerReplaced.push(itemArrayReplaced[counter]);
     }
    });
   }
  });
  console.log('List of subscribed users has been updated.'
            + '\n--------------------------------------------------------'); 
  itemArrayContainer = itemArrayContainerReplaced;
 }, 1000);
} 

function runDeleteInOtherFile() {
 for (var k = 0; k < itemArrayContainer.length; k++) {
  if (itemArrayContainer[k][1] == LLID) {
   var tempCurrentViewCOUNT = "sessionItem" + itemArrayContainer[k][4];
   sessionStorage.setItem(tempCurrentViewCOUNT, "");  // 0);
   itemArrayContainer.splice(k, 1);
  } 
 }
 console.log('Session corresponding to the list/library from which user ' 
            +'has unsubscribed is now empty.');
}

That's all the code. All of it. Everything you need to get fancy notifications. You can always change the style of the notification, it may be in the script but you can just personalize it in whatever way you want to.

Some screenshots

Console - when subscribed to two lists/libraries, first five seconds:

Console - when subscribed to two lists/libraries, after more than fifteen seconds:

Console - when a new item has been added to a list/library to which the current user is subscribed to:

Browser - notification the current user sees when a new item was added to a list/library to which the current user is subscribed to (translation: "A document named 'mouse-pointer.jpg' was added to TESTER."):

Console - when an item gets deleted from a list/library to which the current user is subscribed to:

Console - when the current user unsubscribes from a list/library (it's the one with the long array of ID's):

Console - when the current user subscribes to a list/library (again, the one with the long array of ID's):

Browser - the buttons; there is only one button per list but I used an image editor to place these next to each other, just to demonstrate:

The end

That was it, the whole blog post. My longest one so far I believe. I hope I explained things clear enough, I did my best to tell you every bit of information I have about these scripts. I hope that one day I'll be able to rewrite this functionality in C#, to make it server-side. But until that day, I'm happy with this and I hope you are happy with it too. :)

Do let me know if you are having trouble or problems with one of the scripts and I'll do my best to help you out.

As an extra tip, I suggest you minify the scripts and get rid of all console logs. Just to make it less
heavy.

Enjoy!

Wednesday, February 12, 2014

How to have a discussion board web part with modal dialogs and auto-refreshing content in SharePoint 2013

Imagine you added a discussion board as a web part to a page. Whenever you want to add a new discussion, by default it will always open in a new page rather than in a modal dialog (even if you ticked the "Display forms in a modal dialog" option under "Advanced settings" of the discussion board). As a matter of fact, existing discussions also open in new pages.

For my end users, this is annoying since they will lose track of the page they were originally on. I made it so that they will always know on what page they are, by highlighting the link of the current page in the term-driven subsite navigation. And when they want to create a new discussion or want to look at an existing one, that term-driven subsite navigation can't tell you the path of the "AllItems.aspx" page your user has ended on.

So! In order to stick to the page that has the discussion board web part, I had to write a small script.

How do we create a new discussion or open an existing discussion in a dialog rather than on a new page?

You'll need two scripts for this: one that runs only on the page that has the discussion board web part, and one that is referenced on the master page (so that it will always run, on any page, regardless whether it has a discussion board or not).

I named the first script "discussion-board.js" and gave it the following code. Comments have been added to the code to further explain it.
// When called, this function opens the dialog.
function openDialog(pUrl) { 
   var options = {
      url : pUrl,
      dialogReturnValueCallback: OnDialogClose
   };
   SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', 
    options);
}

// When the user closes the dialog by either pressing OK when adding a new 
// item, by clicking the cancel button or by closing it with the X on the 
// top right corner, this function will run.
function OnDialogClose(dialogResult, returnValue) {
   // The line below will refresh the content of the web part, by acting as 
   // if the refresh button was clicked. 
   $('.ms-comm-refreshIcon').trigger('click');
   // The line below will run the clickMe() function, I also added a timeout
   // because I noticed that it sometimes doesn't run properly. This timeout 
   // should make sure that the function will always run. 
   clickMe();
   setTimeout(function() { 
      clickMe();
   }, 500);
}

// When called, this function makes sure that a new discussion or an existing
// discussion is opened in a modal dialog instead of on a new page.
function clickMe() {
   // The lines below replaces the value of the default onclick and href
   // attributes so that it won't open on a new page, but in a dialog. 
   $('a[href*="NewForm.aspx"]').each(function() {
      $(this).attr('onclick', 'openDialog("' +  $(this).attr('href') + '")');
      $(this).attr('href','javascript:void(0)');
   });
   // Same for the following lines, when the user is on the page that 
   // contains the discussion board web part, we want the existing 
   // discussions to be displayed in a dialog as well rather than on a new 
   // page. 
   $('a[href*="Forum.aspx"]').each(function() {
      $(this).attr('onclick', 'openDialog("' +  $(this).attr('href') + '")');
      $(this).attr('href','javascript:void(0)');
   });
}

// When the window first loads, we want to be sure that the discussions are 
// already set to open in a dialog. So we will run the clickMe() function on
// load, and set the timeout again just to be sure (in my case, it doesn't 
// work without the timeout).
window.onload = function () {
   clickMe();
   setTimeout(function() { 
      clickMe();
   }, 500);
}; 

// The lines below are needed as well, because when a user changes the view 
// of the web part (to for example "Recent" or "My discussions"), then the
// values of the attributes  href and onclick get back their original value.
// We don't want a user to see the discussions on a new page, so we once 
// again set it so that the clickMe() function runs as soon as the user 
// clicks anywhere inside the content div (which in my case, has "content" 
// for its ID. 
$("#content").click(function() {
   clickMe();
   setTimeout(function() {
      clickMe();
   }, 500);
});

So that's the first script that you'll need. Include this script to the page that contains the discussion board web part. Do so by adding a script editor web part at the bottom of the page and add the following code tot it:
<script src="/Style%20Library/Scripts/discussion-board.js" 
 type="text/javascript"></script>

Please do note that your path may be different, so change it if necessary.

And now for the script that has to have a reference on the master page. I already have a file called "scripts.js" which runs on every page, so I just added the following code to that script:
var ref = document.referrer; 
var url = window.location.pathname; 
$(document).ready(function(){
   // If the current url ends with "AllItems.aspx" and the previous url 
   // contained "IsDlg=", stating that it was a dialog, then run the 
   // following code. 
   if ( (url.indexOf('AllItems.aspx') > -1 && ref.indexOf('IsDlg=') > -1) ) {
      // The line below will close the dialog. 
   SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
   }
   else {
      // Do nothing.
   }
});

The reason why we have to state that the dialog has be closed, is because when you delete a discussion through a modal dialog, it will show you the AllItems.aspx page inside the dialog instead of returning to the original page (in my case, Forum.aspx). So to fix this, I check if the dialog came from a page that had "IsDlg=" in the url, and if the url of the dialog is currently "AllItems.aspx" then that must mean that a discussion was deleted. So then we can close the dialog.

Check if your second script is added to your master page. I use a HTML master page so my reference looks like this:
<!--SPM:<SharePoint:ScriptLink language="javascript" OnDemand="false"
  name="~sitecollection/Style Library/Scripts/scripts.js"
  ID="scriptLink4" runat="server" Localizable="false"/>-->

Again, do note that your path may be different, so change it where necessary.

If you did everything as I explained it here, you will now have a discussion board web app on a page that will:
  • open all existing discussions in a modal dialog;
  • open all new discussions in a modal dialog;
  • automatically refresh the content of the web part whenever a new discussion is adde;
  • automatically refresh the content of the web part whenever an existing discussion has been edited or deleted;
  • returns to the page with the web part and closes the dialog after deleting a discussion.

As always, if you have any questions or need any help do let me know by placing a comment!
This post can also be found as an answer on SharePoint StackExchange.

Tuesday, January 28, 2014

IT'S OVER ONE THOUSAAAAAAAAAAND!!!!

My blog just got over one thousand views!!! 

 

Hurray!!! 

 

Confetti for everyone!!!

 

I probably just viewed my own blog so many times that I'm now up to one thousand. Although I did set it so that my own views wouldn't count. But meh, /care, one thousand views!

Also, someone actually clicked on the advertisement box on the right. Which gave me a very tiny small amount of eurocents, but still money nonetheless!
So if you happen to stumble upon this post, could you like... Just... Do a tiny click on that advertisement box on your right? Yeah. That one, right underneath the "Subscribe to" thingy. It won't cost you a thing, it won't do any harm either, but it will give me a (once again) very tiny small amount of money, which in return makes me a very tiny bit more happier each time someone clicks it.

And who knows, it might even be interesting! I have no idea what the advertisement box tells you, it is supposed to show you advertisements that are relevant to whatever business you searched for on Google. In my case it shows me something in French about becoming a florist, although I have absolutely no idea why it would show something like that since I never even searched for flowers online. Peculiar.


I think I'll keep making posts like these every time my views increase by a thousand. Eventually, I'll get to 9000. And you should know what that means. Oh boy, do I look forward to that moment... That will be one heck of a post.

Friday, January 24, 2014

My new favourite syntax highlighter: Prism!

The past few days, I noticed some parts of my code were missing in the Syntax Highlighter and that sometimes, the code wasn't shown in the highlighter at all (it was just dull text). When I edited the affected blog posts however, the missing pieces of code were there and so were the elements for the highlighter. So I figured it might have had to do something with the Syntax Highlighter.

I decided to search for a new highlighter, and came across Prism. This is a very neat highlighter, it is lightweight and extensible, offers six different styles, has various plugins and is supported by most browsers.
For my blog, I'm using the Prism highlighter with the Okaidia theme and I also included the Line Numbers plugin. 

How to use Prism on Blogger/Blogspot

First of all, I discovered that I couldn't host JavaScript files on Blogger/Blogspot. Secondly, I didn't like the idea of hosting scripts elsewhere. I tried hosting it on Google Drive and that sort of worked, but still I wanted to find an easier way.
So I checked the source of prismjs.com and its pages, searched for the scripts and found them there. Not quite sure if I'm allowed to do that... But it was easier for me and I think those will always be the most up-to-date scripts. 
This is the core JavaScript code of Prism. 
This is the JavaScript code for the line numbers plugin.
This is the CSS code for the line numbers plugin.
And this is the CSS code for the Okaidia theme.

I'm not going to provide the link to all the scripts, plugins and themes for Prism since you can probably find most of them yourself by changing the URLs a bit or by doing a search through the source code of the site. 

Now that we have the necessary files, we need to include them to the template. 
To add them, you need to edit the HTML of your template. You can do so by going to the settings of your blog, select "Template" from the left hand side navigation, and then choose "Edit HTML". 

Right before the </head> tag, you paste the following code (source of the scripts may be different depending on which plugins or styles you use):
<script src='http://prismjs.com/prism.js' type='text/javascript'/>
<script src='http://prismjs.com/plugins/line-numbers/prism-line-numbers.js' 
type='text/javascript'/>
<link 
href='http://prismjs.com/themes/prism-okaidia.css' rel='stylesheet'/>
<link 
href='http://prismjs.com/plugins/line-numbers/prism-line-numbers.css' 
rel='stylesheet'/>

Now, when you create a new blog post and you wish to add code to it, you can use the following to highlight your code:
<pre class="line-numbers"><code class="language-javascript">
// Your code here.
</code></pre>

Do note that depending on which plugins you have, you can change the class in the pre tag. You can read more about the different plugins and how to use them here. Also, depending on what kind of code you will be highlighting, you can change the class in the code tag.
To highlight CSS, use language-css class for the code tag.
To highlight HTML, use language-markup class for the code tag.
To highlight JavaScript, use language-javascript class for the code tag.

Got code that's not showing up? No problem. We can fix this. 

I noticed that if you want to use HTML code inside JavaScript (or even script tags in JavaScript), the code will likely not show. I think this might be related to HTML being stripped off. For example, see the following code:
var site = "www.prismjs.com";
var title = "PrismJS";
var text = "" + title + "";

Noticed anything strange? I surely did. I added an anchor tag to that code, yet it is not showing.
Let me show you the same code, but now I changed the "less than" character ("<") with "&lt;" and this is the result:
var site = "www.prismjs.com";
var title = "PrismJS";
var text = "<a href='" + site + "'>" + title + "</a>";

Bam! Suddenly the code works. Just to give you an idea, this is how it looks like (and how I write it in order for it to show up properly) when I edit the blog post with the code:
var site = "www.prismjs.com";
var title = "PrismJS";
var text = "&lt;a href='" + site + "'>" + title + "&lt;/a>";

So when you use HTML inside JavaScript, or even when you use "<script></script>" tags or regular expressions, always make sure to replace the "less than" character with "<". That way, no code will be missing from the highlighter and visitors will be able to correctly copy and use your code.

All done! Let's start making more blog posts now!

Now that I finally have a syntax highlighter that does what I want it to do, I can continue writing blog posts about my SharePoint experiences without having to worry about visitors not seeing my code. ^_^

I would like to thank Lea Verou and all these people who created Prism, without them I would probably still struggle with highlighting stuff. Please do check out Prism, I highly recommend it for Blogger/Blogspot or any other site.

Thursday, January 23, 2014

How to get a term-driven breadcrumb trail with full hierarchy in SharePoint 2013

On the 6th of May, 2013, I had asked a question on Stack Overflow on how one could create a term-driven hierarchical breadcrumb trail in SharePoint 2013. Alas, never really got an answer that suited my needs.

Yesterday, I suddenly had the idea to just try and find a solution with JavaScript. The idea was to loop through the subsite navigation and see which list item resembled the current page, then find all the parent elements of that list item and fetch their values. And in case I was on a page that wasn't part of a subsite (but rather just a page at the top site collection), I would just fetch the title of the page and add that to the breadcrumb trail.

Here's a screenshot of how my breadcrumb looked like earlier:



And here's a screenshot of how it looks like now:



Pretty nice, huh?

Let's just get started, I'll give you the code.

The code

// Just add the following line.
SP.SOD.executeOrDelayUntilScriptLoaded("SP.UserProfiles.js", 
   "~sitecollection/Style Library/Scripts/jquery.SPServices-2013.01.js");

var siteCollection = "Your site collection name";
var siteCollectionUrl = "/";     
var pageName; 
var subsite;
// Fetch the name of the subsite you're currently on.
$().SPServices({
    operation: "SiteDataGetWeb",
    async: false,
  completefunc: function (xData, Status) {
   subsite = $(xData.responseXML).SPFilterNode("Title").text();
  }
});
// Fetch the url of the subsite you're currently on.
var subsiteUrl = $().SPServices.SPGetCurrentSite();
// Fetch the title of the page, remove a piece of text from the title
// (in my case, "Pages - "), then remove any white spaces before and 
// after the title.
var pageTitle = document.getElementsByTagName("title")[0].innerHTML
   .replace("Pages - ", "").replace(/^\s\s*/, "").replace(/\s\s*$/, "");

// If the current site is the same as the site collection (meaning it is
// not a subsite), then use the url of the current page.
if (subsite == siteCollection) {
 // Create the string that will contain the breadcrumb trail.
 var text = "<a href='" + siteCollectionUrl + "'>" + siteCollection 
 + "</a> > <a href='" + document.URL + "'>" + pageTitle + "</a>";
}
// In any other case, use the url of the subsite. 
else {
 // Create the string that will contain the breadcrumb trail.
 var text = "<a href='" + siteCollectionUrl + "'>" + siteCollection 
 + "</a> > <a href='" + subsiteUrl + "'>" + subsite + "</a>";
}

$(function runMe() {
 // Set the ID of your subsite navigation. 
 var $this = $("#NavRootAspMenu");
 if($this != null) {
  // Remove the class "static" from the last item in the navigation 
  // (because it(s a link to edit the navigation) and remove the last
  // child element (since this doesn't have a href attribute).
  $(".ms-listMenu-editLink").removeClass("static");
  $("ul[id*='RootAspMenu'] li.ms-navedit-editArea:last-child").remove();
  $this.find("li").each(function(i){
   var elem = $($this).find("li.static")[i]; 
   // If elem finds an anchor tag that contains the following class, then
   // add a new class. We'll use this class for the parent elements.
   if ($(elem).find("a").hasClass("ms-core-listMenu-selected")) {
    $(elem).addClass("parentSelected");
   }  
  });  
  // If the subsite navigation contains elements with the class 
  // "parentSelected" and that element contains an anchor, a span and
  // another span with the class "menu-item-text", then for each of those
  // elements do the following. 
  $this.find(".parentSelected > a span span.menu-item-text")
   .each(function(j) { 
   $(this).addClass("bcn");  //bcn = breadcrumbnode
   var crumbLink = $($this).find(".parentSelected > a")[j].href;
   var crumbName = $("span.bcn")[j].innerHTML;
   // If the link equals the url of the site collection, then this list
   // item is a category and it does not require an anchor tag.
   if (crumbLink == "https://your-site-collection.com/") {
    text = text + " > " + crumbName;
   }
   // In any other case, this list item has a page and we will add an
   // anchor tag to the breadcrumb trail. 
   else {
   text = text + " > <a href='" + crumbLink + "'>" + crumbName + "</a>";
   }
  });
 }
// When we ran through the navigation, apply the new breadcrumb trail to
// the element in the master page. 
document.getElementById("customBreadcrumb").innerHTML = text;
});

You'll also need to have the jQuery library for SharePoint Web Services, you can find it here.
In order for our code to work properly, we will need to replace some code from the master page and add a reference to the breadcrumb script on the master page. Be sure to read the JavaScript code first, you will need to fill in a name for your site collection (var siteCollection) and give the url of your site collection followed by a slash (var crumbLink).

Adding a reference to the master page

If we want to apply this code on the site collection and all subsites, then we should add a reference to our script in the master page. Please do note that I'm using a HTML master page. This is the code you should add:
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink1"
runat="server" name="~sitecollection/Style Library/Scripts/breadcrumb.js"
OnDemand="false" Localizable="false"/>-->

Do note that the ID might be different. You must make sure that you do not already have a scriptlink with the same ID, so change the number of the ID and make it unique.
Also, the name (path to your script) might be different. Make sure that it matches the path of where your script is located.

Replacing code in the master page

Next, we need to replace some code in the master page. In my HTML master page, I replaced any piece of code that had to do with the breadcrumb. Just to give you an idea, the following pieces of code are the ones that I REMOVED from my master page:
<!--SPM:<asp:sitemappath runat="server" 
 sitemapproviders="SPSiteMapProvider,SPXmlContentMapProvider" 
 rendercurrentnodeaslink="true" 
 nodestyle-cssclass="breadcrumbNode" 
 currentnodestyle-cssclass="breadcrumbCurrentNode" 
 rootnodestyle-cssclass="breadcrumbRootNode" 
 hideinteriorrootnodes="false"
 SkipLinkText=""/>-->
<!--SPM:<SharePoint:AjaxDelta id="DeltaPlaceHolderPageTitleInTitleArea" 
 runat="server">-->
<!--SPM:</SharePoint:AjaxDelta>-->
<!--SPM:<SharePoint:AjaxDelta BlockElement="true" 
 id="DeltaPlaceHolderPageDescription" CssClass="ms-displayInlineBlock 
 ms-normalWrap" runat="server">-->
 <a href="javascript:;" id="ms-pageDescriptionDiv" 
  style="display: none;">
  <span id="ms-pageDescriptionImage"></span>
 </a>
 <span class="ms-accessible" id="ms-pageDescription">
  <!--SPM:<asp:ContentPlaceHolder id="PlaceHolderPageDescription" 
   runat="server"/>-->
 </span>
 <!--SPM:<SharePoint:ScriptBlock runat="server">-->
  <!--SPM:_spBodyOnLoadFunctionNames.push("setupPageDescriptionCallout");-->
 <!--SPM:</SharePoint:ScriptBlock>-->
<!--SPM:</SharePoint:AjaxDelta>-->

It is very important that you keep the following code in your master page, but wrap something around it with a class. Like so:
<span class="hideDefaultBreadcrumb">
 <!--SPM:<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" 
  runat="server">-->
  <!--SPM:<SharePoint:SPTitleBreadcrumb runat="server"
   RenderCurrentNodeAsLink="true"
   SiteMapProvider="SPContentMapProvider"
   CentralAdminSiteMapProvider="SPXmlAdminContentMapProvider">-->
   <!--SPM:<pathseparatortemplate>-->
    <!--SPM:<SharePoint:ClusteredDirectionalSeparatorArrow 
     runat="server"/>-->
   <!--SPM:</PATHSEPARATORTEMPLATE>-->
  <!--SPM:</SharePoint:SPTitleBreadcrumb>-->
 <!--SPM:</asp:ContentPlaceHolder>-->
</span>

Then add the class to your style sheet:
.hideDefaultBreadcrumb {
 display: none;
}

The reason that we must keep this content placeholder, is that otherwise you'll suddenly miss a great portion of the "Apps you can add". I forgot about this at first and then suddenly had only three apps left, but after reading about it here I learned that I should have left in the content placeholder with ID PlaceHolderPageTitleInTitleArea. So that's fixed now.

I also removed a span with the ID "ctl00_DeltaPlaceHolderPageTitleInTitleArea" in the master page.

Bear in mind that your code might be different from mine, so always check your site with source view in your browser, to see the ID's and classes of the elements in the breadcrumb.
Now, ADD the following code to the location of where you just removed the piece of code that was previously your breadcrumb:
<span id="customBreadcrumb"></span>

In that tiny span, your breadcrumb trail will appear. This will be dynamically filled with text and links once your script is running.

Make sure your master page and your script are checked in. Now you can finally see the full breadcrumb trail, with the correct hierarchy!
No need to deploy solutions, no need to find a workaround or use webparts to do the trick, just some simple JavaScript is all you need. ;)

Enjoy!