Skip to content

Instantly share code, notes, and snippets.

@phillipharding
Created January 10, 2020 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipharding/8d77a72f9750284287a5324e048dce9c to your computer and use it in GitHub Desktop.
Save phillipharding/8d77a72f9750284287a5324e048dce9c to your computer and use it in GitHub Desktop.
To export
importSnippets = [
{
"id": "2",
"name": "Print Display ListForm using Dialog",
"content": "function onListFormPrintViewDialogClosed(dialogResult, returnValue) {\n console.log(\"Print View Dialog closed, result: \" + dialogResult);\n}\n\nfunction showListFormPrintViewDialog(e) {\n e.preventDefault();\n var formUrl = e.data && e.data.url && e.data.url.length ? e.data.url : '';\n if (e.data && (!e.data.url && !e.data.url.length)) {\n /* no url supplied, get the DispForm url for the current listitem form */\n var formCtxName = ($(\"*[id$='ClientFormPlaceholder']\")\n .attr('id')\n .replace(/ClientFormPlaceholder/gi,'')) || \"\";\n var formCtx = window[formCtxName+\"FormCtx\"];\n var listItemId = formCtx && formCtx.ItemAttributes\n ? formCtx.ItemAttributes.Id \n : 0;\n formUrl = formCtx.RedirectInfo\n ? formCtx.RedirectInfo.listRootFolderUrl + \"/DispForm.aspx?ID=\" + listItemId\n : \"\";\n }\n\n /* set dialog options and call dialog */\n var dialogOptions = {\n url: formUrl + \"&IsDlg=1\",\n title: (e.data && e.data.dialogTitle && e.data.dialogTitle.length)\n ? e.data.dialogTitle\n : \"Dialog Title\",\n showClose: true,\n allowMaximize: false,\n height: document.body.scrollHeight,\n width: document.body.scrollWidth,\n autoSize: false,\n dialogReturnValueCallback: onListFormPrintViewDialogClosed\n };\n /* add optional parameters as supplied on the click binding, \n only \"e.data.printMode\", \"e.data.url\", \"e.data.autoPrintDelay\" and \n \"e.data.dialogTitle\" have special meaning (see above/below) */\n if (e.data) {\n var opts = [];\n for(var n in e.data) {\n opts.push(n+'='+e.data[n]);\n }\n dialogOptions.url = dialogOptions.url + \"&\" + opts.join('&');\n }\n console.log(\"Print View Dialog url: \" + dialogOptions.url);\n SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.showModalDialog', dialogOptions);\n\n /* add dialog loaded handler */\n var dlgFrame = SP.UI.ModalDialog.get_childDialog().get_frameElement();\n $addHandler(dlgFrame, \"load\", function() {\n console.log(\"Print View Dialog loaded...\");\n var $dialogBody = $(dlgFrame.contentWindow.document.body);\n $dialogBody.find(\"#s4-ribbonrow\").addClass('hidden');\n $dialogBody.find(\"#s4-workspace\").addClass('dialog-print-view');\n\n /* auto print the dialog? */\n if (e.data && e.data.printMode && e.data.printMode.match(/auto/gi)) {\n console.log('Print View Dialog, auto print in '+(e.data.autoPrintDelay || 5000)+' seconds');\n setTimeout(function() {\n try {\n console.log('Print View Dialog, about to print...');\n dlgFrame.contentWindow.print();\n } catch (e) {\n alert(\"Unable to Print this View: \" + e);\n }\n }, e.data.autoPrintDelay || 5000);\n }\n });\n\n return false;\n}\n$(\"#btnPrint\").off(\"click\");\nvar options = {\n printMode: \"auto\", \n autoPrintDelay: 4000, \n dialogTitle: \"Print Project Request\",\n url: \"\",\n /* add any other parameters to send to the dialog url, as query-string parameters */\n arg1: \"arg1 value\",\n arg2: \"arg2 value\"\n};\n$(\"#btnPrint\").on(\"click\", options, showListFormPrintViewDialog);"
},
{
"id": "3",
"name": "Print Current Form using Dialog",
"content": "function showListFormPrintViewDialog(e) {\n e.preventDefault();\n\n var html = [];\n if (e.data && e.data.selector && e.data.selector.length) {\n html.push($(e.data.selector).html());\n }\n var dialogWrapperDiv = null;\n dialogWrapperDiv = document.createElement('DIV');\n dialogWrapperDiv.classList = \"dialog-print-view\";\n dialogWrapperDiv.innerHTML = html.join('');\n /* set dialog options and call dialog */\n var dialogOptions = {\n html: dialogWrapperDiv,\n title: (e.data && e.data.dialogTitle && e.data.dialogTitle.length)\n ? e.data.dialogTitle\n : \"Dialog Title\",\n showClose: true,\n allowMaximize: false,\n height: document.body.scrollHeight,\n width: document.body.scrollWidth,\n autoSize: false,\n dialogReturnValueCallback: function (dialogResult, returnValue) {\n console.log(\"Print View Dialog closed, result: \" + dialogResult);\n if (e.data && e.data.hideSelector && e.data.hideSelector.length) {\n $(e.data.hideSelector).show();\n }\n }\n };\n console.log(\"Print View Dialog url: \" + dialogOptions.url || '');\n SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.showModalDialog', dialogOptions);\n if (e.data && e.data.hideSelector && e.data.hideSelector.length) {\n $(e.data.hideSelector).hide();\n }\n\n console.log(\"Print View Dialog loaded...\");\n /* auto print the dialog? */\n if (e.data && e.data.printMode && e.data.printMode.match(/auto/gi)) {\n console.log('Print View Dialog, auto print in '+(e.data.autoPrintDelay || 5000)+' seconds');\n setTimeout(function() {\n try {\n console.log('Print View Dialog, about to print...');\n window.print();\n } catch (e) {\n alert(\"Unable to Print this View: \" + e);\n }\n }, e.data.autoPrintDelay || 5000);\n } \n\n return false;\n}\n\n$(\"#btnPrint\").off(\"click\");\nvar options = {\n printMode: \"auto\",\n autoPrintDelay: 2000,\n arg1: \"arg1 value\",\n selector: \"#DeltaPlaceHolderMain\",\n hideSelector: \"#s4-workspace\",\n dialogTitle: \"Print Project Request\"\n};\n$(\"#btnPrint\").on(\"click\", options, showListFormPrintViewDialog);"
},
{
"id": "4",
"name": "SetWebPropertyByCSOM",
"content": "SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"sp.js LOADED!!!!\");\n\n propertyName=\"FerreroNpdPackagingCostThreshold\";\n propertyValue=100.29.toFixed(2);\n ctx = SP.ClientContext.get_current();\n web = ctx.get_web();\n props = web.get_allProperties();\n props.set_item(propertyName, propertyValue || \"\");\n web.update();\n ctx.load(web);\n ctx.executeQueryAsync(function() {\n console.log(`Set WebProperty: ${propertyName} to ${propertyValue} - Done!`);\n }, function(s,args) {\n console.log(`Set WebProperty Error: ${args.get_message()}`);\n });\n\n})"
},
{
"id": "5",
"name": "LoadWebPropertiesByCSOM",
"content": "SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"sp.js LOADED!!!!\");\n\n ctx = SP.ClientContext.get_current();\n web = ctx.get_web();\n props = web.get_allProperties();\n ctx.load(props);\n ctx.executeQueryAsync(function() {\n console.log(\"Load WebProperties - Done!\");\n console.log(props);\n }, function(s,args){ \n console.log(`Load WebProperties Error: ${args.get_message()}`);\n });\n});"
},
{
"id": "6",
"name": "ShowCurrentPagePrintViewNoDialog",
"content": "function showPagePrintViewNoDialog(options) {\n\n if (options && (!options.hideSelector || !options.hideSelector.length)) {\n options.hideSelector = \"#s4-workspace\";\n }\n\n var restoreStyle='';\n var html = ['<div style=\"position:absolute;width:100%;height:calc(100% - 45px);background-color:transparent;z-index:1;box-sizing:border-box;top:45px;left:0;\"></div>'];\n html.push(String.format('<div class=\"ms-dlgTitle\" style=\"padding-left: 0;border-bottom: 1px dashed #cdcdcd;padding-bottom: 5px;margin-bottom: 5px;\"><span id=\"dlgTitleBtns\" style=\"margin-top: -10px;margin-right: -18px;\" class=\"ms-dlgTitleBtns\"><a id=\"dialog-print-view-container-close\" class=\"ms-dlgCloseBtn\" title=\"Close dialog\" href=\"javascript:;\" accesskey=\"C\"><span style=\"padding:8px;height:16px;width:16px;display:inline-block\"><span style=\"height:16px;width:16px;position:relative;display:inline-block;overflow:hidden;\" class=\"s4-clust\"><img src=\"/_layouts/15/images/fgimg.png?rev=44\" alt=\"Close dialog\" style=\"left:-0px !important;top:-645px !important;position:absolute;\" class=\"ms-dlgCloseBtnImg\"></span></span></a></span><h1 title=\"{0}\" class=\"ms-dlgTitleText ms-accentText ms-dlg-heading\" id=\"dialogTitleSpan\" style=\"\">{0}</h1></div>', \n (options && options.dialogTitle && options.dialogTitle.length)\n ? options.dialogTitle\n : \"Dialog Title\"));\n\n if (options && options.selector && options.selector.length) {\n var chtml = $(\"<div>\").append($(options.selector).clone()).html();\n html.push(chtml);\n }\n var dialogWrapperDiv = null;\n dialogWrapperDiv = document.createElement('DIV');\n dialogWrapperDiv.classList = \"dialog-print-view\";\n dialogWrapperDiv.innerHTML = html.join('');\n var $printContent = $(dialogWrapperDiv);\n $printContent.attr(\"style\", \"margin: 5px 0;width: 95%;padding: 0 10px 0 10px;border: 1px solid #cdcdcd;overflow-y: auto;height: auto;position: absolute;transform: translateX(-50%);left: 50%;\");\n $printContent\n .attr(\"id\", \"dialog-print-view-container\");\n /*.attr(\"height\", document.body.scrollHeight-(50+35+10));*/\n $(\"body\").css(\"overflow-y\",\"scroll\");\n\n try {\n restoreStyle = $(options.hideSelector).attr(\"style\");\n $printContent.insertAfter($(options.hideSelector));\n $(options.hideSelector).hide();\n } catch (e) {\n }\n\n $(\"#dialog-print-view-container-close\").click(function(e) {\n e.preventDefault();\n $(\"body\").css(\"overflow-y\",\"\");\n $(\"#dialog-print-view-container\").remove();\n $(options.hideSelector).show();\n $(options.hideSelector).attr(\"style\", restoreStyle);\n });\n\n console.log(\"Print View Dialog loaded...\");\n /* auto print the dialog? */\n if (options && options.printMode && options.printMode.match(/auto/gi)) {\n console.log('Print View Dialog, auto print in '+(options.autoPrintDelay || 5000)+' seconds');\n setTimeout(function() {\n try {\n console.log('Print View Dialog, about to print...');\n window.print();\n } catch (e) {\n alert(\"Unable to Print this View: \" + e);\n }\n }, options.autoPrintDelay || 5000);\n } \n}\n\n$(\"#btnPrint\").off(\"click\");$(\"#btnPrint\").off(\"click\");$(\"#btnPrint\").off(\"click\");\n$(\"#btnPrint\").click(function(e) {\n e.preventDefault();\n\n var options = {\n printMode: \"auto\",\n autoPrintDelay: 2000,\n arg1: \"arg1 value\",\n selector: \"#form-container\",\n hideSelector: \"#s4-workspace\",\n dialogTitle: \"Print Project Request\"\n };\n showPagePrintViewNoDialog(options);\n});"
},
{
"id": "7",
"name": "Script snippet #7",
"content": "function onListFormPrintViewDialogClosed(dialogResult, returnValue) {\n console.log(\"Print View Dialog closed, result: \" + dialogResult);\n}\n\nfunction showListFormPrintViewDialog(e) {\n e.preventDefault();\n var formUrl = e.data && e.data.url && e.data.url.length ? e.data.url : '';\n if (e.data && (!e.data.url && !e.data.url.length)) {\n /* no url supplied, get the DispForm url for the current listitem form */\n var formCtxName = ($(\"*[id$='ClientFormPlaceholder']\")\n .attr('id')\n .replace(/ClientFormPlaceholder/gi,'')) || \"\";\n var formCtx = window[formCtxName+\"FormCtx\"];\n var listItemId = formCtx && formCtx.ItemAttributes\n ? formCtx.ItemAttributes.Id \n : 0;\n formUrl = formCtx.RedirectInfo\n ? formCtx.RedirectInfo.listRootFolderUrl + \"/DispForm.aspx?ID=\" + listItemId\n : \"\";\n }\n\n /* set dialog options and call dialog */\n var dialogOptions = {\n url: formUrl + \"&IsDlg=1\",\n title: (e.data && e.data.dialogTitle && e.data.dialogTitle.length)\n ? e.data.dialogTitle\n : \"Dialog Title\",\n showClose: true,\n allowMaximize: false,\n height: e.data.height || document.body.scrollHeight,\n width: e.data.width || document.body.scrollWidth,\n autoSize: false,\n dialogReturnValueCallback: onListFormPrintViewDialogClosed\n };\n /* add optional parameters as supplied on the click binding, \n only \"e.data.printMode\", \"e.data.url\", \"e.data.autoPrintDelay\" and \n \"e.data.dialogTitle\" have special meaning (see above/below) */\n if (e.data) {\n var opts = [];\n for(var n in e.data) {\n opts.push(n+'='+e.data[n]);\n }\n dialogOptions.url = dialogOptions.url + \"&\" + opts.join('&');\n }\n console.log(\"Print View Dialog url: \" + dialogOptions.url);\n SP.SOD.execute('SP.UI.Dialog.js', 'SP.UI.ModalDialog.showModalDialog', dialogOptions);\n\n /* add dialog loaded handler */\n var dlgFrame = SP.UI.ModalDialog.get_childDialog().get_frameElement();\n $addHandler(dlgFrame, \"load\", function() {\n console.log(\"Print View Dialog loaded...\");\n var $dialogBody = $(dlgFrame.contentWindow.document.body);\n $dialogBody.find(\"#s4-ribbonrow\").addClass('hidden');\n $dialogBody.find(\"#s4-workspace\").addClass('dialog-print-view');\n\n /* auto print the dialog? */\n if (e.data && e.data.printMode && e.data.printMode.match(/auto/gi)) {\n console.log('Print View Dialog, auto print in '+(e.data.autoPrintDelay || 5000)+' seconds');\n setTimeout(function() {\n try {\n console.log('Print View Dialog, about to print...');\n dlgFrame.contentWindow.print();\n } catch (e) {\n alert(\"Unable to Print this View: \" + e);\n }\n }, e.data.autoPrintDelay || 5000);\n }\n });\n\n return false;\n}\n$(\"a[href$='SPBookmark_AuditTrail']\").off(\"click\");\n$(\"a[href$='SPBookmark_AuditTrail']\").on(\"click\", function(e) {\n e.preventDefault();\n var $this = $(this);\n var id = $this.attr(\"href\").split('&')[2].split('#')[0].split('=')[1];\n var options = {\n height: document.body.scrollHeight * 0.50,\n width: document.body.scrollWidth * 0.80,\n printMode: \"off\", \n autoPrintDelay: 4000, \n dialogTitle: \"Project Audit Trail\",\n url: String.format(\"{0}/Lists/NPD Requests/DispForm.aspx?ID={1}&formAction=audittrail\", \n _spPageContextInfo.webServerRelativeUrl.replace(/\\/$/gi, ''),\n id),\n };\n showListFormPrintViewDialog({ data: options, preventDefault: function() {} });\n});"
},
{
"id": "8",
"name": "Script snippet #8",
"content": "class Polygon {\n constructor(height, width) {\n this._name = 'Polygon';\n this._height = height;\n this._width = width;\n }\n\n get width() {\n return this._width;\n }\n set width(w) {\n this._width = w;\n }\n\n sayName() {\n console.log('Hi, I am a ', this._name + ' <-> ' + this._width);\n }\n\n sayHistory() {\n console.log('\"Polygon\" is derived from the Greek polus (many) ' +\n 'and gonia (angle).');\n }\n\n}\n\nlet o = new Polygon(100,200);\no.sayName();"
},
{
"id": "9",
"name": "O365 WorkManagement",
"content": "/*\nhttp://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.workmanagement.client(v=office.15).aspx\nhttps://msdn.microsoft.com/en-us/library/office/microsoft.sharepoint.workmanagement.client(v=office.15).aspx\nhttp://www.lifeonplanetgroove.com/mytasks-workmanagement-task-aggregation-apis-sharepoint-online/\n*/\nvar context;\nvar userSessionManager;\nvar userSession;\nvar query;\nvar myTasks;\n \nfunction getMyTasks() {\n context = new SP.ClientContext.get_current();\n userSessionManager = new SP.WorkManagement.OM.UserOrderedSessionManager(context);\n userSession = userSessionManager.createSession();\n query = new SP.WorkManagement.OM.TaskQuery(context);\n myTasks = userSession.readTasks(query);\n\n context.load(myTasks);\n context.executeQueryAsync(onGetMyTasksSuccess, onGetMyTasksFail);\n}\n \n// On Failure\nfunction onGetMyTasksFail(sender, args) {\n console.log('Failed to get tasks. Error:' + args.get_message());\n}\n \n// On Success\nfunction onGetMyTasksSuccess() {\n console.log(\"Successfully retrieved tasks...\");\n var taskEnumerator = myTasks.getEnumerator();\n while (taskEnumerator.moveNext()) {\n var task = taskEnumerator.current;\n console.log(\"Task: \" + task.get_id() + \" - \" + task.get_name());\n }\n}\n\nfunction start() {}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"SP.JS LOADED!!!!\");\n\n $(function() {\n $.getScript(\"/_layouts/15/sp.workmanagement.js\").then(function() {\n console.log(\"sp.workmanagement.js LOADED!!!\");\n\n getMyTasks();\n }); \n });\n});\n\n"
},
{
"id": "10",
"name": "Load CSOM w SOD SOD Dependency",
"content": "SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"sp.js loaded!!!!\");\n});\n\nSP.SOD.registerSod(\"sp.publishing.js\", _spPageContextInfo.siteAbsoluteUrl + \"/_layouts/15/sp.publishing.js\");\nSP.SOD.registerSodDep(\"sp.publishing.js\", \"sp.js\");\nSP.SOD.executeFunc(\"sp.publishing.js\", \"SP.Publishing\", function () {\n console.log(\"sp.publishing.js loaded!!!!\");\n});\n"
},
{
"id": "11",
"name": "RefreshListViewWebPart",
"content": "function autoRefresh()\n{\n window.setInterval(listViewRefresh, 2000); // 20 seconds\n}\n \n// refresh all list view web parts on the page\nfunction listViewRefresh() {\n $('#labelMessage').text('refreshed ').fadeIn(\"slow\").fadeOut(\"slow\"); // debugging\n inplview.MyRestoreAllClvpsNavigation = MyRestoreAllClvpsNavigation;\n inplview.MyRestoreAllClvpsNavigation();\n}\n \n// Enumerate list view web parts\nfunction MyRestoreAllClvpsNavigation()\n{\n EnumCLVPs(MyCLVPRestoreNavigation);\n}\n \n// refresh referencing list view web part\nfunction MyCLVPRestoreNavigation(clvp) {\n var strHash = ajaxNavigate.getParam(\"InplviewHash\" + clvp.WebPartId());\n if (strHash == null)\n strHash = '';\n \n var strInpl = '?' + InplViewUtil.DecodeHashAsQueryString(strHash);\n var strShowInGrid = GetUrlKeyValue(\"ShowInGrid\", true, strInpl);\n \n if (strShowInGrid == \"True\") {\n InitGridFromView(clvp.ctx.view, true);\n }\n else if (clvp.ctx.inGridMode) {\n ExitGrid(clvp.ctx.view, true);\n }\n clvp.strHash = strHash;\n clvp.fRestore = true;\n var curRootFolder = GetRootFolder2(this);\n \n if (curRootFolder != null)\n strInpl = SetUrlKeyValue(\"RootFolder\", unescapeProperly(curRootFolder), true, strInpl);\n clvp.RefreshPagingEx(strInpl, true, null);\n \n }"
},
{
"id": "12",
"name": "CreateNewDocument",
"content": "\tfunction createNewDocument(newDocumentName, listName, docType, templateUrl) {\n\t\tvar ctx = SP.ClientContext.get_current();\n\t\tvar web = ctx.get_web();\n\t\tvar list = web.get_lists().getById(listName);\n\t\tvar folder = list.get_rootFolder();\n\t\tvar docName = newDocumentName && newDocumentName.length ?\n\t\t\tString.format(\"{0}\", newDocumentName) :\n\t\t\tString.format(\"New Document - {0}.docx\", new Date().format(\"yyyy-MM-dd_hhmmss\"));\n\t\tvar docItem = templateUrl && templateUrl.length ?\n\t\t\tlist.createDocumentFromTemplate(docName, folder, templateUrl) :\n\t\t\tlist.createDocument(docName, folder, docType || 1);\n\t\tvar wfUrl = docItem.getWOPIFrameUrl(SP.Utilities.SPWOPIFrameAction.edit);\n\t\tvar docFile = docItem.get_file();\n\t\t//docFile.checkIn(\"Initial version checked in.\", SP.CheckinType.majorCheckIn);\n\t\tctx.load(list, \"DefaultEditFormUrl\");\n\t\tctx.load(docItem, \"Id\");\n\t\tctx.load(docFile, \"ServerRelativeUrl\", \"CheckOutType\");\n\t\tctx.executeQueryAsync(success, fail);\n\n\t\tfunction success() {\n\t\t\tvar wopiUrl = wfUrl.get_value();\n\t\t\tvar doc = {\n\t\t\t\tdocumentName: docName,\n\t\t\t\teditDocumentPropertiesUrl: list.get_defaultEditFormUrl() +\n\t\t\t\t\t\"?ID=\" + docItem.get_id() +\n\t\t\t\t\t\"&Source=\" +\n\t\t\t\t\t_spPageContextInfo.webServerRelativeUrl,\n\t\t\t\tfileUrl: docFile.get_serverRelativeUrl(),\n\t\t\t\twopiEditDocumentUrl: Boolean(wopiUrl) ? wopiUrl.replace(/wopiframe\\.aspx/gi, \"WOPIFrame2.aspx\") : \"\",\n\t\t\t};\n\n\t\t\tconsole.info(\"Document: \" + doc.documentName + \" checked in.\");\n\t\t\tconsole.info(\"File: \" + doc.fileUrl);\n\t\t\tconsole.info(\"Edit properties url: \" + doc.editDocumentPropertiesUrl);\n\t\t\tconsole.info(\"WOPI edit document url: \" + doc.wopiEditDocumentUrl);\n\n\t\t\tvar opts = {\n\t\t\t\turl: doc.editDocumentPropertiesUrl,\n\t\t\t\targs: null,\n\t\t\t\ttitle: \"Edit Document Properties\",\n\t\t\t\tdialogReturnValueCallback: onNavigationReturn.bind(doc),\n\t\t\t};\n\t\t\tOpenPopUpPageWithDialogOptions(opts);\n\t\t}\n\n\t\tfunction onNavigationReturn(returnValue, docObject) {\n\t\t\t/**\n\t\t\t\tdocObject = {\n\t\t\t\t\tisFolder: false,\n\t\t\t\t\tnewFileIcon: \"icdocx.png\",\n\t\t\t\t\tnewFileSize: 18420,\n\t\t\t\t\tnewFileUrl: \"/sites/testblanksite1/Documents/Document - 2017-43-17_030239.docx\"\n\t\t\t\t}\n\t\t\t*/\n\t\t\tconsole.info(\"returned from edit properties\");\n\t\t\tconsole.info(this);\n\t\t\tconsole.info(returnValue);\n\t\t\tconsole.info(docObject);\n\t\t\tif (returnValue === SP.UI.DialogResult.OK) {\n\t\t\t\t//GoToPage(this.wopiEditDocumentUrl);\n\t\t\t}\n\t\t}\n\n\t\tfunction fail(c, b) {\n\t\t\tconsole.error(b.get_message());\n\t\t\talert(\"Critical Error: \" + b.get_message());\n\t\t}\n\t}\n\nfunction createNew() {\n console.info(\"In createNew\");\n var template = \"https://platinumdogsconsulting.sharepoint.com/sites/testblanksite1/Documents/Forms/template.dotx\";\n template = \"https://platinumdogsconsulting.sharepoint.com/sites/testblanksite1/SiteCollectionDocuments/Sample Template.docx\";\n\n var listName = \"{4ED33853-52EF-4AA5-878D-25F855DB1449}\";\n listName = \"{6215605E-B29B-4850-9916-082A4CAD348B}\";\n createNewDocument(\"\", listName, 0, template);\n}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', createNew);\n"
},
{
"id": "13",
"name": "Search Stuff",
"content": "https://blog.josequinto.com/2015/07/01/sharepoint-2013-javascript-search-files-classes-reference-refinement-web-part-classes-in-detail/\n \n /*sam.queryGroups.Default.dataProvider.get_queryGroupName() == \"Default\"*/\n var qs = new Srch.QueryState();\n var b = new Srch.QueryEventArgs(QueryState);\n b.userAction = 3;\n sam.queryGroups.Default.dataProvider.raiseQueryIssuingEvent(b);\n sam.queryGroups.Default.dataProvider.raiseQueryStateChangedEvent(b);\n\n /* get possible refinement info from current search results */\n sam.queryGroups.Default.dataProvider.get_refinementInfo()\n\n/* parse QueryState from querystring */\nsam = Srch.ScriptApplicationManager.get_current();\nvar ref = ajaxNavigate.getParam(sam.queryGroups.Default.dataProvider.get_queryGroupName()) // get the #Default=... value as JSON string\nvar qs = Srch.ParseJSONUtil.parseObjectFromJsonString(ref)\nqs\n\n/* update search results using refiners and update the querystring hash */\nvar myqs = {\"e\":-1,\"k\":\"site\",\"o\":null,\"x\":null,\"s\":0,\"r\":[{\"n\":\"ADMDocumentType\",\"t\":[\"\\\"ǂǂ534f50\\\"\"],\"o\":\"and\",\"k\":false,\"m\":null}],\"l\":1033,\"m\":\"\",\"d\":0};\nmyqs.k = \"lorem\";\nmyqs.r[0].t.push(\"\\\"ǂǂ466f726d\\\"\");\nmyqs.r[0].o = \"or\";\nsam = Srch.ScriptApplicationManager.get_current();\nqs = sam.queryGroups.Default.dataProvider.get_currentQueryState();\nqs.copyFrom(myqs);\n\nvar b = new Srch.QueryEventArgs(qs);\nb.userAction = Srch.UserActionType.refine; //3\nsam.queryGroups.Default.dataProvider.raiseQueryStateChangedEvent(b);\nsam.queryGroups.Default.dataProvider.issueQuery();\nsam.navigateTo(null, false);\n\n\n/* clear search results */\nsam = Srch.ScriptApplicationManager.get_current();\nmyqs = new Srch.QueryState();\nmyqs.copyFrom(Srch.QueryState.prototype);\nmyqs.k = \"subsite\"; // set to empty string to retain default results\nmyqs.r = [];\nqs = sam.queryGroups.Default.dataProvider.get_currentQueryState();\nqs.copyFrom(myqs);\nvar b = new Srch.QueryEventArgs(qs);\nb.userAction = Srch.UserActionType.refine; //3\nsam.queryGroups.Default.dataProvider.raiseQueryStateChangedEvent(b);\nsam.queryGroups.Default.dataProvider.issueQuery();\nsam.navigateTo(null, false);\n"
},
{
"id": "14",
"name": "CSS Bootstrap Accordion",
"content": "/* drops down over top of content below */\n.collapse.in {\n display: block;\n position: absolute;\n z-index: 9;\n width: 100%;\n left: 0;\n border: 1px solid #ddd;\n border-top: none;\n}\n\n.collapsing {\n position: absolute;\n z-index: 9;\n width: 100%;\n left: 0;\n border: 1px solid #ddd;\n border-top: none;\n}\n\n.collapsed span.caret.pull-right {\n transform: rotate(0deg);\n}\n\nspan.caret.pull-right {\n transform: rotate(90deg);\n transition: all .5s ease;\n}\n\n.panel-{default}theme > .panel-heading {\n color: hsla(0,0%,100%,.8);\n background-color: rgba(34,139,34,.6);\n border-color: rgba(34,139,34,.8);\n}\n\n.panel-{default}theme .panel-title > .small, \n.panel-{default}theme .panel-title > .small > a,\n.panel-{default}theme .panel-title > a,\n.panel-{default}theme .panel-title > small,\n.panel-{default}theme .panel-title > small > a {\n color: hsla(0,0%,100%,.8);\n}"
},
{
"id": "15",
"name": "GraphSearchStuff",
"content": "sam = Srch.ScriptApplicationManager.get_current();\nprovider = sam.queryGroups.Default.dataProvider;\n\n/* setting the result source (http://blog.voyta.net/2014/04/26/how-to-specify-results-source-name-for-search-query-using-sharepoint-2013-javascript-client-object-model/)\nprovider.set_sourceID(\"\")\nOR\nprovider.set_sourceName(\"\")\nprovider.set_sourceLavel(\"\")\n\nSourceName is source display name.\nSourceLevel indicates the level at which given source was defined;\n SPWeb – sources defined locally for current site\n SPSite – sources defined locally for current site collection\n SPSiteSubscription – sources defined for site subscription (for SharePoint online this is the level where all your custom results sources are defined in tenant administration)\n Ssa – search service application (for SharePoint Online all global predefined sources)\n*/\n/* \n\nhttps://github.com/SPCSR/DisplayTemplates/tree/master/Search%20Display%20Templates/mAdcOW%20Search%20Center%20Templates/mAdcOWGraph\nhttps://www.itunity.com/content/content/724/developing-with-delve-and-office-graph.pdf\n\nPersonalFeed\n1021\nPrivate\n\nModified\n1003\nPublic\n\nOrgColleague\n1015\nPublic\n\nOrgDirect\n1014\nPublic\n\nOrgManager\n1013\nPublic\n\nOrgSkipLevelManager\n1016\nPublic\n\nWorkingWith\n1019\nPrivate\n\nTrendingAround\n1020\nPublic\n\nViewed\n1001\nPrivate\n\nWorkingWithPublic\n1033\nPublic\n\nFollowedUser\n1006\n\nInFeed\n1021\n\nCommentedBy\n1023\n\nPresentedToMe\n1024\n\nSharedWithMe\n1022\n\nviewedTidbit\n1036\n\nlikedTidbit\n1037\n\ncommentedTidbit\n1038\n\nmodifiedTidbit\n1039\n\npopularWithTidbit\n1040\n\n*/\n\n\n/* delve Home Personal Feed query */\nvar properties = provider.get_properties();\nproperties[\"GraphQuery\"] = \"and(actor(me,action:1021),actor(me,or(action:1021,action:1036,action:1037,action:1039)))\";\nproperties[\"GraphRankingModel\"] = \"action:1021,weight:1,edgeFunc:weight,mergeFunc:max\";\nprovider.set_fallbackRankingModelID(\"0c77ded8-c3ef-466d-929d-905670ea1d72\");\nprovider.set_fallbackSort([]);\nprovider.set_queryTemplate(\"(FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf)\");\nprovider.issueQuery();\n\n/* delve My Work query */\nvar properties = provider.get_properties();\nproperties[\"GraphQuery\"] = \"and(actor(me,action:1003),actor(me,or(action:1003,action:1036,action:1037,action:1039)))\";\ndelete properties.GraphRankingModel;\nprovider.set_fallbackRankingModelID(\"\");\nprovider.set_fallbackSort([{\"p\":\"LastModifiedTime\",\"d\":1}]);\nprovider.set_queryTemplate(\"FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf\");\nprovider.issueQuery();\n\n/* shared with me */\nvar properties = provider.get_properties();\ndelete properties.GraphQuery;\ndelete properties.GraphRankingModel;\nprovider.set_fallbackRankingModelID(\"\");\nprovider.set_fallbackSort([{\"p\":\"LastModifiedTime\",\"d\":1}]);\nprovider.set_queryTemplate(\"(FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf) AND (SharedWithUsersOWSUSER:{User.AccountName})\");\nprovider.issueQuery();\n\n/* trending around - popular in my circle */\nvar properties = provider.get_properties();\nproperties[\"GraphQuery\"] = \"AND( ACTOR(ME, action:1020), ACTOR(ME, OR(action:1020,action:1001,action:1003)))\";\ndelete properties.GraphRankingModel;\nprovider.set_fallbackRankingModelID(\"\");\nprovider.set_fallbackSort([{\"p\":\"LastModifiedTime\",\"d\":1}]);\nprovider.set_queryTemplate(\"(FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf)\");\nprovider.issueQuery();\n\n/* my recently view/modified */\nvar properties = provider.get_properties();\nproperties[\"GraphQuery\"] = \"actor(me, or(action:1001,action:1003))\";\ndelete properties.GraphRankingModel;\nprovider.set_fallbackRankingModelID(\"\");\nprovider.set_fallbackSort([{\"p\":\"LastModifiedTime\",\"d\":1}]);\nprovider.set_queryTemplate(\"(FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf)\");\nprovider.issueQuery();\n\n/* featured documents */\t\t\t\nvar properties = provider.get_properties();\ndelete properties.GraphQuery;\ndelete properties.GraphRankingModel;\nprovider.set_fallbackRankingModelID(\"\");\nprovider.set_fallbackSort([{\"p\":\"LastModifiedTime\",\"d\":1}]);\nprovider.set_queryTemplate(\"ContentTypeId:0x0101001C6D22D5ABD44258AA6FE85814F301EE* Path:{Site.URL}* RefinableString104:1 (FileExtension:doc OR FileExtension:docx OR FileExtension:ppt OR FileExtension:pptx OR FileExtension:xls OR FileExtension:xlsx OR FileExtension:pdf)\");\nprovider.issueQuery();\n\n"
},
{
"id": "16",
"name": "Get Pages Items",
"content": "function getListItems(siteUrl, listTitle, queryColumns, queryXml) {\n var d = new $.Deferred();\n var ctx = !siteUrl || !siteUrl.length \n ? SP.ClientContext.get_current()\n : new SP.ClientContext(siteUrl);\n var list = ctx.get_web().get_lists().getByTitle(listTitle);\n\n var spQuery;\n if (queryXml && queryXml.length) {\n spQuery = new SP.CamlQuery();\n spQuery.set_viewXml(queryXml);\n } else {\n spQuery = SP.CamlQuery.createAllItemsQuery();\n }\n\n var includeColumns = String.format(\"Include({0})\", queryColumns.join(','));\n var listItems = list.getItems(spQuery);\n ctx.load(listItems/*, includeColumns*/);\n ctx.executeQueryAsync(function() {\n var mappedItems = [];\n for(var i = 0; i < listItems.get_count();i++) {\n var listItem = listItems.getItemAtIndex(i);\n var fieldValues = listItem.get_fieldValues();\n var newItem = {};\n $.each(queryColumns, function(i,e) {\n newItem[e] = fieldValues[e];\n });\n newItem.Id = listItem.get_id();\n if (includeColumns.match(/contenttype,/gi)) {\n newItem.ContentType = listItem.get_contentType().get_name();\n }\n mappedItems.push(newItem);\n }\n d.resolve(mappedItems);\n }, function(sender, args) {\n d.reject(args);\n });\n return d.promise();\n}\n\nfunction printListItemDetails(listItems) {\n\twindow.collection=window.collection || [];\nvar coll = window.collection;\ncoll.push(listItems);\n console.log(listItems);\n console.log(\"\\n\\n=======================================================\");\n console.log(\"=======================================================\\n\\n\");\n}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"LOADED!!!!\");\n \n var query = \n\"<View>\\\n <Query>\\\n <Where>\\\n <Or>\\\n <Eq>\\\n <FieldRef Name='ContentType' />\\\n <Value Type='Text'>Interflora Common News</Value>\\\n </Eq>\\\n <Eq>\\\n <FieldRef Name='ContentType' />\\\n <Value Type='Text'>Interflora Useful Information</Value>\\\n </Eq>\\\n </Or>\\\n </Where>\\\n <OrderBy>\\\n <FieldRef Name='Modified' Ascending='FALSE' />\\\n </OrderBy>\\\n </Query>\\\n <RowLimit>3</RowLimit>\\\n</View>\";\n getListItems(null, 'Pages', [\n \"Id\",\n \"Title\",\n \"ArticleStartDate\",\n \"PublishingPageContent\",\n \"PublishingRollupImage\",\n \"intfArticleEndDate\",\n \"intfContentSummary\",\n \"intfIsFeaturedNews\",\n \"ContentTypeId\",\n \"FileRef\",\n ], query).then(printListItemDetails);\n \n query = \n\"<View>\\\n\t<Query>\\\n\t\t<Where>\\\n\t\t\t<And>\\\n\t\t\t\t<Eq>\\\n\t\t\t\t\t<FieldRef Name='ContentType' />\\\n\t\t\t\t\t<Value Type='Text'>Interflora Vacancy</Value>\\\n\t\t\t\t</Eq>\\\n\t\t\t\t<Geq>\\\n\t\t\t\t\t<FieldRef Name='intfVacancyClosingDate' />\\\n\t\t\t\t\t<Value Type='DateTime'>\\\n\t\t\t\t\t\t<Today />\\\n\t\t\t\t\t</Value>\\\n\t\t\t\t</Geq>\\\n\t\t\t</And>\\\n\t\t</Where>\\\n\t\t<OrderBy>\\\n\t\t\t<FieldRef Name='intfVacancyClosingDate' Ascending='TRUE' />\\\n\t\t</OrderBy>\\\n\t</Query>\\\n\t<RowLimit>3</RowLimit>\\\n</View>\";\n var recr = _spPageContextInfo.webServerRelativeUrl + \"/recruitment\";\n getListItems(recr, 'Pages', [\n \"Id\",\n \"Title\",\n \"ArticleStartDate\",\n \"PublishingPageContent\",\n \"PublishingRollupImage\",\n \"intfVacancyClosingDate\",\n \"intfContentSummary\",\n \"intfIsExternalVacancy\",\n \"intfExternalVacancyUrl\",\n \"intfVacancyApplyToEmailAddress\",\n \"ContentTypeId\",\n ], query).then(printListItemDetails);\n\ngetListItems(null, 'Site Links', [\n \"Id\",\n \"Title\",\n \"BackgroundImageLocation\",\n \"Description\",\n \"LinkLocation\",\n \"LaunchBehavior\",\n \"intfLinkPurpose\",\n \"TileOrder\",\n\t\"ContentTypeId\",\n ], null).then(printListItemDetails, function(error) {\n\tconsole.error(error);\n\tconsole.error(error.get_message());\n\t});\n\n});\n\n\n\n\n"
},
{
"id": "17",
"name": "Get Announcements",
"content": "function getListItems(siteUrl, listTitle, queryColumns, queryXml) {\n var d = new $.Deferred();\n var ctx = !siteUrl || !siteUrl.length \n ? SP.ClientContext.get_current()\n : new SP.ClientContext(siteUrl);\n var list = ctx.get_web().get_lists().getByTitle(listTitle);\n\n var spQuery;\n if (queryXml && queryXml.length) {\n spQuery = new SP.CamlQuery();\n spQuery.set_viewXml(queryXml);\n } else {\n spQuery = SP.CamlQuery.createAllItemsQuery();\n }\n\n var includeColumns = String.format(\"Include({0})\", queryColumns.join(','));\n var listItems = list.getItems(spQuery);\n ctx.load(listItems/*, includeColumns*/);\n ctx.executeQueryAsync(function() {\n var mappedItems = [];\n for(var i = 0; i < listItems.get_count();i++) {\n var listItem = listItems.getItemAtIndex(i);\n var fieldValues = listItem.get_fieldValues();\n var newItem = {};\n $.each(queryColumns, function(i,e) {\n newItem[e] = fieldValues[e];\n });\n newItem.Id = listItem.get_id();\n if (includeColumns.match(/contenttype,/gi)) {\n newItem.ContentType = listItem.get_contentType().get_name();\n }\n mappedItems.push(newItem);\n }\n d.resolve(mappedItems);\n }, function(sender, args) {\n d.reject(args);\n });\n return d.promise();\n}\n\nfunction printListItemDetails(listItems) {\n window.collection=window.collection || [];\n var coll = window.collection;\n coll.push(listItems);\n console.log(listItems);\n console.log(\"\\n\\n=======================================================\");\n console.log(\"=======================================================\\n\\n\");\n}\n\n\nfunction runQueries() {\n var query = \n\"<View>\\\n <Query>\\\n <OrderBy>\\\n <FieldRef Name='Expires' Ascending='TRUE' />\\\n </OrderBy>\\\n <Where>\\\n <Or>\\\n <IsNull>\\\n <FieldRef Name='Expires' />\\\n </IsNull>\\\n <Geq>\\\n <FieldRef Name='Expires' />\\\n <Value Type='DateTime' >\\\n <Today/>\\\n </Value>\\\n </Geq>\\\n </Or>\\\n </Where>\\\n </Query>\\\n <RowLimit>3</RowLimit>\\\n</View>\";\n getListItems(null, 'Announcements', [\n \"Id\",\n \"Title\",\n \"Expires\",\n \"Body\",\n \"Author\",\n \"Editor\",\n \"Created\",\n \"Modified\",\n \"FileRef\",\n ], query).then(printListItemDetails);\n\n}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"LOADED!!!!\");\n runQueries();\n});\n\n\n\n\n"
},
{
"id": "19",
"name": "Get Vacancies",
"content": "function getListItems(siteUrl, listTitle, queryColumns, queryXml) {\n var d = new $.Deferred();\n var ctx = !siteUrl || !siteUrl.length \n ? SP.ClientContext.get_current()\n : new SP.ClientContext(siteUrl);\n var list = ctx.get_web().get_lists().getByTitle(listTitle);\n\n var spQuery;\n if (queryXml && queryXml.length) {\n spQuery = new SP.CamlQuery();\n spQuery.set_viewXml(queryXml);\n } else {\n spQuery = SP.CamlQuery.createAllItemsQuery();\n }\n\n var includeColumns = String.format(\"Include({0})\", queryColumns.join(','));\n var listItems = list.getItems(spQuery);\n ctx.load(listItems/*, includeColumns*/);\n ctx.executeQueryAsync(function() {\n var mappedItems = [];\n for(var i = 0; i < listItems.get_count();i++) {\n var listItem = listItems.getItemAtIndex(i);\n var fieldValues = listItem.get_fieldValues();\n var newItem = {};\n $.each(queryColumns, function(i,e) {\n newItem[e] = fieldValues[e];\n });\n newItem.Id = listItem.get_id();\n if (includeColumns.match(/contenttype,/gi)) {\n newItem.ContentType = listItem.get_contentType().get_name();\n }\n mappedItems.push(newItem);\n }\n d.resolve(mappedItems);\n }, function(sender, args) {\n d.reject(args);\n });\n return d.promise();\n}\n\nfunction printListItemDetails(listItems) {\n\twindow.collection=window.collection || [];\n\tvar coll = window.collection;\n\tcoll.push(listItems);\n\tconsole.log(listItems);\n\tconsole.log(\"\\n\\n=======================================================\");\n\tconsole.log(\"=======================================================\\n\\n\");\n}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.log(\"LOADED!!!!\");\n \n var query = \n\"<View>\\\n\t<Query>\\\n\t\t<Where>\\\n\t\t\t<And>\\\n\t\t\t\t<Eq>\\\n\t\t\t\t\t<FieldRef Name='ContentType' />\\\n\t\t\t\t\t<Value Type='Text'>Interflora Vacancy</Value>\\\n\t\t\t\t</Eq>\\\n\t\t\t\t<Geq>\\\n\t\t\t\t\t<FieldRef Name='intfVacancyClosingDate' />\\\n\t\t\t\t\t<Value Type='DateTime'>\\\n\t\t\t\t\t\t<Today />\\\n\t\t\t\t\t</Value>\\\n\t\t\t\t</Geq>\\\n\t\t\t</And>\\\n\t\t</Where>\\\n\t\t<OrderBy>\\\n\t\t\t<FieldRef Name='intfVacancyClosingDate' Ascending='TRUE' />\\\n\t\t</OrderBy>\\\n\t</Query>\\\n\t<RowLimit>3</RowLimit>\\\n</View>\";\n var recr = _spPageContextInfo.webServerRelativeUrl + \"/recruitment\";\n getListItems(recr, 'Pages', [\n \"Id\",\n \"Title\",\n \"ArticleStartDate\",\n \"PublishingPageContent\",\n \"PublishingRollupImage\",\n \"intfVacancyClosingDate\",\n \"intfContentSummary\",\n \"intfIsExternalVacancy\",\n \"intfExternalVacancyUrl\",\n \"intfVacancyApplyToEmailAddress\",\n \"ContentTypeId\",\n ], query).then(printListItemDetails);\n\n});\n\n\n\n\n"
},
{
"id": "20",
"name": "Script snippet #20",
"content": "function asyncOne() {\n var d = new $.Deferred();\n\n setTimeout(function() {\n d.resolve([{ id:1, title:\"title1\",},{ id:2, title:\"title2\",},{ id:3, title:\"title3\",}]);\n }, 2000);\n\n return d.promise();\n}\n\nfunction asyncTwo() {\n var d = new $.Deferred();\n\n setTimeout(function() {\n d.resolve([{ id:10, title:\"title10\",},{ id:20, title:\"title20\",},{ id:30, title:\"title30\",}]);\n }, 5000);\n\n return d.promise();\n}\n\nvar masterWaits = [asyncOne(), asyncTwo()];\n$.when.apply(null, masterWaits)\n.then(function(oneRes, twoRes) {\n console.log(\"Wait complete!\");\n\n console.log(oneRes);\n console.log(twoRes);\n\n});\n"
},
{
"id": "21",
"name": "Get Calendar Events",
"content": "function getListItems(siteUrl, listTitle, queryColumns, queryXml) {\n var d = new $.Deferred();\n var ctx = !siteUrl || !siteUrl.length \n ? SP.ClientContext.get_current()\n : new SP.ClientContext(siteUrl);\n var list = ctx.get_web().get_lists().getByTitle(listTitle);\n\n var spQuery;\n if (queryXml && queryXml.length) {\n spQuery = new SP.CamlQuery();\n spQuery.set_viewXml(queryXml);\n } else {\n spQuery = SP.CamlQuery.createAllItemsQuery();\n }\n\n var includeColumns = String.format(\"Include({0})\", queryColumns.join(','));\n var listItems = list.getItems(spQuery);\n ctx.load(listItems/*, includeColumns*/);\n ctx.executeQueryAsync(function() {\n var mappedItems = [];\n for(var i = 0; i < listItems.get_count();i++) {\n var listItem = listItems.getItemAtIndex(i);\n var fieldValues = listItem.get_fieldValues();\n var newItem = {};\n $.each(queryColumns, function(i,e) {\n newItem[e] = fieldValues[e];\n });\n newItem.Id = listItem.get_id();\n if (includeColumns.match(/contenttype,/gi)) {\n newItem.ContentType = listItem.get_contentType().get_name();\n }\n mappedItems.push(newItem);\n }\n d.resolve(mappedItems);\n }, function(sender, args) {\n d.reject(args);\n });\n return d.promise();\n}\n\nfunction printListItemDetails(listItems) {\n window.collection=window.collection || [];\n var coll = window.collection;\n coll.push(listItems);\n listItems.forEach((ev) => {\n console.info(`- ${ev.Title}`, ev);\n });\n\n console.log(\"=======================================================\\n\\n\");\n}\n\n\nfunction runQueries() {\n var aDate = new Date(2017, 06, 01, 01, 00, 00).toISOString();\n var query = \n\"<View RecurrenceRowset=\\\"TRUE\\\" Scope=\\\"Recursive\\\">\\\n <Query>\\\n <CalendarDate>\" + aDate + \"</CalendarDate>\\\n <Where>\\\n <DateRangesOverlap>\\\n <FieldRef Name='EventDate' />\\\n <FieldRef Name='EndDate' />\\\n <FieldRef Name='RecurrenceID' />\\\n <Value Type='DateTime'>\\\n <Week />\\\n </Value>\\\n </DateRangesOverlap>\\\n </Where>\\\n <OrderBy>\\\n <FieldRef Name='EventDate' Ascending='TRUE' />\\\n </OrderBy>\\\n <QueryOptions>\\\n <CalendarDate>\" + aDate + \"</CalendarDate>\\\n <ExpandRecurrence>TRUE</ExpandRecurrence>\\\n <RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>\\\n </QueryOptions>\\\n </Query>\\\n</View>\";\n console.log(query);\n getListItems(null, 'Calendar', [\n \"Id\",\n \"Title\",\n \"EventDate\",\n \"EndDate\",\n \"fAllDayEvent\",\n \"RecurrenceID\",\n \"fRecurrence\",\n \"RecurrenceData\",\n \"Author\",\n \"Editor\",\n \"Created\",\n \"Modified\",\n \"URL\",\n ], query).then(printListItemDetails);\n\n}\n\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.clear();\n console.log(\"LOADED!!!!\");\n runQueries();\n});\n\n\n\n\n"
},
{
"id": "22",
"name": "CalHelper",
"content": "function CalendarHelper(year, month, day) {\n if (typeof year !== \"undefined\" && year instanceof Date) {\n this.Year = year.getFullYear();\n this.Month = year.getMonth();\n this.Day = year.getDate();\n } else {\n var def = new Date();\n this.Year = year || def.getFullYear();\n this.Month = (month && month-1) || def.getMonth();\n\n this.Day = Math.min(this.DaysInMonth, (day || def.getDate()));\n }\n\n this.AnchorDate = new Date(this.Year, this.Month, this.Day);\n this.getModel = function() {\n var o = {\n calendarStart: this.CalendarStart,\n calendarEnd: this.CalendarEnd,\n days: this.CalendarDays,\n year: this.Year,\n month: this.Month + 1,\n day: this.Day,\n dayShort: this.AnchorDate.format(\"ddd\"),\n dayLong: this.AnchorDate.format(\"dddd\"),\n monthShort: this.AnchorDate.format(\"MMM\"),\n monthLong: this.AnchorDate.format(\"MMMM\"), \n };\n return o;\n };\n}\nObject.defineProperty(CalendarHelper.prototype, \"OneDay\", {\n get: function() {\n return 1000*60*60*24;\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"DaysInMonth\", {\n get: function() {\n var daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n var isLeapYear = (this.Year % 4 == 0) && ((this.Year % 100 !== 0) || (this.Year % 400 == 0));\n var lastDay = (this.Month == 1) && isLeapYear\n\t\t\t\t\t\t\t? 29\n\t\t\t\t\t\t\t: daysOfMonth[this.Month];\n return lastDay;\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"StartOfMonth\", {\n get: function() {\n return new Date(this.Year, this.Month, 1, 1, 0, 0);\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"EndOfMonth\", {\n get: function() {\n return new Date(this.Year, this.Month, this.DaysInMonth, 23, 59, 59);\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"CalendarStart\", {\n get: function() {\n var offset = 0 - (this.OneDay * this.StartOfMonth.getDay());\n return new Date(this.StartOfMonth.getTime() + offset );\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"CalendarEnd\", {\n get: function() {\n var offset = (this.OneDay * (6 - this.EndOfMonth.getDay()));\n return new Date(this.EndOfMonth.getTime() + offset );\n }\n});\nObject.defineProperty(CalendarHelper.prototype, \"CalendarDays\", {\n get: function() {\n var start = this.CalendarStart.getTime();\n var end = this.CalendarEnd.getTime();\n var calDays = [];\n for(var i = start; i <= end; i += this.OneDay) {\n var d = new Date(i);\n calDays.push({ \n Date: d, \n Unix: d.getTime(),\n OutsideAnchorMonth: d.getMonth() !== this.Month, \n Day: d.format(\"dd\"),\n DayShort: d.format(\"ddd\"),\n DayLong: d.format(\"dddd\"),\n Month: d.format(\"MM\"),\n MonthShort: d.format(\"MMM\"),\n MonthLong: d.format(\"MMMM\"),\n Year: d.getFullYear(),\n Events: [],\n });\n }\n return calDays;\n }\n});\n\n\nconsole.clear();\nvar cal = new CalendarHelper(2017, 05);\nconsole.log(cal);\n\nvar cal = new CalendarHelper(new Date());\nconsole.log(cal);\n\nvar cal = new CalendarHelper();\nconsole.log(cal.getModel());"
},
{
"id": "23",
"name": "ListgroupValue",
"content": "function makeDateOnly(date) {\n\t\tvar newDate = new Date(date);\n\t\tnewDate.setHours(0);\n\t\tnewDate.setMinutes(0);\n\t\tnewDate.setSeconds(0);\n\t\tnewDate.setMilliseconds(0);\n\t\treturn newDate;\n\t}\n\tfunction ListGroupValue(baseValue) {\n\n\t\tthis.labelCssClass = \"\";\n\t\tthis.groupDisplayValue = \"\";\n\t\tthis.groupHashValue = \"\";\n\t\tthis.groupCompareValue = \"\";\n\t\tthis.originalValue = \"\";\n\n\t\tvar type = Object.prototype.toString.call(baseValue);\n\t\tswitch(type) {\n\t\t\tcase \"[object Date]\": {\n\t\t\t\tthis.labelCssClass = \"label-success\";\n\t\t\t\tthis.groupDisplayValue = baseValue.format(\"ddd, MMM d yyyy\");\n\t\t\t\tthis.groupHashValue = makeDateOnly(baseValue).getTime().toString();\n\t\t\t\tthis.groupCompareValue = makeDateOnly(baseValue).getTime();\n\t\t\t\tthis.originalValue = baseValue;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"[object Number]\": {\n\t\t\t\tthis.labelCssClass = \"label-success\";\n\t\t\t\tthis.groupDisplayValue = baseValue.toString();\n\t\t\t\tthis.groupHashValue = baseValue.toString().replace(/[\\\"\\' ]+/gi, '').toLowerCase();\n\t\t\t\tthis.groupCompareValue = baseValue.toString().replace(/[\\\"\\' ]+/gi, '').toLowerCase();\n\t\t\t\tthis.originalValue = baseValue;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\tcase \"[object String]\": {\n\t\t\t\tthis.labelCssClass = \"label-default\";\n\t\t\t\tthis.groupDisplayValue = baseValue;\n\t\t\t\tthis.groupHashValue = baseValue.replace(/[\\\"\\' ]+/gi, '').toLowerCase();\n\t\t\t\tthis.groupCompareValue = baseValue.replace(/[\\\"\\' ]+/gi, '').toLowerCase();\n\t\t\t\tthis.originalValue = baseValue;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n console.clear();\n d=new Date();\n\ta=new ListGroupValue(d);\n\tconsole.log(a);"
},
{
"id": "24",
"name": "CloneObject",
"content": "\tfunction cloneObject(obj, deep) {\n\t\tif (null == obj || \"object\" != typeof obj) return obj;\n\n\t\tvar copy = obj.constructor();\n\t\tfor (var keyName in obj) {\n\t\t\tif (obj.hasOwnProperty(keyName)) {\n\t\t\t\tvar keyValue = obj[keyName];\n\t\t\t\tvar type = Object.prototype.toString.call(keyValue);\n\t\t\t\tif (type === '[object Object]') {\n\t\t\t\t\tcopy[keyName] = deep ? cloneObject(keyValue, deep) : {};\n\t\t\t\t} else if (type === '[object Array]') {\n\t\t\t\t\tcopy[keyName] = keyValue.map(function(e) {\n\t\t\t\t\t\treturn cloneObject(e, deep);\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tcopy[keyName] = obj[keyName];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn copy;\n\t}\n\nconsole.clear();\na = {a: 1, b: 2, c: 3, d:[1,2,3,4,5] };\nb = {a: 1, b: 2, c: 3, ob: a };\nd = [a,b];\n\na1=cloneObject(a);\nconsole.log(a1);\nd1=cloneObject(d,true);\nconsole.log(d1);\n\na.a *= 10;\na.b *= 10;\na.c *= 10;\nc=cloneObject(b,true);\nconsole.log(a, c);\na.a *= 10;\na.b *= 10;\na.c *= 10;\nconsole.log(a, c);\n"
},
{
"id": "25",
"name": "Permissions",
"content": "\tfunction hasPermission(effectivePermissionMask, permissionToCheck) {\n\t\tif (typeof effectivePermissionMask === \"undefined\" || !effectivePermissionMask) {\n\t\t\teffectivePermissionMask = {\n\t\t\t\t\"High\": 0,\n\t\t\t\t\"Low\": 0,\n\t\t\t};\n\t\t\treturn false;\n\t\t} else if (typeof effectivePermissionMask === \"string\") {\n\t\t\teffectivePermissionMask = JSON.parse(effectivePermissionMask);\n\t\t} else if (typeof effectivePermissionMask === \"object\") {\n\t\t effectivePermissionMask = JSON.parse(JSON.stringify(effectivePermissionMask));\n\t\t}\n\n\t\tvar permissions = new SP.BasePermissions();\n\t\ttry {\n\t\t\tpermissions.fromJson(effectivePermissionMask);\n\t\t\tvar hasPermission = permissions.has(permissionToCheck);\n\t\t\treturn hasPermission;\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Exception in [hasPermission] \", effectivePermissionMask, permissionToCheck, e);\n\t\t\treturn false;\n\t\t}\n\t}\n\nperms = { High: \"2147483647\", Low: \"4294967295\", }\nconsole.clear();\nconsole.log(perms);\nconsole.log(\"Has Edit: \", SP.PermissionKind.editListItems, hasPermission(perms, SP.PermissionKind.editListItems ));\nconsole.log(\"Has Edit: \", SP.PermissionKind.approveItems, hasPermission(perms, SP.PermissionKind.approveItems ));\nconsole.log(\"Has Edit: \", SP.PermissionKind.manageLists, hasPermission(perms, SP.PermissionKind.manageLists ));\n\nconsole.log(perms);\n"
},
{
"id": "26",
"name": "UserLanguageRedirection",
"content": "$(document).ready(function() {\n\tSP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {\n\n\t\tgetUserLanguagePreference(\"USA\")\n\t\t\t.then(function(userLang) {\n\t\t\t\tconsole.info(\"PCC User Language is: \", userLang);\n\t\t\t\t/*if (userLang == \"USA\") {\n\t\t\t\t\twindow.location.replace(_spPageContextInfo.webAbsoluteUrl + \"/en-gb\");\n\t\t\t\t} else if (userLang == \"CYM\") {\n\t\t\t\t\twindow.location.replace(_spPageContextInfo.webAbsoluteUrl + \"/cy-gb\");\n\t\t\t\t} else {\n\t\t\t\t\twindow.location.replace(_spPageContextInfo.webAbsoluteUrl + \"/en-gb\");\n\t\t\t\t}*/\n\t\t\t});\n\n\t});\n})\n\nfunction getCachedLanguage(username) {\n\tvar cCacheName = \"PCC-SPVar-UsrLang-\" + username;\n\tvar cachedLanguage = null;\n\tif (window.localStorage && window.localStorage.getItem) {\n\t\t// local storage is supported\n\t\tvar parts = (window.localStorage.getItem(cCacheName) || \"\").split(\"|\");\n\t\tif (parts && parts.length) {\n\t\t\tvar now = new Date().getTime();\n\t\t\tvar expires = Date.parse(parts[0]);\n\t\t\tnow = new Date(now - (now % (1000 * 60 * 60 * 24)));\n\t\t\texpires = new Date(expires - (expires % (1000 * 60 * 60 * 24)));\n\t\t\tif (now.getTime() > expires.getTime()) {\n\t\t\t\t// expired\n\t\t\t\twindow.localStorage.removeItem(cCacheName);\n\t\t\t} else {\n\t\t\t\tcachedLanguage = parts[1];\n\t\t\t}\n\t\t}\n\t}\n\treturn cachedLanguage;\n}\nfunction setCachedLanguage(username, language, days) {\n\tvar cCacheName = \"PCC-SPVar-UsrLang-\" + username;\n\tvar expires = null;\n\tif (window.localStorage && window.localStorage.setItem) {\n\t\t// local storage is supported\n\t\tvar now = (new Date()).getTime();\n\t\tnow = new Date( (now - (now % (1000 * 60 * 60 * 24))) + ((days || 7) * (1000 * 60 * 60 * 24)) );\n\t\texpires = now.toISOString();\n\t\twindow.localStorage.setItem(cCacheName, expires + \"|\" + (language || \"USA\"));\n\t}\n\treturn expires;\n}\n\nfunction getUserLanguagePreference(defaultLanguage) {\n\tvar d = new $.Deferred();\n\t\n\tvar username = _spPageContextInfo.userLoginName;\n\tvar n = username.lastIndexOf('\\\\');\n\tvar username = username.substring(n + 1);\n\n\tvar cachedLanguage = getCachedLanguage(username);\n\tif (!cachedLanguage) {\n\t\t// if not cached, or cache expired, do query\n\t\tconsole.info(\"PCC UserName: \" + username + \", language not in cache!\");\n\t\tgetLanguage(username)\n\t\t\t.then(function(usrLang, usrName) {\n\t\t\t\tsetCachedLanguage(username, usrLang, 7);\n\t\t\t\td.resolve(usrLang);\n\t\t\t}, function(message) {\n\t\t\t\tconsole.error(message);\n\t\t\t\td.resolve(defaultLanguage || \"\");\n\t\t\t});\n\t} else {\n\t\t// else return cached value\n\t\tconsole.info(\"PCC UserName: \" + username + \", language: \" + cachedLanguage + \" served from cache.\");\n\t\td.resolve(cachedLanguage);\n\t}\n\n\treturn d.promise();\n}\n\nfunction getLanguage(username) {\n\tvar d = new $.Deferred();\n\n\tvar clientContext = new SP.ClientContext.get_current();\n\tvar web = clientContext.get_site().get_rootWeb();\n\tvar mylist = web.get_lists().getByTitle('UserDetails');\n\tvar collListItems;\n\n\tvar camlQuery = new SP.CamlQuery();\n\tcamlQuery.set_viewXml(\"<View>\" +\n\t\t\"<Query>\" +\n\t\t\"<Where><Eq>\" +\n\t\t\"<FieldRef Name='User'/>\" +\n\t\t\"<Value Type='Text'>\" + username + \"</Value>\" +\n\t\t\"</Eq></Where>\" +\n\t\t\"</Query>\" +\n\t\t\"<ViewFields>\" +\n\t\t\"<FieldRef Name='User' />\" +\n\t\t\"<FieldRef Name='Language' />\" +\n\t\t\"</ViewFields>\" +\n\t\t\"</View>\");\n\tcollListItems = mylist.getItems(camlQuery);\n\tclientContext.load(mylist);\n\tclientContext.load(collListItems);\n\tclientContext.executeQueryAsync(function() {\n\t\tlistItemEnumerator = collListItems.getEnumerator();\n\t\tvar langCount = collListItems.get_count();\n\t\tconsole.info(\"Found \" + langCount + \" languages\");\n\n\t\tif (langCount == 0) {\n\t\t\tr.reject(\"No item found in UserDetails for user: \" + username);\n\t\t} else {\n\t\t\tif (listItemEnumerator.moveNext()) {\n\t\t\t\tcollListItems = listItemEnumerator.get_current();\n\n\t\t\t\tvar usrName = collListItems.get_item(\"User\");\n\t\t\t\tvar usrLang = collListItems.get_item(\"Language\");\n\t\t\t\tconsole.info(\"Found: \" + usrName + \" - \" + usrLang)\n\t\t\t\td.resolve(usrLang, usrName);\n\t\t\t}\n\t\t}\n\t}, function(sender, args) {\n\t\tvar message = 'Request failed getting Language. \\nError: ' + args.get_message() + '\\nStackTrace: ' + args.get_stackTrace();\n\t\td.reject(message);\n\t});\n\n\treturn d.promise();\n}\n"
},
{
"id": "27",
"name": "Search Refinement",
"content": "sam = Srch.ScriptApplicationManager.get_current();\nref = sam.queryGroups.Default.displays.filter(function(e) { return (e instanceof Srch.Refinement); });\n/*\n is sam.queryGroups.Default.displays[0] instanceof Srch.Refinement ?\n is sam.queryGroups.Default.displays[1] instanceof Srch.Result ?\n*/\n\n\n\n// get refiner controls\nrc = ref[0].get_selectedRefinementControls();\n/*\n[\n {\n alternateRenderContext:Object,\n containerId:\"ctl00_ctl42_g_08773096_0792_4275_8e27_69701d35cbd1_csr2\",\n countDisplay:\"Both\",\n deepHits:100000,\n overrideDisplayName:\"Doc Owner\",\n propertyName:\"RefinableString105\",\n renderTemplateId:\"~sitecollection/_catalogs/masterpage/Display Templates/Filters/Filter_Default.js\",\n spec:\"(deephits=100000,filter=15/0/*)\",\n useDefaultDateIntervals:false,\n }\n]\n*/\n\n\n// get refinement tokens for refiner controls\nrdp = ref[0].get_dataProvider().get_refinementInfo();\n/*\n{\n\t\"RefinableString105\": [\n\t\t{\n\t\t\t\"RefinerName\": \"RefinableString105\",\n\t\t\t\"DisplayName\": \"\",\n\t\t\t\"Type\": \"String\",\n\t\t\t\"Modifier\": \"RefinableString105\",\n\t\t\t\"Score\": 1.19078254699707,\n\t\t\t\"UniqueCount\": 0,\n\t\t\t\"HitCount\": 24,\n\t\t\t\"NonZeroCount\": 27,\n\t\t\t\"Ratio\": 0.888888888888889,\n\t\t\t\"Min\": 0,\n\t\t\t\"Max\": 0,\n\t\t\t\"Mean\": 0,\n\t\t\t\"Entropy\": 1.1907825152919,\n\t\t\t\"Sum\": 0,\n\t\t\t\"RefinementName\": \"Eve Cortana\",\n\t\t\t\"RefinementValue\": \"Eve Cortana\",\n\t\t\t\"RefinementToken\": \"\\\"ǂǂ45766520436f7274616e61\\\"\",\n\t\t\t\"RefinementCount\": 11,\n\t\t\t\"PartitionId\": {\n\t\t\t\t\"_m_guidString$p$0\": \"f1a23d2f-d11b-4d03-8b2c-98225bbf3165\"\n\t\t\t},\n\t\t\t\"UrlZone\": 0,\n\t\t\t\"Culture\": \"en-US\",\n\t\t\t\"RenderTemplateId\": \"~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Default.js\",\n\t\t\t\"RefinementTokens\": [\n\t\t\t\t\"\\\"ǂǂ45766520436f7274616e61\\\"\"\n\t\t\t],\n\t\t\t\"RefinementTokenWrappedValues\": [\n\t\t\t\t\"equals(\\\"Eve Cortana\\\")\"\n\t\t\t]\n\t\t},\n\t],\n\t\"DisplayAuthor\": [\n\t\t{\n\t\t\t\"RefinerName\": \"DisplayAuthor\",\n\t\t\t\"DisplayName\": \"\",\n\t\t\t\"Type\": \"String\",\n\t\t\t\"Modifier\": \"DisplayAuthor\",\n\t\t\t\"Score\": 0.244136065244675,\n\t\t\t\"UniqueCount\": 0,\n\t\t\t\"HitCount\": 27,\n\t\t\t\"NonZeroCount\": 27,\n\t\t\t\"Ratio\": 1,\n\t\t\t\"Min\": 0,\n\t\t\t\"Max\": 0,\n\t\t\t\"Mean\": 0,\n\t\t\t\"Entropy\": 0.244136064148469,\n\t\t\t\"Sum\": 0,\n\t\t\t\"RefinementName\": \"Phillip Allan-Harding\",\n\t\t\t\"RefinementValue\": \"Phillip Allan-Harding\",\n\t\t\t\"RefinementToken\": \"\\\"ǂǂ5068696c6c697020416c6c616e2d48617264696e67\\\"\",\n\t\t\t\"RefinementCount\": 27,\n\t\t\t\"PartitionId\": {\n\t\t\t\t\"_m_guidString$p$0\": \"f1a23d2f-d11b-4d03-8b2c-98225bbf3165\"\n\t\t\t},\n\t\t\t\"UrlZone\": 0,\n\t\t\t\"Culture\": \"en-US\",\n\t\t\t\"RenderTemplateId\": \"~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Default.js\",\n\t\t\t\"RefinementTokens\": [\n\t\t\t\t\"\\\"ǂǂ5068696c6c697020416c6c616e2d48617264696e67\\\"\"\n\t\t\t],\n\t\t\t\"RefinementTokenWrappedValues\": [\n\t\t\t\t\"equals(\\\"Phillip Allan-Harding\\\")\"\n\t\t\t]\n\t\t},\n\t]\n}*/\n"
},
{
"id": "28",
"name": "Promises",
"content": "console.clear();\n\nvar promise = new Promise(function(resolve, reject) { \n setTimeout(function() {\n throw new Error(\"This is an Error\");\n reject(\"This is a Rejection\");\n resolve(\"{ \\\"Msg\\\": \\\"This is the message\\\" }\");\n }, 5000);\n});\n\npromise\n .then(JSON.parse)\n .then(function(response) {\n console.info(\"Reponse is: \", response);\n })\n .catch(function(error) {\n console.error(\"Rejection is: \", error);\n });"
},
{
"id": "29",
"name": "TAX",
"content": "function exec() {\n console.clear();\n\n var name = \"Document Navigation and Metadata\";\n var lcid = 1033;\n\n var ctx = SP.ClientContext.get_current();\n var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);\n var termStore = taxonomySession.getDefaultSiteCollectionTermStore();\n \n var termGroup = termStore.getSiteCollectionGroup(ctx.get_site(), false);\n var termSet = termGroup.get_termSets().getByName(name);\n var terms = termSet.getAllTerms(); \n\n ctx.load(taxonomySession);\n ctx.load(termStore);\n ctx.load(termGroup);\n ctx.load(termSet);\n ctx.load(terms, 'Include(Name,Labels)');\n ctx.executeQueryAsync( (sender, args) => {\n\n var termArray = [];\n var termsEnumerator = terms.getEnumerator();\n while (termsEnumerator.moveNext()) {\n var currentTerm = termsEnumerator.get_current();\n var label = currentTerm.getDefaultLabel(lcid);\n termArray.push({\n term: currentTerm,\n label: label,\n });\n ctx.load(currentTerm);\n }\n ctx.executeQueryAsync( (sender, args) => {\n \n console.info(`TermStore: ${termStore.get_name()} (${termStore.get_id()})`);\n console.info(`TermGroup: ${termGroup.get_name()} (${termGroup.get_id()}) (sitecollection: ${termGroup.get_isSiteCollectionGroup()})`);\n console.info(`TermSet: ${termSet.get_name()} (${termSet.get_id()})`);\n console.info(`Done: ${termArray.length}`);\n termArray.forEach((e) => {\n e.id = e.term.get_id().toString();\n e.name = e.term.get_name();\n e.label = e.label.get_value();\n e.path = e.term.get_pathOfTerm();\n console.info(`\\t: ${e.label} (${e.id}) [${e.path}]`);\n }); \n\n }, (sender, args) => {\n var m = args.get_message();\n console.error(\"INNER ERROR: \", m);\n });\n\n }, (sender, args) => {\n var m = args.get_message();\n console.error(\"ERROR: \", m);\n });\n}\n\nSP.SOD.loadMultiple(['sp.js'], () => {\n SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));\n SP.SOD.loadMultiple(['sp.taxonomy.js'], () => {\n exec();\n });\n});"
},
{
"id": "31",
"name": "Video",
"content": "function createNewLibraryContent(listName, postUploadUrl) {\n var ctx = SP.ClientContext.get_current();\n var list = ctx.get_web().get_lists().getByTitle(listName);\n var folder = list.get_rootFolder();\n ctx.load(list, \"EffectiveBasePermissions\", \"DefaultNewFormUrl\", \"DefaultDisplayFormUrl\", \"DefaultEditFormUrl\", \"Id\");\n ctx.load(folder, \"UniqueId\", \"ServerRelativeUrl\");\n ctx.executeQueryAsync(success, fail);\n\n function success() {\n var dataObject = {\n permissions: list.get_effectiveBasePermissions(),\n newFormUrl: list.get_defaultNewFormUrl(),\n displayFormUrl: list.get_defaultDisplayFormUrl(),\n editFormUrl: list.get_defaultEditFormUrl(),\n id: list.get_id().toString(),\n folderId: folder.get_uniqueId().toString(),\n folderUrl: folder.get_serverRelativeUrl(),\n postUploadUrl: postUploadUrl || \"\"\n };\n console.info(\"list: \", list);\n console.info(\"folder: \", folder);\n console.info(\"dataObject: \", dataObject);\n\n var opts = {\n url: dataObject.newFormUrl,\n args: null,\n title: \"Upload New Video\",\n dialogReturnValueCallback: onDialogReturn.bind(dataObject),\n };\n OpenPopUpPageWithDialogOptions(opts);\n }\n\n function onDialogReturn(returnValue, dialogObject) {\n /**\n dialogObject = {\n isFolder: false,\n newFileIcon: \"icdocx.png\",\n newFileSize: 18420,\n newFileUrl: \"/sites/testblanksite1/Documents/Document - 2017-43-17_030239.docx\"\n }\n */\n console.info(\">>returned from new/upload form\");\n console.info(\"this (dataObject):\", this);\n console.info(\"returnValue:\", returnValue);\n console.info(\"dialogObject:\", dialogObject);\n if (returnValue === SP.UI.DialogResult.OK && (this.postUploadUrl)) {\n //GoToPage(this.postUploadUrl);\n ShowPopupDialogWithCallback(this.postUploadUrl, function(returnValue, dialogObject) {\n console.info(\">>returned from post new/upload navigate URL\");\n console.info(\"returnValue:\", returnValue);\n console.info(\"dialogObject:\", dialogObject);\n });\n }\n }\n\n function fail(c, b) {\n console.error(b.get_message());\n alert(\"Critical Error: \" + b.get_message());\n }\n}\n\nfunction exec() {\n console.info(\">> in exec()\");\n SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n createNewLibraryContent(\"Videos\", _spPageContextInfo.webServerRelativeUrl);\n });\n}\n\nconsole.clear();\nexec();\n"
},
{
"id": "32",
"name": "CommentingCreateFolderAndListItem",
"content": "window.gCounter = window.gCounter || 100;\n\nfunction createFolderName(webId, listId, itemId) {\n webId = typeof webId !== \"undefined\" && webId ? `${webId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n listId = typeof listId !== \"undefined\" && listId ? `-${listId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n itemId = typeof itemId !== \"undefined\" ? `-${Math.max(_spPageContextInfo.pageItemId,0)}` : \"\"; \n\n var folderName = `${webId}${listId}${itemId}`;\n return folderName.toLowerCase();\n}\n\nfunction createComment(commentBody, parentId, folderName, commentTargetUrl, listName) {\n folderName = folderName || createFolderName(_spPageContextInfo.webId, _spPageContextInfo.pageListId, _spPageContextInfo.pageItemId);\n commentTargetUrl = commentTargetUrl || window.location.href;\n listName = listName || \"Comments\";\n parentId = Math.max(parentId, 0);\n\n var ctx = new SP.ClientContext(_spPageContextInfo.siteServerRelativeUrl);\n var list = ctx.get_web().get_lists().getByTitle(listName);\n\n function getCommentFolder() {\n var pGotFolder = new $.Deferred();\n var rootFolder = list.get_rootFolder();\n var itemCreationInfo = new SP.ListItemCreationInformation();\n itemCreationInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);\n itemCreationInfo.set_leafName(folderName);\n var newFolder = list.addItem(itemCreationInfo);\n newFolder.set_item(\"Title\", folderName);\n newFolder.update();\n\n ctx.load(list);\n ctx.load(rootFolder, \"ServerRelativeUrl\");\n ctx.executeQueryAsync(() => {\n pGotFolder.resolve({ \n folderUrl: rootFolder.get_serverRelativeUrl() + \"/\" + folderName, \n isNewFolder: true \n });\n }, (sender, args) => {\n if ((args.get_errorCode() === -2130245363) || (args.get_message().match(/^a file or folder with the name.*already exists.?$/gi) )) {\n pGotFolder.resolve({\n folderUrl: _spPageContextInfo.webServerRelativeUrl + \"/Lists/\" + listName + \"/\" + folderName, \n isNewFolder: false\n });\n } else {\n console.info(\"GOTFOLDER: failed, \", arguments);\n pGotFolder.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n }\n });\n\n return pGotFolder.promise(); \n }\n\n function createCommentItem(folderResponse) {\n var pGotItem = new $.Deferred();\n var title = SP.Guid.newGuid().toString().replace(/[\\{\\}-]*/gi, '');\n var itemCreateInfo = new SP.ListItemCreationInformation();\n itemCreateInfo.set_folderUrl(folderResponse.folderUrl);\n\n var listItem = list.addItem(itemCreateInfo);\n listItem.set_item(\"Title\", title);\n listItem.set_item(\"Comment\", commentBody || \"\");\n listItem.set_item(\"URL\", commentTargetUrl);\n listItem.set_item(\"ParentId\", parentId);\n /*listItem.set_item(\"Person\", _spPageContextInfo.userId);*/\n \n listItem.update();\n ctx.load(listItem, \"ID\");\n ctx.executeQueryAsync( (sender, args) => {\n pGotItem.resolve({ \n id: listItem.get_id(),\n commentFolderUrl: folderResponse.folderUrl, \n commentId: title,\n isNewFolder: folderResponse.isNewFolder\n });\n }, (sender, args) => {\n console.info(\"CreateCommentItem: failed, \", args);\n pGotItem.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n });\n\n return pGotItem.promise();\n }\n\n return getCommentFolder()\n .then(createCommentItem)\n .then(function(commentResponse) {\n return commentResponse;\n }, function(errorResponse) {\n console.error(\"Failed to add comment: \", errorResponse);\n return errorResponse;\n });\n}\n\nfunction exec() {\n console.info(\">> in exec()\");\n SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n var commentBody = \"This is the (\"+(++gCounter)+\") comment body,\\r\\nIt should span multiple\\r\\nlines - \" + (new Date().getTime());\n var commentTargetUrl = window.location.href;\n var commentFolder = \"\";\n var replyToId = 209;\n replyToId = 0;\n //commentTargetUrl = _spPageContextInfo.siteAbsoluteUrl;\n //commentFolder = _spPageContextInfo.webId.replace(/[\\{\\}-]*/gi, ''); // web\n //commentFolder = _spPageContextInfo.siteId.replace(/[\\{\\}-]*/gi, ''); // site\n\n createComment(commentBody, replyToId, commentFolder, commentTargetUrl)\n .then((response) => {\n console.info(\"SUCCESS \", response);\n }, (error) => {\n console.error(\"ERROR!!! \", response);\n });\n\n });\n}\n\nconsole.clear();\nexec();\n"
},
{
"id": "33",
"name": "CommentingGetListItemsFromFolder",
"content": "function createFolderName(webId, listId, itemId) {\n webId = typeof webId !== \"undefined\" && webId ? `${webId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n listId = typeof listId !== \"undefined\" && listId ? `-${listId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n itemId = typeof itemId !== \"undefined\" ? `-${Math.max(_spPageContextInfo.pageItemId,0)}` : \"\"; \n\n var folderName = `${webId}${listId}${itemId}`;\n return folderName.toLowerCase();\n}\n\nfunction getCommentsCount(folderName, listName) {\n folderName = folderName || createFolderName(_spPageContextInfo.webId, _spPageContextInfo.pageListId, _spPageContextInfo.pageItemId);\n listName = listName || \"Comments\";\n\n var columns = [\"ContentTypeId\", \"Title\", \"Comment\", \"Id\", \"URL\", \"Editor\", \"Modified\"];\n var ctx = new SP.ClientContext(_spPageContextInfo.siteServerRelativeUrl);\n var list = null;\n\n function getCommentFolder() {\n var d = new $.Deferred();\n\n list = ctx.get_web().get_lists().getByTitle(listName);\n var rootFolder = list.get_rootFolder();\n ctx.load(list);\n ctx.load(rootFolder, \"ServerRelativeUrl\");\n ctx.executeQueryAsync(() => {\n d.resolve({\n targetFolderUrl: rootFolder.get_serverRelativeUrl() + \"/\" + folderName\n });\n }, (sender, args) => {\n console.info(\"GETFOLDER FAILED,\", arguments);\n d.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n });\n return d.promise();\n }\n\n function getCommentsCount(folderResponse) {\n var d = new $.Deferred();\n\n var query = \"<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name=\\\"ParentId\\\" Ascending=\\\"TRUE\\\" /><FieldRef Name=\\\"Modified\\\" Ascending=\\\"FALSE\\\" /></OrderBy></Query></View>\";\n var camlQuery = new SP.CamlQuery();\n camlQuery.set_viewXml(query);\n camlQuery.set_folderServerRelativeUrl(folderResponse.targetFolderUrl);\n var allItems = list.getItems(camlQuery);\n ctx.load(allItems/*, \"Include(\"+columns.join(',')+\")\"*/);\n ctx.executeQueryAsync(() => {\n d.resolve({\n targetFolderUrl: folderResponse.targetFolderUrl,\n commentCount: allItems.get_count()\n });\n }, (sender, args) => {\n console.info(\"GETCOMMENTSCOUNT FAILED,\", arguments);\n d.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n });\n return d.promise();\n }\n\n return getCommentFolder()\n .then(getCommentsCount);\n}\n\nfunction getComments(folderName, listName) {\n folderName = folderName || createFolderName(_spPageContextInfo.webId, _spPageContextInfo.pageListId, _spPageContextInfo.pageItemId);\n listName = listName || \"Comments\";\n\n var columns = [\"ContentTypeId\", \"Title\", \"Comment\", \"Id\", \"URL\", \"Editor\", \"Modified\"];\n var ctx = new SP.ClientContext(_spPageContextInfo.siteServerRelativeUrl);\n var list = null;\n\n function getCommentFolder() {\n var d = new $.Deferred();\n\n list = ctx.get_web().get_lists().getByTitle(listName);\n var rootFolder = list.get_rootFolder();\n ctx.load(list);\n ctx.load(rootFolder, \"ServerRelativeUrl\");\n ctx.executeQueryAsync(() => {\n d.resolve({\n targetFolderUrl: rootFolder.get_serverRelativeUrl() + \"/\" + folderName\n });\n }, (sender, args) => {\n console.info(\"GETFOLDER FAILED,\", arguments);\n d.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n });\n return d.promise();\n }\n\n function getComments(folderResponse) {\n var d = new $.Deferred();\n\n var query = \"<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name=\\\"ParentId\\\" Ascending=\\\"TRUE\\\" /><FieldRef Name=\\\"Modified\\\" Ascending=\\\"FALSE\\\" /></OrderBy></Query></View>\";\n var camlQuery = new SP.CamlQuery();\n camlQuery.set_viewXml(query);\n camlQuery.set_folderServerRelativeUrl(folderResponse.targetFolderUrl);\n var allItems = list.getItems(camlQuery);\n ctx.load(allItems/*, \"Include(\"+columns.join(',')+\")\"*/);\n ctx.executeQueryAsync(() => {\n var allComments = [];\n for(var i = 0; i < allItems.get_count();i++) {\n var listItem = allItems.getItemAtIndex(i);\n var url = listItem.get_item(\"URL\");\n var editor = listItem.get_item(\"Editor\");\n\n var newItem = {};\n //newItem.ContentType = listItem.get_contentType().get_name();\n newItem.Id = listItem.get_id();\n newItem.ParentId = listItem.get_item(\"ParentId\");\n newItem.PublishedDate = listItem.get_item(\"Modified\");\n newItem.DisplayPublishedDate = newItem.PublishedDate.format(\"hh:mm on dddd MMM yyyy\");\n newItem.CommentId = listItem.get_item(\"Title\") || \"\";\n newItem.Comment = listItem.get_item(\"Comment\") || \"\";\n newItem.TargetUrl = (url && url.get_url()) || \"\";\n newItem.Author = {\n id: editor.get_lookupId(),\n email: editor.get_email(),\n displayTitle: editor.get_lookupValue(),\n photo: _spPageContextInfo.siteAbsoluteUrl + \"/_vti_bin/DelveApi.ashx/people/profileimage?userId=\" + editor.get_email() + \"&size=S\"\n };\n allComments.push(newItem);\n }\n\n var mappedComments = allComments\n .filter((e) => { return e.ParentId === 0; })\n .map((e) => {\n var parentItem = e;\n parentItem.replies = allComments\n .filter((c) => { return c.ParentId === e.Id; })\n .reverse();\n return parentItem;\n });\n d.resolve(mappedComments);\n }, (sender, args) => {\n console.info(\"GETCOMMENTS FAILED,\", arguments);\n d.reject({\n code: args.get_errorCode(),\n message: args.get_message()\n });\n });\n return d.promise();\n }\n\n return getCommentFolder()\n .then(getComments);\n}\n\nfunction exec() {\n console.info(\">> in exec()\");\n SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n \n getCommentsCount()\n .then((countResponse) => {\n console.info(\"COMMENTS COUNT\", countResponse);\n })\n .then(getComments)\n .then((commentsReponse) => {\n console.info(\"COMMENTS\", commentsReponse);\n window.commentsReponse = commentsReponse;\n }, (errorResponse) => {\n console.error(\"ERROR!!!\", errorResponse);\n });\n\n });\n}\n\nconsole.clear();\nexec();\n"
},
{
"id": "34",
"name": "Likes",
"content": "function AjaxErrorResponse() {}\n\nfunction createItemName(webId, listId, itemId, elementId) {\n webId = typeof webId !== \"undefined\" && webId ? `${webId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n listId = typeof listId !== \"undefined\" && listId ? `-${listId.replace(/[\\{\\}-]*/gi, \"\")}` : \"\";\n itemId = typeof itemId !== \"undefined\" ? `-${Math.max(_spPageContextInfo.pageItemId,0)}` : \"\";\n elementId = typeof elementId !== \"undefined\" ? `-${elementId}` : \"-0\";\n\n var itemName = `${webId}${listId}${itemId}${elementId}`;\n return itemName.toLowerCase();\n}\n\nfunction getRatedItem(options) {\n var opts = { ...options };\n\n opts.itemName = opts.itemName || createItemName(_spPageContextInfo.webId, _spPageContextInfo.pageListId, _spPageContextInfo.pageItemId, opts.elementId);\n opts.targetUrl = opts.targetUrl || window.location.href;\n opts.listName = opts.listName || \"HiddenSocialItems\";\n\n opts.webUrl = (typeof opts.webUrl === \"undefined\" || !opts.webUrl) ? _spPageContextInfo.siteServerRelativeUrl : opts.webUrl;\n const method = opts.listName.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) ?\n\t\t\t\"getById\" :\n\t\t\t\"getByTitle\";\n const filterExpression = `&$filter=Title eq '${opts.itemName}'`;\n const endpoint = `_api/web/lists/${method}('${opts.listName}')/items?$top=1&$select=ID,Title,URL,LikesCount,LikedByStringId${filterExpression}`;\n const restOps = {\n url: `${opts.webUrl}/${endpoint}`,\n type: \"GET\",\n headers: {\n \"Accept\": \"application/json;odata=nometadata\",\n },\n };\n let d = new $.Deferred();\n $.ajax(restOps)\n /*.then(AjaxResponse.NormaliseResponse)*/\n .then((response) => {\n let d1 = new $.Deferred();\n if (!response.value.length) {\n /* rating item for element not found - create one */\n console.log(`>>>Nothing found for: ${opts.itemName} -- CREATING ONE`);\n restOps.url = `${opts.webUrl}/_api/web/lists/${method}('${opts.listName}')/items`;\n restOps.method = \"POST\";\n restOps.headers[\"X-RequestDigest\"] = $(\"#__REQUESTDIGEST\").val();\n restOps.headers[\"Content-Type\"] = \"application/json;odata=nometadata\";\n restOps.data = JSON.stringify({\n \"Title\": opts.itemName,\n \"URL\": {\n \"Description\": opts.targetUrl,\n \"Url\": opts.targetUrl\n },\n \"LikesCount\": 0,\n \"LikedByStringId\": []\n });\n $.ajax(restOps)\n .then((response) => {\n /* resolve created rating item */\n console.log(`>>>CREATED RATING ITEM for: ${opts.itemName} -- DONE`);\n d1.resolve({ value: [response] });\n })\n .fail((jqXhr, textStatus) => {\n /* reject failed-created rating item */\n console.log(\"ERROR [AddRatedItem]: \", jqXhr.responseText);\n const r = new AjaxErrorResponse(\n \"[AddRatedItem]\",\n `listName: ${options.listName}\\nwebUrl: ${options.webUrl}\\nmethod: ${method}`,\n jqXhr, textStatus);\n d1.reject(r);\n }); \n /**/\n } else {\n /* resolve found rating item */\n d1.resolve(response);\n }\n return d1.promise();\n })\n .then((response) => {\n const mapped = response.value.map((e, index) => {\n const linkLocation = e.URL.Url;\n const linkLabel = e.URL.Description || e.URL.Url;\n const isExt = (linkLocation.match(/^http[s]?:\\/\\//gi) && (linkLocation.indexOf(window.location.host) < 0));\n return {\n Id: e.ID || e.Id,\n Title: e.Title,\n TargetLinkLocation: linkLocation,\n TargetLinkLabel: linkLabel,\n LikesCount: e.LikesCount,\n LikedBy: e.LikedByStringId,\n };\n });\n d.resolve(mapped && mapped.length ? mapped[0] : null);\n })\n .fail((jqXhr, textStatus) => {\n console.log(\"ERROR [GetRatedItem]: \", jqXhr.responseText);\n const r = new AjaxErrorResponse(\n \"[GetRatedItem]\",\n `listName: ${options.listName}\\nwebUrl: ${options.webUrl}\\nmethod: ${method}`,\n jqXhr, textStatus);\n d.reject(r);\n });\n return d.promise();\n}\n\n\nfunction exec() {\n const start = (new Date()).getTime();\n console.info(\">> in exec()\");\n const options = { elementId: \"bubble:r07\", itemName: \"\", targetUrl: \"\", listName: \"\", webUrl: \"\" };\n getRatedItem(options)\n .then((response) => {\n console.info(\"Got Rated Item: \", response, response && response.Title && response.Title.length);\n const end = (new Date()).getTime();\n console.log(`Took: ${(end - start)/1000} seconds`)\n });\n}\n\nconsole.clear();\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.info(\">> loaded SP.js\");\n\n SP.SOD.registerSod(\"reputation.js\", _spPageContextInfo.siteAbsoluteUrl + \"/_layouts/15/reputation.js\");\n SP.SOD.executeFunc(\"reputation.js\", \"Microsoft.Office.Server.ReputationModel.Reputation\", function() {\n console.info(\">> loaded reputation.js\");\n exec();\n });\n \n});\n"
},
{
"id": "35",
"name": "Get List Permission",
"content": "SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {\n console.clear();\n console.log(\"SP.js loaded\");\n console.log(_spPageContextInfo.userLoginName);\n\n var listName = \"Drop Off Library\";\n //listName = \"All Documents\";\n getListByTitleCSOM(listName);\n\n var columns = [\"DocumentTemplateUrl\",\"EffectiveBasePermissions\",\"EnableVersioning\",\"EnableMinorVersions\",\"EnableModeration\",\"ForceCheckout\",\"RootFolder/ServerRelativeUrl\"];\n var expand = [\"RootFolder\"];\n getListByTitleREST(listName, columns, expand)\n .then((list) => {\n console.log(`REST: ${listName}`, list.EffectiveBasePermissions);\n var perms = new SP.BasePermissions();\n perms.fromJson(list.EffectiveBasePermissions);\n console.log(`REST: ${listName}`, perms);\n if (perms.has(SP.PermissionKind.editListItems)) {\n console.log(`REST: \"${_spPageContextInfo.userLoginName}\" HAS edit permission to \"${list.Title}\"`);\n } else {\n console.log(`REST: \"${_spPageContextInfo.userLoginName}\" does not have edit permission to \"${list.Title}\"`);\n }\n console.log(`REST: ${enumeratePermissions(perms)}`);\n });\n});\n\nfunction getListByTitleCSOM(listName) {\n var web, clientContext, currentUser, list;\n\n clientContext = new SP.ClientContext.get_current();\n web = clientContext.get_web();\n currentUser = web.get_currentUser();\n list = web.get_lists().getByTitle(listName);\n clientContext.load(list, 'DocumentTemplateUrl');\n clientContext.load(list, 'EffectiveBasePermissions');\n clientContext.load(list, 'EnableVersioning');\n clientContext.load(list, 'EnableMinorVersions');\n clientContext.load(list, 'EnableModeration');\n clientContext.load(list, 'ForceCheckout');\n clientContext.load(list, 'RootFolder');\n clientContext.load(list, 'Id');\n clientContext.load(list, 'Title');\n clientContext.load(currentUser);\n clientContext.load(web);\n\n clientContext.executeQueryAsync(function() {\n console.log(\"CSOM: \", list.get_id().toString());\n console.log(\"CSOM: \", list.get_title());\n console.log(\"CSOM: \", list.get_documentTemplateUrl());\n console.log(\"CSOM: \", list.get_effectiveBasePermissions());\n console.log(\"CSOM: \", list.get_enableVersioning());\n console.log(\"CSOM: \", list.get_enableMinorVersions());\n console.log(\"CSOM: \", list.get_enableModeration());\n console.log(\"CSOM: \", list.get_forceCheckout());\n console.log(\"CSOM: \", list.get_rootFolder().get_serverRelativeUrl());\n\n console.log(\"CSOM: \", currentUser.get_email());\n var perms = list.get_effectiveBasePermissions();\n if (list.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems)) {\n console.log(`CSOM: \"${_spPageContextInfo.userLoginName}\" HAS edit permission to \"${list.get_title()}\"`);\n } else {\n console.log(`CSOM: \"${_spPageContextInfo.userLoginName}\" does not have edit permission to \"${list.get_title()}\"`);\n }\n console.log(`CSOM: ${enumeratePermissions(perms)}`);\n }, function(sender, args) {\n console.log('request failed ' + args.get_message() + '\\n' + args.get_stackTrace());\n });\n}\nfunction getListByTitleREST(listTitle, columns, expandList, webUrl) {\n var select = [\"Id,Title\"].concat((columns || []));\n var pExpand = expandList && expandList.length ?\n String.format(\"&$expand={0}\", ([].concat(expandList)).join(\",\")) :\n \"\";\n\n webUrl = webUrl || _spPageContextInfo.webAbsoluteUrl;\n var request = {\n type: 'GET',\n url: String.format(\"{0}/_api/web/lists/getByTitle('{1}')?$select={2}{3}\",\n webUrl.replace(/\\/$/gi, ''),\n listTitle,\n select.join(','),\n pExpand),\n headers: {\n \"Accept\": \"application/json;odata=nometadata\",\n },\n };\n var p = new $.Deferred(function(d) {\n $.ajax(request).then(function (response) {\n d.resolve(response);\n }, function(xhr, textStatus) {\n console.error(arguments);\n var r = new AjaxErrorResponse(\n \"[getListByTitle]\", \n String.format('listTitle: {0}\\nwebUrl: {1}\\nexpandList: {2}', listTitle, webUrl, pExpand), \n xhr, textStatus);\n d.reject(r);\n });\n });\n return p.promise();\n}\nfunction enumeratePermissions(basePermissions) {\n var perms = [];\n for(key in SP.PermissionKind.prototype) {\n if (SP.PermissionKind.prototype.hasOwnProperty(key)) {\n if (basePermissions.has(SP.PermissionKind.prototype[key])) {\n perms.push(`${key}`); \n } \n }\n }\n return perms;\n}"
},
{
"id": "36",
"name": "TreePickerDialog",
"content": "console.clear();\nSP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {\n console.info(\">> loaded SP.js\");\n\n SP.SOD.registerSod(\"PickerTreeDialog.js\", _spPageContextInfo.siteAbsoluteUrl + \"/_layouts/15/PickerTreeDialog.js\");\n SP.SOD.executeFunc(\"PickerTreeDialog.js\", \"LaunchPickerTreeDialog\", function() {\n console.info(\">> loaded PickerTreeDialog.js\");\n LaunchPickerTree();\n });\n\n});\n\nfunction callback(arr) {\n console.log(\"in Callback(arr)\", arr);\n if (arr == null || arr == undefined)\n return;\n\n console.log(\"in Callback(arr)\", arr);\n}\n\nfunction LaunchPickerTree() {\n console.log(\"in LaunchPickerTree()\");\n\n var hostUrl = _spPageContextInfo.siteAbsoluteUrl; \n LaunchPickerTreeDialog(\n \"CbqPickerSelectListTitle\", \n \"CbqPickerSelectListText\", \n \"websLists\", \n \"\", \n hostUrl, \n \"\", \n \"\", \n \"\", \n \"/_layouts/images/Copy.gif\", \n 0, \n callback,\n \"\", \n \"\");\n}\n"
},
{
"name": "GraphFromClassic",
"content": "(async function() {\n\nfunction getAccessToken(resource) {\n return new Promise( async (resolve, reject) => {\n\n var body = {\n \"resource\": resource || \"https://graph.microsoft.com\"\n };\n const url = `${_spPageContextInfo.webAbsoluteUrl}/_api/SP.OAuth.Token/Acquire`;\n const response = await fetch(url, {\n \"credentials\": \"include\",\n \"method\": \"POST\",\n \"headers\": {\n \"X-RequestDigest\": _spPageContextInfo.formDigestValue,\n \"Accept\": \"application/json;odata=nometadata\",\n \"Content-Type\": \"application/json;odata=nometadata\"\n },\n \"body\": JSON.stringify(body)\n });\n const data = await response.json();\n\n console.info(data);\n var accessToken = data.access_token;\n resolve(accessToken);\n \n });\n}\nfunction getGroups(accessToken) {\n return new Promise( async (resolve, reject) => {\n\n const url = `https://graph.microsoft.com/v1.0/groups`;\n const response = await fetch(url, {\n \"method\": \"GET\",\n \"headers\": {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${accessToken}`,\n },\n });\n const data = await response.json();\n\n console.info(data);\n resolve(data);\n \n });\n}\n\nconsole.clear();\n\nconst accessToken = await getAccessToken(\"https://graph.microsoft.com\");\nconsole.info(\"accessToken\", accessToken);\n\nconst groups = await getGroups(accessToken);\nconsole.info(\"groups\", groups.value);\n\n})();\n\n"
},
{
"name": "findStartingApprovalRouteIndex",
"content": "var contractOwner = \"phil@platinumdogs.co.uk\";\nvar routes = [\n { // 0\n id: 10,\n email: \"phil@platinumdogs.co.uk\",\n role: \"Area Sales Manager\"\n },\n { // 1\n id: 10,\n email: \"phil1@platinumdogs.co.uk\",\n role: \"Category Manager\"\n },\n { // 2\n id: 10,\n email: \"phil1@platinumdogs.co.uk\",\n role: \"Site Manager\"\n },\n { // 3\n id: 10,\n email: \"phil1@platinumdogs.co.uk\",\n role: \"Business Manager\"\n },\n { // 4\n id: 10,\n email: \"phil@platinumdogs.co.uk\",\n role: \"Procurement Director\"\n },\n];\n\nfunction findStartingApprovalRouteIndex(approvalRoutes, contractOwnerEmail, ignoreTrailingCount = 1) {\n console.clear();\n\n var startIndex = 0;\n var subjectApprovalRoutes = approvalRoutes.slice(0, approvalRoutes.length - ignoreTrailingCount).reverse();\n \n var lastIndex = subjectApprovalRoutes.findIndex( (e) => e.email === contractOwnerEmail );\n if ((lastIndex > -1)) {\n console.log(\"routes\", approvalRoutes);\n console.log(\"subjectRoutes\", subjectApprovalRoutes);\n console.log(\"subjectRoutes lastIndexOf\", lastIndex);\n\n lastIndex = (approvalRoutes.length) - (lastIndex + ignoreTrailingCount);\n startIndex = lastIndex;\n console.log(\"normalised lastIndexOf\", startIndex );\n } else {\n console.log(\"No occurances of ContractOwner\");\n }\n return startIndex;\n}\n\nvar startApprovalRouteIndex = findStartingApprovalRouteIndex(routes, contractOwner, 1);\nconsole.log(\"startApprovalRouteIndex\", startApprovalRouteIndex);\n"
},
{
"name": "ShowDiscussionsListViewDialog",
"content": "/*\nhttps://platinumdogsconsulting.sharepoint.com/teams/InovynDOA/Lists/Discussions/Flat.aspx?IsDlg=1&amp;RootFolder=%2Fteams%2FInovynDOA%2FLists%2FDiscussions%2FPINVDOA-S-99880054_S35&amp;FolderCTID=0x01200200A18EDD12A2019448A853A28F767A0C68\n*/\n\nfunction showConversationsDialog(e) {\n e.preventDefault();\n\n var dialogUrl = e.data && e.data.url && e.data.url.length ? e.data.url : \"\";\n\n /* set dialog options and call dialog */\n var dialogOptions = {\n url: `${dialogUrl}&IsDlg=1`,\n title: (e.data && e.data.dialogTitle && e.data.dialogTitle.length) ? e.data.dialogTitle : \"Dialog Title\",\n showClose: true,\n allowMaximize: true,\n autoSize: false,\n dialogReturnValueCallback: function(dialogResult, returnValue) {\n console.log(`Conversations Dialog closed, dialogResult: ${dialogResult}, returnValue: ${returnValue}`);\n }\n };\n console.log(`Print View Dialog url: ${dialogOptions.url || \"\"}`);\n SP.SOD.execute(\"SP.UI.Dialog.js\", \"SP.UI.ModalDialog.showModalDialog\", dialogOptions);\n console.log(\"Conversations Dialog loaded...\");\n return false;\n}\n\n$(\"#btnDiscuss\").off(\"click\");\nvar options = {\n url: \"https://platinumdogsconsulting.sharepoint.com/teams/InovynDOA/Lists/Discussions/Flat.aspx?RootFolder=%2Fteams%2FInovynDOA%2FLists%2FDiscussions%2FPINVDOA-S-99880054_S35&FolderCTID=0x01200200A18EDD12A2019448A853A28F767A0C68\",\n dialogTitle: \"Conversation\"\n};\n$(\"#btnDiscuss\").on(\"click\", options, showConversationsDialog);\n"
},
{
"name": "CreateListItemInOtherSite",
"content": "(async function() {\n\nfunction getFailedResponseData(response) {\n return new Promise( async (resolve) => {\n\n const ct = response.headers.get(\"Content-Type\") || \"\";\n let data = {};\n if (ct.match(\"application/json\")) {\n data = await response.json();\n } else {\n data = {\n \"odata.error\": {\n \"code\": `0x8000FFFF, E_UNEXPECTED, httpStatus(${response.status}${response.statusText ? \", \" + response.statusText : \"\"})`,\n \"message\": {\n \"lang\": \"en-us\",\n \"value\": await response.text()\n }\n }\n }\n }\n resolve(data);\n\n });\n}\n\nfunction getSiteContextInfo(siteUrl) {\n return new Promise( async (resolve, reject) => {\n\n const url = `${siteUrl}/_api/contextinfo`;\n const response = await fetch(url, {\n \"credentials\": \"include\",\n \"method\": \"POST\",\n \"headers\": {\n \"Accept\": \"application/json;odata=nometadata\",\n \"Cache-Control\": \"no-cache\"\n },\n });\n\n if (response.ok) {\n const data = await response.json();\n resolve({\n \"formDigest\": data.FormDigestValue || \"\",\n \"webFullUrl\": `${data.WebFullUrl}`\n });\n } else {\n let data = await getFailedResponseData(response);\n reject(data);\n }\n\n });\n}\nfunction addEDMSOperation(siteContext, opRequest) {\n return new Promise( async (resolve, reject) => {\n\n const body = {\n \"Title\": opRequest.EDMSTargetItemUrl || \"\",\n \"EDMSTargetSiteUrl\": opRequest.EDMSTargetSiteUrl || \"\",\n \"EDMSTargetSiteId\": opRequest.EDMSTargetSiteId || \"\",\n \"EDMSTargetWebId\": opRequest.EDMSTargetWebId || \"\",\n \"EDMSTargetListId\": opRequest.EDMSTargetListId || \"\",\n \"EDMSTargetItemId\": opRequest.EDMSTargetItemId || \"\",\n \"EDMSAction\": opRequest.EDMSAction || \"\",\n \"EDMSOperationStatus\": \"Pending\",\n \"EDMSOperationOutcome\": \"Pending\"\n };\n const url = `${siteContext.webFullUrl}/_api/web/lists/GetByTitle('EDMS Transactions')/items`;\n const response = await fetch(url, {\n \"credentials\": \"include\",\n \"method\": \"POST\",\n \"headers\": {\n \"X-RequestDigest\": `${siteContext.formDigest}`,\n \"Accept\": \"application/json;odata=nometadata\",\n \"Content-Type\": \"application/json;odata=nometadata\",\n \"Cache-Control\": \"no-cache\"\n },\n \"body\": JSON.stringify(body)\n });\n\n if (response.ok) {\n const data = await response.json();\n resolve(data);\n } else {\n let data = await getFailedResponseData(response);\n reject(data);\n }\n });\n}\n\nlet siteContext = null;\nconst otherSiteUrl = \"https://platinumdogsconsulting.sharepoint.com/sites/hubsitetest\";\n//const otherSiteUrl = \"https://platinumdogsconsulting.sharepoint.com/sites/audiotonix\";\ntry {\n siteContext = await getSiteContextInfo(otherSiteUrl);\n console.log(`CONTEXTINFO site: ${siteContext.webFullUrl}`);\n console.log(`CONTEXTINFO digest: ${siteContext.formDigest}`);\n} catch(e) {\n console.warn(`ERROR GETTING CONTEXTINFO for [${otherSiteUrl}]: `, e);\n}\n\nif (siteContext) {\n try {\n //\"https://platinumdogsconsulting.sharepoint.com/sites/hubsitetest/Lists/EDMS%20Transactions/AllItems.aspx\"\n const opRequest = {\n \"EDMSTargetItemUrl\": `${window.location.href}`,\n \"EDMSTargetSiteUrl\": `${_spPageContextInfo.webServerRelativeUrl}`,\n \"EDMSTargetSiteId\": `${_spPageContextInfo.siteId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetWebId\": `${_spPageContextInfo.webId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetListId\": `${_spPageContextInfo.listId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetItemId\": `${_spPageContextInfo.pageItemId}`,\n \"EDMSAction\": \"Close\"\n }\n\n const opData = await addEDMSOperation(siteContext, opRequest);\n console.log(`ADDEDMSOPERATION at ${siteContext.webFullUrl}`, opData);\n } catch(e) {\n console.warn(`ERROR CALLING ADDEDMSOPERATION for [${siteContext.webFullUrl}]: `, e);\n }\n}\n\n\n})();"
},
{
"name": "Get O365 Groups using Graph on Classic SP Page.js",
"content": "(async function() {\n\nfunction getAccessToken(resource) {\n return new Promise( async (resolve, reject) => {\n\n var body = {\n \"resource\": resource || \"https://graph.microsoft.com\"\n };\n const url = `${_spPageContextInfo.webAbsoluteUrl}/_api/SP.OAuth.Token/Acquire`;\n const response = await fetch(url, {\n \"method\": \"POST\",\n \"headers\": {\n \"X-RequestDigest\": _spPageContextInfo.formDigestValue,\n \"Accept\": \"application/json;odata=nometadata\",\n \"Content-Type\": \"application/json;odata=nometadata\"\n },\n \"body\": JSON.stringify(body)\n });\n const data = await response.json();\n\n console.info(data);\n var accessToken = data.access_token;\n resolve(accessToken);\n \n });\n}\nfunction getGroups(accessToken) {\n return new Promise( async (resolve, reject) => {\n\n const url = `https://graph.microsoft.com/v1.0/groups`;\n const response = await fetch(url, {\n \"method\": \"GET\",\n \"headers\": {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${accessToken}`,\n },\n });\n const data = await response.json();\n\n console.info(data);\n resolve(data);\n \n });\n}\n\nconsole.clear();\n\nconst accessToken = await getAccessToken(\"https://graph.microsoft.com\");\nconsole.info(\"accessToken\", accessToken);\n\nconst groups = await getGroups(accessToken);\nconsole.info(\"groups\", groups.value);\n\n})();"
},
{
"name": "Create a ListItem in another site using the REST API",
"content": "(async function() {\n\nfunction getFailedResponseData(response) {\n return new Promise( async (resolve) => {\n\n const ct = response.headers.get(\"Content-Type\") || \"\";\n let data = {};\n if (ct.match(\"application/json\")) {\n data = await response.json();\n } else {\n data = {\n \"odata.error\": {\n \"code\": `0x8000FFFF, E_UNEXPECTED, httpStatus(${response.status}${response.statusText ? \", \" + response.statusText : \"\"})`,\n \"message\": {\n \"lang\": \"en-us\",\n \"value\": await response.text()\n }\n }\n }\n }\n resolve(data);\n\n });\n}\n\nfunction getSiteContextInfo(siteUrl) {\n return new Promise( async (resolve, reject) => {\n\n const url = `${siteUrl}/_api/contextinfo`;\n const response = await fetch(url, {\n \"credentials\": \"include\",\n \"method\": \"POST\",\n \"headers\": {\n \"Accept\": \"application/json;odata=nometadata\",\n \"Cache-Control\": \"no-cache\"\n },\n });\n\n if (response.ok) {\n const data = await response.json();\n resolve({\n \"formDigest\": data.FormDigestValue || \"\",\n \"webFullUrl\": `${data.WebFullUrl}`\n });\n } else {\n let data = await getFailedResponseData(response);\n reject(data);\n }\n\n });\n}\nfunction addEDMSOperation(siteContext, opRequest) {\n return new Promise( async (resolve, reject) => {\n\n const body = {\n \"Title\": opRequest.EDMSTargetItemUrl || \"\",\n \"EDMSTargetSiteUrl\": opRequest.EDMSTargetSiteUrl || \"\",\n \"EDMSTargetSiteId\": opRequest.EDMSTargetSiteId || \"\",\n \"EDMSTargetWebId\": opRequest.EDMSTargetWebId || \"\",\n \"EDMSTargetListId\": opRequest.EDMSTargetListId || \"\",\n \"EDMSTargetItemId\": opRequest.EDMSTargetItemId || \"\",\n \"EDMSAction\": opRequest.EDMSAction || \"\",\n \"EDMSOperationStatus\": \"Pending\",\n \"EDMSOperationOutcome\": \"Pending\"\n };\n const url = `${siteContext.webFullUrl}/_api/web/lists/GetByTitle('EDMS Transactions')/items`;\n const response = await fetch(url, {\n \"credentials\": \"include\",\n \"method\": \"POST\",\n \"headers\": {\n \"X-RequestDigest\": `${siteContext.formDigest}`,\n \"Accept\": \"application/json;odata=nometadata\",\n \"Content-Type\": \"application/json;odata=nometadata\",\n \"Cache-Control\": \"no-cache\"\n },\n \"body\": JSON.stringify(body)\n });\n\n if (response.ok) {\n const data = await response.json();\n resolve(data);\n } else {\n let data = await getFailedResponseData(response);\n reject(data);\n }\n });\n}\n\nlet siteContext = null;\nconst otherSiteUrl = \"https://platinumdogsconsulting.sharepoint.com/sites/hubsitetest\";\n//const otherSiteUrl = \"https://platinumdogsconsulting.sharepoint.com/sites/audiotonix\";\ntry {\n siteContext = await getSiteContextInfo(otherSiteUrl);\n console.log(`CONTEXTINFO site: ${siteContext.webFullUrl}`);\n console.log(`CONTEXTINFO digest: ${siteContext.formDigest}`);\n} catch(e) {\n console.warn(`ERROR GETTING CONTEXTINFO for [${otherSiteUrl}]: `, e);\n}\n\nif (siteContext) {\n try {\n //\"https://platinumdogsconsulting.sharepoint.com/sites/hubsitetest/Lists/EDMS%20Transactions/AllItems.aspx\"\n const opRequest = {\n \"EDMSTargetItemUrl\": `${window.location.href}`,\n \"EDMSTargetSiteUrl\": `${_spPageContextInfo.webServerRelativeUrl}`,\n \"EDMSTargetSiteId\": `${_spPageContextInfo.siteId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetWebId\": `${_spPageContextInfo.webId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetListId\": `${_spPageContextInfo.listId.replace(/[\\{\\}]*/gi, '')}`,\n \"EDMSTargetItemId\": `${_spPageContextInfo.pageItemId}`,\n \"EDMSAction\": \"Close\"\n }\n\n const opData = await addEDMSOperation(siteContext, opRequest);\n console.log(`ADDEDMSOPERATION at ${siteContext.webFullUrl}`, opData);\n } catch(e) {\n console.warn(`ERROR CALLING ADDEDMSOPERATION for [${siteContext.webFullUrl}]: `, e);\n }\n}\n\n\n})();"
},
{
"name": "Get O365 Groups and Current User Profile using the Graph API and AdalJS",
"content": "console.clear();\n/* Logging levels\n 0: Error\n 1: Warning\n 2: Info\n 3: Verbose\n*/\n\n(function() {\n /* LOAD ADAL.JS onto the page \n see: https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/Installation\n */\n return new Promise( (resolve,reject) => {\n s = document.createElement(\"script\");\n s.src = \"https://secure.aadcdn.microsoftonline-p.com/lib/1.0.17/js/adal.min.js\"\n s.onload = function() {\n console.log(\">> Loaded: adal.min.js\");\n resolve();\n }\n document.getElementsByTagName(\"head\")[0].append(s);\n });\n}\n)().then( async () => {\n /* Use ADAL to perform a Silent Login and get an AccessToken */\n console.log(\">>> AdalJS is loaded, can start working...\");\n\n /* see: https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/Config-authentication-context */\n const clientId = _spPageContextInfo.spfx3rdPartyServicePrincipalId;\n const authContext = new AuthenticationContext({\n clientId: clientId,\n tenant: _spPageContextInfo.aadTenantId,\n redirectUri: window.location.origin + '/_forms/spfxsinglesignon.aspx',\n cacheLocation: 'sessionStorage' // Other option is localStorage\n });\n /* if ADAL logging is required, uncomment the lines below... */\n /*window.Logging = {\n level: 3,\n log: function (message) {\n console.log(message);\n },\n piiLoggingEnabled: true\n };*/\n\n /* to clear the ADAL local/session cache... */\n // authContext.clearCache();\n\n function silentLoginWithAccessToken() {\n return new Promise( (resolve, reject) => {\n console.info(\"Performing silenLogin()...\");\n authContext._renewToken(clientId, (errorMsg, token) => {\n if (!token || errorMsg) {\n const err = new Error(errorMsg || \"No Token and No Error Msg\");\n console.error(\"silentLoginWithAccessToken() error:\", err);\n reject(err);\n } else {\n const user = authContext.getCachedUser();\n resolve({ token, user });\n\n }\n }, authContext.RESPONSE_TYPE.ID_TOKEN_TOKEN);\n });\n }\n function getTokenForResource(resource) {\n return new Promise( (resolve, reject) => {\n console.info(`>>> Getting Token for ${resource} ...`);\n authContext.acquireToken(resource, (errorMsg, token) => {\n if (!token || errorMsg) {\n const err = new Error(errorMsg || \"No Token and No Error Msg\");\n console.error(`getTokenForResource(${resource}) error:`, err);\n reject(err);\n } else {\n resolve(token);\n }\n });\n });\n }\n function getGroups(accessToken) {\n return new Promise( async (resolve, reject) => {\n\n console.info(\">>> Getting Office 365 Groups...\");\n const url = `https://graph.microsoft.com/v1.0/groups`;\n const response = await fetch(url, {\n \"method\": \"GET\",\n \"headers\": {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${accessToken}`,\n },\n });\n const data = await response.json();\n\n console.info(data);\n resolve(data);\n\n });\n }\n function getMyProfile(accessToken) {\n return new Promise( async (resolve, reject) => {\n\n console.info(\">> Getting MyProfile...\");\n const url = `https://graph.microsoft.com/v1.0/me`;\n const response = await fetch(url, {\n \"method\": \"GET\",\n \"headers\": {\n \"Accept\": \"application/json\",\n \"Authorization\": `Bearer ${accessToken}`,\n },\n });\n const data = await response.json();\n\n console.info(data);\n resolve(data);\n\n });\n }\n\n try {\n\n const authData = await silentLoginWithAccessToken();\n console.info(\"authData\", authData);\n /* this access token is a user+id access token to the \"SharePoint Online Client Extensibility Web Application Principal\"\n app registration itself and cannot be used to access data from other APIs\n it can be used to exchange for an access token to another API though\n */\n console.info(`accessToken (${clientId})`, authData.token);\n\n /* get an access token to the graph API */\n const accessToken = await getTokenForResource(\"https://graph.microsoft.com\");\n console.info(\"accessToken (https://graph.microsoft.com)\", accessToken);\n\n const groups = await getGroups(accessToken);\n console.info(\"office 365 groups\", groups.value);\n\n const profile = await getMyProfile(accessToken);\n console.info(\"my profile\", profile);\n } catch (e) {\n console.error(\"CATCH: \", e);\n }\n\n\n});"
}
]
InspectorFrontendHost.setPreference("scriptSnippets", JSON.stringify(importSnippets));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment