CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

My PowerShell Profile

Screen Shot 2016-06-13 at 20.52.26

It has been a while I last worked with PowerShell. I had my custom profile where I had my own prompt and some other customizations. Now I cannot find it anymore. I’ll start with the new one and I am saving it on my blog, so it will be easier to find in future:

Function Prompt {
    $PromptData="PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
    $host.ui.RawUI.WindowTitle=$PromptData
       +'-'+(Get-Date).tostring()
    # .Link# http://go.microsoft.com/fwlink/?LinkID=225750
    # .ExternalHelp System.Management.Automation.dll-help.xml
}

The prompt function comes from the scripting guy blog.

To customize your profile, just open it in a text editor (in my case: code)

code $profile

 

Update Field.JSLink using JSOM or REST

Today I have just a little code snippet to share. This code snippet shows how to update the JSLink property for an existing field using JSOM and REST. For REST I use sharepoint-utilities.

var updateJsLinkCsom = function(config) {
	var ctx = SP.ClientContext.get_current();
	var web = ctx.get_web();
	var lists = web.get_lists();
	var list = lists.getByTitle(config.listTitle)
	var fields = list.get_fields();
	var field = fields.getByInternalNameOrTitle(config.fieldTitle)
	field.set_jsLink(config.jsLink)
	field.update()
	ctx.executeQueryAsync()
};
var updateJsLinkRest = function(config) {
	SP.SOD.registerSod('sputils.js', '<your cdn endpoint>/sputils.min.js')
	SP.SOD.executeFunc('sputils.js', '', function() {
		var url = _spPageContextInfo.webAbsoluteUrl
			+ '/_api/web/lists/getbytitle(\''
			+ config.listTitle + '\')/fields/getbyinternalnameortitle(\''+ config.fieldTitle + '\')';
		var payload = {'__metadata': {'type': 'SP.Field'}, 'JSLink': config.jsLink};
	    var config = {'headers' : {'X-HTTP-Method': 'MERGE' }};
		sputils.rest.post(url, payload, config);
	});
};
var config = {
	listTitle: '<your list title>',
	fieldTitle: '<your field title>',
	jsLink: '~site/<your jslink>'
};
updateJsLinkCsom(config);
updateJsLinkRest(config);

A couple of notes, to update a field we need:

  • A POST request
  • with a header ‘X-HTTP-Method’: ‘MERGE’
  • with __metadata: { type: SP.Field } and JSLink property in the payload
  • and X-RequestDigest‘ header (but it is nicely handled by sharepoint-utilities)

Trigger SP2010 Workflows using JSOM

Today I found out how to start workflows in JSOM (JavaScript Object Model in SharePoint). Nothing special, but since it is not documented, it took me a while to find a solution. Here is the code which I want to keep as simple as possible.

What you need to start a SP2010 Workflow for a list item or a document in JSOM, you need to load SP.WorkflowServices.js and you need to create the manager and get the service, then you can trigger a workflow using the workflow name, the list guid and the guid of the list item:

var ctx = SP.ClientContext.get_current();
var workflowServicesManager =
	SP.WorkflowServices.WorkflowServicesManager.newObject(ctx,
		ctx.get_web());
var service = workflowServicesManager.getWorkflowInteropService();
service.startWorkflow(workflowName, null,
	listGuid, plainItem.guid, initiationParams);

Here is the code to trigger a workflow for multiple items:

//fire the workflows
function fire2010WorkflowForListItems(ctx, listGuid, plainItems) {
	var workflowServicesManager =
		SP.WorkflowServices.WorkflowServicesManager.newObject(ctx,
			ctx.get_web());
	var service = workflowServicesManager.getWorkflowInteropService();
	for(var i = 0; i &lt; plainItems.length; i++) {
		var plainItem = plainItems[i];
		console.log('scheduling workflow for id: ', plainItem.id);
		service.startWorkflow(options.workflowName, null,
			listGuid, plainItem.guid, options.initiationParams);
	}
	console.log('now executing...');
	ctx.executeQueryAsync(function() {
		console.info('yes, workflows completed for '
			+ items.length + ' items');
	}, function() {
		console.error('it didnt go well');
	});
}

 

The code above is inspired from this gist and sharepoint stackexchange. It is a simplified version that only works for list item workflows and SharePoint 2010 workflows.
Here is an example how you can get multiple items and batch start a workflow:

//just a couple of variables
var options = {
	workflowName: 'Behörigheter',
	listName: 'Documents',
	initiationParams: {}
};
//load list items
function startWorfklows() {
	//Start 2010 Workflow for a List Item
	var ctx = SP.ClientContext.get_current();
	var web = ctx.get_web();
	var lists = web.get_lists();
	var list = lists.getByTitle(options.listName);
	ctx.load(list);
	var items = list.getItems(new SP.CamlQuery());
	ctx.load(items);
	ctx.executeQueryAsync(function() {
		var listGuid = list.get_id() + '';
		var en = items.getEnumerator();
		var plainItems = [];
		while (en.moveNext()) {
			var it = en.get_current();
			//do not take checked out files, it won't work
			if (!it.get_item('CheckoutUser')) {
				plainItems.push({id: it.get_id(), guid: it.get_item('GUID') + '' });
			}
		}
		fire2010WorkflowForListItems(ctx, listGuid, plainItems);
	}, function() {
		alert('boom');
	});
}

//Load Worfklow Js dependency
var wfScript = 'SP.WorkflowServices.js'
SP.SOD.registerSod(wfScript,
	_spPageContextInfo.webAbsoluteUrl + '/_layouts/15/SP.WorkflowServices.js');
SP.SOD.executeFunc(wfScript, '', startWorfklows);

Why I needed it

I created a simple workflow that is triggered on Item Added and Item Updated. Unfortunately there are already thousands of items in the document library. To trigger them manually is nothing good. But a simple javascript solution did exactly what I wanted.

Create and download a file in javascript

Phew, I spent a lot of time to get this to work:

  • Create a text based file in javascript – a simple csv or txt
  • Download a file in Chrome and Internet Explorer
  • Make Excel understand Unicode characters (å ä ö and many more) in csv directly.

I found many solutions on the Internet that I used to find out a solution that works for me

A deep diving jsfiddle about unicode encodings, bom, line endings: http://jsfiddle.net/kimiliini/HM4rW (unfortunately, does not work in IE). There I learned one important thing: we need a BOM in order to make Excel understand that it is not just ASCII. The BOM (byte order mark) for utf-8 is %ef%bb%bf for utf-8. Without this bom you’ll see the right characters in a text editor (except Notepad of course), but if you open the csv file directly in Excel, you’ll see wrong letters.
Other good resources are FileSaver.js: https://github.com/eligrey/FileSaver.js and download.js: http://danml.com/download.html and a discussion on that github repository issue: https://github.com/mholt/PapaParse/issues/175

This is my solution that is tested in Chrome and IE10:

function downloadContent(options) {
	if (!options || !options.content) {
		throw 'You have at least to provide content to download';
	}
	options.filename = options.filename || 'tolle.txt';
	options.type = options.type || 'text/plain;charset=utf-8';
	options.bom = options.bom || decodeURIComponent('%ef%bb%bf');

	if (window.navigator.msSaveBlob) {
		var blob = new Blob([options.bom + options.content],
                 {type: options.type });
		window.navigator.msSaveBlob(blob, options.filename);
	}
	else {
		var link = document.createElement('a');
		var content = options.bom + options.content;
		var uriScheme = ['data:', options.type, ','].join('');
		link.href = uriScheme + content;
		link.download = options.filename;
//FF requires the link in actual DOM
                document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	}
}

//test
var separator = ';';
downloadContent({
	type: 'text/csv;charset=utf-8',
	filename: 'tolle.csv',
	content: ['ASCII', separator,
		'Åbäcka sig', separator,
		'to się podoba: żźćąęłć',
		separator, 'Яшлӑхӑма туйаймарӑм'].join('')
});

Safari

So it works on the latest Chrome (tested with 50 on Windows, Mac and Linux), Firefox (tested with 46 on Windows), Internet Explorer (tested with 11 on Windows 7). Unfortunately in Safari on a Mac, the link is opened directly in the web browser. You have to press Cmd – S to trigger Save As manually.

Part of SharePoint Utilities

I submitted this code to sputils (SharePoint Utilities) on github.

Minimal Download Strategy. Simple

There are many correct ways (1234, 5…) of making scripts work with the Minimal Download Strategy Feature (MDS) in SharePoint 2013 and 2016. But to be honest – every time I need it, I get confused. So now it is time to find a simple solution for that.

Who is better at it than the developers of the SharePoint themselves? Look at the MDS code in the built-in Display Templates:

mds-001

Let’s keep it as simple as Item_Default.js, let’s take it as it is and create our own scripts. Here is a skeletton of and MDS-ready script:

function runMyCode() {
	var time = new Date().toISOString();
	console.log('runMyCode', time );
}
runMyCode();
if (typeof(RegisterModuleInit) == 'function') {
	var scriptUrl = '/Style Library/runMyCode.js';
  RegisterModuleInit(scriptUrl, runMyCode);
}

Which boils down to this in pseudocode:

  1. Execute your code
  2. Determine if MDS is enabled
  3. If MDS is enabled
  4.       Register your code for execution

That’s it. No more overcomplicating.

Related findings

External scripts (outside SharePoint Site Collection, from CDN) within ScriptBlock of a custom action (like AddJSLink in PnP)  work withou any MDS-adjustments. The ScriptBlock adds a script tag to the head of the html document, and it the js reference is added to every AjaxDelta load. I would need more time to find out why. The good news is: it is an argument for using more CDN solutions in SharePoint.

Old stuff

A while ago I wrote two blog posts about MDS. Now I realise they were overcomplicated and the solution required customizations of the master page and 3rd-party scripts.

  1. Make your javascript code work with MDS part 1
  2. Make your javascript code work with MDS part 2

 

 

Minimal Display Template

We want to use our own Display Templates on Non-publishing sites – our team sites. Without the Publishing Feature activated you have to create an own javascript file. Here is short and concise instructions how to install it: Display Templates on Non-publishing Sites.

As described on that blog, you can make copy of an existing Item_Default.js and adjust to your needs.

I also asked Elio Struyf and I got the same tip. I did create my starter template. Here I want to share this very minimal javascript based Display Template. The real Minimal Display Template is in the SPCSR github repository: Item_Minimal.js It has been improved by Elio Stuyf himself🙂

(function () {
  // Config contains variables that are defined in one place
  var config = {
    propertyMappings: { 'Path':null, 'Title':['Title'] }
  };
  var templateUrl;

  var register = function () {
      if ("undefined" !== typeof (Srch) && "undefined" !== typeof (Srch.U) && typeof (Srch.U.registerRenderTemplateByName) === "function") {
              Srch.U.registerRenderTemplateByName(templateUrl, render);
          }
    };
    render = function (ctx) {
      // Display template data
      var cachePreviousTemplateData = ctx.DisplayTemplateData;
        ctx.DisplayTemplateData = {
        'TemplateUrl': templateUrl,
        'TemplateType': 'Item',
        'TargetControlType': ['SearchResults', 'Content Web Parts'],
        'ManagedPropertyMapping': config.propertyMappings
        };
        var cachePreviousItemValuesFunction = ctx.ItemValues;
        ctx.ItemValues = function(slotOrPropName) {
                return Srch.ValueInfo.getCachedCtxItemValue(ctx, slotOrPropName);
        };

      // Retrieve managed property data
      var path = $getItemValue(ctx, 'Path');
      var title = $getItemValue(ctx, 'Title');

      // HTML markup for an item
      var htmlMarkup = String.format( '<div>' +
                        '<a href="{0}" title="{1}">{1}</a>' +
                                        '</div>', path, title);

        // Caching
        ctx.ItemValues = cachePreviousItemValuesFunction;
        ctx.DisplayTemplateData = cachePreviousTemplateData;

        // Return the HTML markup
        return htmlMarkup;
    };

  // Retrieve all the loaded scripts
  var allScripts = document.getElementsByTagName("script");
  // Get the last script file (this is the current DT file)
    var scriptUrl = allScripts[allScripts.length - 1].src;
    if (scriptUrl.indexOf('/_catalogs/') > 0) {
      // Remove the query string 
      if (scriptUrl.indexOf('?') > 0) {
        scriptUrl = scriptUrl.split("?")[0];
      }
      // Insert the site collection token
      templateUrl = '~sitecollection' + scriptUrl.substr(scriptUrl.indexOf('/_catalogs/'))
    // Register the template to load
    register();
      if (typeof (RegisterModuleInit) === "function" && typeof(Srch.U.replaceUrlTokens) === "function") {
          RegisterModuleInit(Srch.U.replaceUrlTokens(templateUrl), register);
      }
  }
})();

Benefits of js approach

If you choose to directly upload and mantain a javascript file you’ll get following benefits:

  • You can use the same display templates on Non-publishing sites and they work directly in SharePoint Foundation
  • You’ll get intellisense
  • You can run static code analysis agains your javascript code and you can create unit tests
  • It is more readable understandable from developer to developer
  • It is easier to follow best practices for javascript
  • It encourages reusing javascript components for Display Templates, CSR (JSLink) Templates.
  • You like TypeScript? Well, then it is best to skip the “grey” code in html comments.

Findings

  • You cannot use ‘use strict’ in your js file.

How to create a Display Template

Rename the Item_Minimal.js file to your name, update some properties.

Upload it to _catalogs/masterpage/Display Templates/Search/<your-folder>

Use ContentType: Display Template Code

displaytemplate-002

Template Level: Item and Managed Property Mappingsdisplaytemplate-003

Create a new Result Type. Every time you update the Display Template (item properties) you have to update the Result Type.

displaytemplate-001

Moving from Minimal to Better

Of course the minimal display template is not enough. There is a whole lot of things we can do, I prepared some tips (my own “best practices”):

  1. Learn the Search Display Template Syntax: Corey Roth – Useful js for Display Templates
  2. Follow Elio Struyf’s 10 tips for working with Display Templates (except the first one – javascript is better🙂 )
  3. Prefer JavaScript Display Templates if you are a developer and you want to  have a better control
  4. Never update the built-in Display Templates.
  5. Centralize reused parts of Display Templates – utilities, common parts, css. Use a CDN site for that.
  6. Check out the SPCSR github repo, there are many Display Templates that you can use or be inspired from.
  7. Create your own folder in _catalogs/masterpage/Display Template/Search to have all your Display Templates within a site collection.

 

SharePoint Utilities – a promising JavaScript Framework

My colleagues at Bool have developed a new JavaScript framework for SharePoint – sharepoint utilities. It started on our DevDay last year – a whole free day when we could learn new things, try out new techniques or build something that was not even requested from a customer. I was not working on sharepoint utilities, so I almost forgot it until…

I recently  re-discovered sharepoint utilities. It is on Github, it is MIT licensed and contributions are welcome. The core of sharepoint utilities (sputils) is a set of wrappers for Search, TermStore, REST that allow you be more productive as a developer.

What I find especially compelling with that it contains some other fundamental stuff that every SharePoint developer needs:

  • XHR, you only need to use sputils.rest.get or sputils.rest.post to make Ajax requests to SharePoint, no need for jQuery or sprequestexecutor.js
  • Promise, it contains a minimalist Promise framework – no need for jQuery.Deferred. All calls to SharePoint _api are wrapped in promises. So there is a better way of making calls to SharePoint.
  • DateTime, it contains some useful functions for working with dates and time.
  • Functional JavaScript. No need for underscore.js or lodash.js.

To me, XHR and Promises are two important parts that I need in every solution. So instead of linking jQuery and preparing reusable XHR functions for SharePoint, I’d recommend using sharepoint-utilities.

A tiny tool for User Custom Actions

hehyuaf

Everybody loves User Custom Actions in SharePoint. That’s the only recommended way of customizing SharePoint. You have heard about it. Unfortunately there is no convinient way of administering them. People have their console applications or powershell scripts to add, update and delete user custom actions. It works but it is hard to open up Visual Studio or PowerShell every time you will try out an idea on a test site.

To overcome this, I have created a tiny little tool, packaged as a bookmarklet for your browser. When you click on it, it will show your existing user custom actions and you can add new user custom actions.

It is an ongoing little project, available on github, contributions are welcome. What’s left is:

  • Implement Delete operation
  • Implement Update operation
  • Improve the UI.

Here is how it looks today:

usercustomaction-001

To use this tool, add a new bookmark in your browser and copy the content of bookmarklet.html as the url.

Resources on that topic:

Creating a bookmarklet for Exporting Web Parts

REST API for User Custom Actions (MSDN)

What it can be used for

It can be used on test sites to try out ideas. But do not use it in Production. On ther other hand, parts of this script can be used in other scenarios, like adding new functionality by site owners directly from the browser, where data is predefined.

How to add a JavaScript code

You can use this boilerplate code to add a UserCustomAction, just put it into the textarea and click “Add new”:


var fileref=document.createElement("script");
fileref.setAttribute.src= "YOUR-SCRIPT";
document.getElementsByTagName("head")[0].appendChild(fileref);

Best practices for User Custom Actions

  • Add a ScriptBlock instead of ScriptSrc. In that way you can reference javascript and css files outside you site collection – ultimately from a CDN site.

Provisioning Google Maps JSLink with SPMeta2

kartta-000

Among PnP Samples there is a solution for using Google Maps. Great solution where where you can pick a point on a map and define a spacial area on the map. Unfortunately it is a sandbox solution. I rewrote it to a code based template with SPMeta2 Framework. Now it can be installed on any site very easily, without needing UserCode Service and a cumbersome process of uploading a wsp package and activating it. The code is very simple, you can see it on github.

kartta-001

Let’s take a look at it. It does not contain a single line of SharePoint Legacy XML. There are following SharePoint artefacts that are getting provisioned:

  1. Two site columns (Location Point and Location Area)
  2. A SharePoint List (Locations) with two additional fields mentioned above
  3. Google Maps code in and CSR in a jslink file
  4. Auxiliary pages for selecting points and areas on the map.

Field Definitions

In SPMeta2 everything is separated in meaningful definitions. First we define our fields. The preferred place in the VS solution is Definitions – IA – Fields.

kartta-002

List Definitions

Then we define our List – Locations. That is also a SPMeta2 Definition. List Definitions reside in Definitions – IA – Lists. We do not add fields in our list definition. The fields are added while “assembling” the model.

kartta-003

ListView Definitions

ListView Definitions are also in the Definitions – IA folder. We inherit from the OOB AllItems view:

kartta-004

Modules (a.k.a. Files)

Resource files like javascript, css, aspx, html and so on are Modules. They are in the “Modules – Implicit” folder. The internal structure is copied to the web folder. The upload of files is easy and is defined in the web model, see next section.

Web Model

Now it is time to pick the definitions and create a model. The most common model is a Web Model. The model is created programmatically and relies on “Add” methods: AddField, AddList and so on:

kartta-005

Provisioning

The actual provisioning is the most fun, it is easy and straight forward, it takes models and deploys it to a SharePoint site. You can easily switch between SSOM and CSOM.

kartta-006

Distribution

Another bonus of SPMeta2 Provisioning Framework is the ability to serialize and deserialize models to XML or JSON. In our project we define SharePoint Applications as SPMeta2 models serialized in XML and make them available for installation on any SharePoint Site.  A SharePoint Application is a meaningful collection of SharePoint artefacts that becomes an entity and solves a business need.

Summary

This Maps solution is a simple solution, but it is a very powerful one, originally created by the PnP team. If we just redesign the Provisioning Part, it becomes awesome. SPMeta2 provides a solid, well defined, easy-to-understand framework for define code-first models for SharePoint Applications.

Setting up Raspberry Pi2 for a Dashboard Monitor

I have set up Raspberry Pi as a Dashboard Monitor a couple of times. Here I want to summarize my steps. In fact, it is nothing special, a raspberry pi that is used as a browser showing a web based dashboard in full screen, but there are some important configuration steps needed to make it as good as possible.

Install Raspbian

Raspbian is the best operating system for Raspberry Pi. Just stick with that.

Expand file storage

When you boot up Raspberry Pi, the first thing you should do is to expand the file storage, otherwise it is hard to install anything. To do so, run raspi-config from command line and restart your raspberry pi after that.

dashboard-rasp-002

Rename your raspberry

You are advised to change the password. In my case I usually just want to keep the default password: “raspberry”. What I want is to change the hostname from raspberrypi to some unique hostname (in my example it will be “kallerasp”), so that I can access it from my network without running risk for name conflicts. To rename your raspberry, update the /etc/hostname file:

sudo vim /etc/hostname

After that restart your computer.

Install iceweasel

Iceweasel is a Firefox fork, which works just fine on the raspberry pi. Update your raspberry pi and install it:

sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install -y iceweasel

Make sure the screen is not getting blank

To use your raspberry pi as a dashboard monitor we need to prevent the screen from getting blank (dark).

cd /etc/lightdm
sudo cp lightdm.conf lightdm.conf.bak
sudo vim lightdm.conf

Update it so you have the following:

[SetDefaults]
xserver-command=X -s 0 -dpms

dashboard-rasp-001

Start dashboard page on startup

To automatically start iceweasel on startup, we need to configure autostart. To do so, run this from terminal:

cd ~/.config
mkdir autostart
cd autostart
vim .desktop

In the .desktop file write following:

[Desktop Entry]
Type=Application
Exec=iceweasel

Previously I had chromium-browser –kiosk http://someurl, but Chromiums is no longer available, and iceweasel does not have –kiosk parameter. On the other hand, you have to activate Full Screen the first time, then after OS restart iceweasel automatically will activate Full Screen and your dashboard page from the previous session.

Discovering SharePoint

And having fun doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

.:paul.tavares:.

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis