Search

Binary Jam

Simon's blog, SharePoint, Arduino type things.

Category

Uncategorized

DisplayTemplate:Hide edit fields based on choice field

This is a simple displaytemplate (JSLINK) that will hide fields based on a value in a choice.  I use it for pseudo content-types, having the advantage of being able to switch.

It’s not MDS compliant.

In this example “ItemType” is the field name of the Choice field and could be “Standard” or “PopUp”

The array of hideme items are the fields that are hidden when that choice field is selected.

The HiddenItems starts empty and contains the hidden elements to be unhidden on a change of type.

It relies on jQuery being in the masterpage or somewhere on the page.

You store this as a JS file in a doclib or SPfolder or siteassets etc,  edit the form page and point the JSLINK setting to that file.  remember to use the tokens ~site or ~sitecollection as JSlink doesnt like fixed urls.

$(function () {
"use strict";


    var hiddenItems = [];
    var hideMeItems = {
        Standard: ["[id^=PopUpBodyText]","[id^=ReadMoreUrl]","[id^=ReadMoreUrlTarget]"],
        PopUp: ["[id^=Teaser]","[id^=TargetUrl]","[id^=TargetUrlTarget]"]
    };


    $('[id^="ItemType"]').change(hideItems);
    hideItems();

    function hideItems() {
        var selected = ($('[id^="ItemType"]').val());

        $.each(hiddenItems, function () {
            this.show();
        });
        hiddenItems.length = 0;

        $.each(hideMeItems[selected], function () {
            var tr = $(this).closest('tr');
            tr.hide();
            hiddenItems.push(tr);
        });
    }
});

VS Code, Git, Gulp and SharePoint

UPDATE:Since writing this VSCode 1.0 was released which told me I was using the old Git package.  So I updated Code and Git. The new Git has a better windows credential manager and is built in now, you may find the git config win.cred stuff in here is not needed, so experiment and don’t do that bit unless you need to.  Also this was on Windows not mac or Linux, so some things might be different.

UPDATE2:I created a framework for Sandbox solutions based on gulp and git and browsersync and yeoman and npm and bower etc.  search for generator-sb-framework.   It was done 2 weeks before they announced SPfx framework, I was thinking along the same lines, but without access to 365 back end code 🙂   Mine will work on SP2010 and 20!£ and 365 though.  It’s a work in progress anyone wants to help let me know. Now on with the Article.

 

 

I get asked to “knock stuff up” quite often, its a single page that has to grab data and display it in a funky way and NOT look like SharePoint whilst utilising SharePoint.

I could be deploying it to MOSS or 2010 or 2013, any of the three so I tend to write with SPServices, and I find that REST isnt done.

I tend to write these things as single htm pages hosted in a doc lib, so this lends itself to angular and knockout with bootstrap etc.

Of course when you write stuff like this, what your doing is essentially creating a mini website connecting to services that exist outside of your website, except thans to virtual folder like _layouts they are actually part of your site, you just dont have to worry about CORS.

In the past I would just create the doc lib, open the folder (webDav) and just edit away.

This isn’t good enough though, I want my stuff to be under source code control, natively and you just can’t working like this.

Today I took the time to investigate using VSCode, git and gulp to acheive what I wanted.

To do this stuff you will need, VSCode, Git for Windows, GitHub for windows is handy too it has a better Gui and Node.js installed on your machine. You need NPM in node, but it comes with node now so no need for an extra installation. You will also need a Git repository, I’m using VS online, which has its own issues.  Go ahead and install all that lot.

There are some things called bower, and grunt and yeoman and all that.  Not touching that lot. Not yet anyways, so don’t expect it here.

To start with, create a new visual studio online project, name it, pick a methodology and pick GIT as the Version control.

Navigate to your project, because next I’m making it easier to connect by creating a credential.

Explore your project and you get a page a bit like this

There are various bits on this page, but first let’s click the Generate Git Credentials.

Then click create a personal access token,  this applies across all git projects so if you have one already then you don’t have to do this again, but you need to store that user name password combo securely in something like lastpass or dashlane

These are handy cos you can revoke them and they have a lifespan.

Go back to your default code page cos now we want to clone the Git repository.  This is easier in Git Bash , this works like linux so no “DIR” commands here

 

Firstly, if your in a company chances are you have a proxy server.  You need to configure git with  proxy server settings.  Because git doesn’t have a bypass capability I set my proxy server up as fiddler and then I can control what’s going on with regards to bypass lists.

So as I work in d:dev I changed Dir and then set my proxies

Screenshot_6

This will set you global git config to point at local fiddler address (IF YOU CONFIGURED FIDDLER LIKE THAT).  Feel free to set it to whatever proxy you want.

 

There is a slight problem when using VSCode and git with a remote host, in that when you issue a remote command it needs credentials but has no way of showing them so it just hangs till you kill it.

I found that you can save you creds locally, I do that just before cloning, see next lot of commands.

Next to do is to clone the git repository you just created in Visual Studio online.  This will create the local version of git. You check in there and then sync to the master when you want. Then branch and pull and push and whatever else git does, which I’m still getting my head around.

Copy the Clone command from visual studios code page,

 

Screenshot_7

don’t use mine, its easy to guess what mine would be called, you won’t get access and if you do MS and me will be having words.

but do it in git bash and enter your creds when prompted.  You can use any user name you like, but use the specials credentials you created earlier as the password,  this works, other ways I’ve tried don’t.

Your creds are now cached in the windows credential manager thing, look in control panel to remove it.

Next lets open the Folder in VSCode, File->open folder and select you VSCodeDemo folder, inside of which is a .git folder.

Once open create a test.htm file and put some words in it, anything, this is a test. Save it.

Switch to the Git tab and check in locally those changes, give it a message of “Initial test” and click the Tick at the top

Screenshot_8

Now to sync up to the web, look at the status bar at the bottom and click the cloud with an up arrow icon, which means publish or the recycle icon, you will see one of these.

Screenshot_9

When you return to visual studio on line your code tab now shows the branches you have published, synced, whatever that means.

That’s the git integration done.  Have a play add files rollback etc.  Next up configure VScode and some handy plugins.

When running VSCode in an enterprise and you want to use plugins you have to configure it to use a proxy server.

File>Preferences->User Settings

This will open two files for edit, default settings for reference (dont edit) and the settings.json

Here’s mine

{
	"editor.fontSize": 12,
	"editor.tabSize": "4",
        "http.proxyStrictSSL": false,
        "http.proxy": "http://127.0.0.1:8080",
        "https.proxy": "http://127.0.0.1:8080"
}

 

Again Im using fidder as my proxy server, because I have more control.

Next hit F1 and lets install some extensions.  F1 and type “ext install”

it will show you available extensions, heres what I’ve installed.

Screenshot_10

You may want to control settings for code and your plugins locally per project so open the workspaces prefs.  File->Preferences->Workspace settings.  Again this opens a settings.json file here’s mine

{
    "minify.minifyExistingOnSave": true,
    
        "indent_size": 4,
        "indent_char": " ",
        "css": {
            "indent_size": 2
        },
    "beautify.onSave": false
}

 

This sets my auto minify on to create those min.js files for me automatically. You have to force create one first by hitting F1 and type minify.  This creates the min file and from that point on its automatic. Play with this cos if you change its settings you can minify a whole directory of js files.

Next on to task runner (gulp in vs code).

Make sure you installed node.js and npm works and if thats got proxy config to do go do it (I’ll let you figure it out).

In fact go follow this guide

https://cmatskas.com/setting-up-a-gulp-task-with-visual-studio-code/

OK so that made no sense, but I guess you at least installed gulp globally.

So back to our project.  Open a Node.JS command shell and change directory to our project, now run the command

npm init

Enter the details at the prompts, you can next thru most of them, change the name to all lower case those it complains if you dont.  Im sure these have proper uses but for now, meh.

Now back in VSCode hit F1 and type “Configure Task Runner”

it opens the tasks.json file.  Rip all that out and replace it with this  (we will create the actual gulp task in a minute)

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": [
        
        {
            "taskName":"deploy",
            "isBuildCommand": true
        }
    ]
}

Save that.  Our task to create is a robocopy so on build it will copy the contents of our folders to another folder.

switch back to node.js and install local version of gulp and robocopy (cos globals wont work)

npm install gulp
npm install robocopy

In the root of our project create a file  “gulpfile.js”

var gulp = require('gulp'),
 fs = require("fs");
 
 var robocopy = require('robocopy');

gulp.task('deploy',  function() {
    return robocopy({
        source: 'Web',
        destination: 'd:\tmp\web',
        files: ['*.*'],
        copy: {
            mirror: false
        },
        file: {
            excludeFiles: ['packages.config'],
             excludeDirs: ['Forms'],
        },
        retry: {
            count: 2,
            wait: 3
        }
    });
});

This creates a gulp task called deploy (the one we matched in the tasks.json) that uses robocopy to copy everything under the folder Web to another folder on this machine d:tmpweb.  In VS code Hit Ctrl-Shift-B and that builds and copies.

So in using this mechanism we have to assume some stuff.  Firstly that we build our deployable content under a folder under the root called web.  We do this cos of all the bloody rubbish node and git pish and paff and every thing else needs.

Because we have all this stupid files in our project though, some of them are not compatible with GIT.  So we have to exclude them from git.  This is easy.

Create a file in the root of the project called  .gitignore

node_modules

Add that line to it to exclude the node_modules, as that’s all that’s incompatible really.

And lastly where the SharePoint ?  You promised me Sharepoint, Tocker!,

Well what we want is to deploy this Web folder into a Document Library in SharePoint (assuming that we are allowed to have .js.htlm.htm extensions files, if not well save everything as a .aspx with no aspx code in it).

Imaging that we have our site collection and doc library, its full path is this

http://binaryjam.sharepoint.com/sites/mysite/myDocLib

Well we just have to copy to the webDav folder equivalent.

This is a slight change to the gulpfile.js robocopy task.

Edit that gulpfile.js file and change destination from d:\tmp\web

to

 destination: '\\binaryjam.sharepoint.com\davwwwroot\sites\mysite\myDocLib',

That davwwwroot is the magic door.

That’s it.  Build SPA’s that live in doc libs with Git source control and minifying and all thatlovely stuff.

Of course this tasker stuff lends itself to all sorts of tasks, like less/sass compilation, typescript compilation for angular 2 (or just typescript).  Have fun.

 

 

 

 

 

MDS Compliant Disp Template example

This is just a reminder for me really, take a look if you like, but its not done, based on Martin Hatch’s colour field example with Wictor’s mds detection.

https://github.com/binaryjam/DisplayTemplateExample

 

/// <reference path="DefinitelyTyped/microsoft-ajax/microsoft.ajax.d.ts" />
/// <reference path="DefinitelyTyped/sharepoint/sharepoint.d.ts" />
/// <reference path="DefinitelyTyped/DisplayTemplateFieldColour.d.ts" />
"use strict";
//This is a work in progress, trying to come up with a kind of best practice, of best practices
//because the office pnp examples do not do things how other JS peeps might.


//Im not convinced about this either, this should be SOD'ed  / Leaving in for future reference
//(jQuery || document.write('//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js'));

//Creates the namespace and registers it so MDS knows its there, 
Type.registerNamespace('BinaryJam.JSLink');

(function(ns) {
	
	ns.DisplayTemplateFieldColour = function () {
		
		//private members
		var overrides = {};
	  	overrides.Templates = {};
	  
	   	overrides.Templates.Fields = {
	       //Colour is the Name of our field
	       'Colour': {
	          'View': colour_FieldItemRender,
	          'DisplayForm': colour_FieldItemRender
	        }
	    };

		//Create CSS classes
		var style = document.createElement('style');
		style.type = 'text/css';
		style.innerHTML = '.binaryJam_dt_FieldColour { display:inline-block; margin 3px;width:20px;height:20px;border:1px solid black; }';
		document.getElementsByTagName('head')[0].appendChild(style);
		
		function colour_FieldItemRender(ctx) {
			if (ctx !== null && ctx.CurrentItem !== null) {
				
				var divStyle="style='background-color:" + ctx.CurrentItem['Colour'] + "'";
				var html = "
" + ctx.CurrentItem['Colour'] ; return html; } }; function registerTemplateOverrides() { SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrides); }; function mdsRegisterTemplateOverrides() { var thisUrl = _spPageContextInfo.siteServerRelativeUrl + "js/jslink/test1.js"; RegisterModuleInit(thisUrl, registerTemplateOverrides); }; //Public interface this.RegisterTemplateOverrides = registerTemplateOverrides; this.MdsRegisterTemplateOverrides = mdsRegisterTemplateOverrides; }; })(BinaryJam.JSLink); //This is the "official" way to check MDS //https://msdn.microsoft.com/en-us/library/office/dn913116.aspx if ("undefined" != typeof g_MinimalDownload && g_MinimalDownload && (window.location.pathname.toLowerCase()).endsWith("/_layouts/15/start.aspx") && "undefined" != typeof asyncDeltaManager) { BinaryJam.JSLink.DisplayTemplateFieldColour.MdsRegisterTemplateOverrides(); } else { BinaryJam.JSLink.DisplayTemplateFieldColour.RegisterTemplateOverrides(); };

 

Adding a Post Feature Activation notification

Recently I’ve been doing some 2010 work on a site which needed a bunch of javascript and some CSS files. Now most of these were deployed to the style library but as you know you often have to check them in etc once deployed.

Rather than figure that out I thought I’d just give a message to the user on activation of the feature

Continue reading “Adding a Post Feature Activation notification”

Creating TFS task Items from Powershell – Using a list of files

So you’ve been given a project to work on.  Namely convert this project from this technology to that technology and your in luck because you have TFS.

The pain in the backside bit is now I’ve you have got to enter all the tasks into TFS which in itself is going to take ages.

Enter the wonderful world of Powershell !  This is the kind of repetitive task that PowerShell is good at it can loop thru things and use the .NET object model, Easy!

So here is a code snippet that rips thru aspx pages and creates the TFS entries.

Continue reading “Creating TFS task Items from Powershell – Using a list of files”

Songsmith

In case you have not heard, Microsoft Research have come up with some song writing software.  It’s called Songsmith.

The idea behind it is that you make up a tune in your head then sing it into songsmith.  First you pick a music style and then a tempo and then sing away.  Once recorded  the software will analyse your song and the notes you sang,( hopefully you sang them in tune I don’t think it cleverly pitch shifts your voice, but I may be wrong ) and then it will create a musical accompaniment in the style you selected.

Now I know what your thinking but the MS web site states

"The samples you hear in Songsmith aren’t toy sounds… they’re a high-powered general MIDI set from Garritan, one of the biggest names in the industry"

With resources like this how can it fail ?

Now it’s not aimed at pros but to give anyone a chance to write a song, well my son is seven and is not a musician, yet, he hasn’t displayed any interest in that area, until recently, but even he hears that the stuff this thing produces is absolute pap.  It can’t even compose a good jingle, take a listen to the MS videos and cringe.

Where the genius of Songsmith lies, and this was totally unintentional I’m sure, was the sheer comedy value provided when you take songs you know and feed the vocals into Songsmith and have it re-write the original into the dreadful "early eighties, cheap casiotone" sounding affair it produces.

Youtube is starting to accumulate examples of Songsmith Massacres.  Radio heads Creep, britney’s Toxic, battery by metallica and loads more.  

So I wouldn’t bother getting Songsmith but go take a look on youtube and laugh your pants off on the utter tosh it produces.

 

Technorati Tags:

Being Human

Last night with tons of advertising and announcements (I don’t think), the first series of Being Human snuck its way onto the schedules.

Well done BBC for finally getting there with this series.

I’d love to tell you how good or bad it was but due to the marvelous media campaign I missed it, I stumbled across it half way through the episode where I managed to see all the characters and the new actors playing two of them. 

Like I say I missed it so I wonder how the new actors will fit, if at all, the characters we were introduced to.  I do have doubts about the ghost, far to attractive and very removed from the pilot character, who I absolutely loved.  Is this a real improvement to help the story or just eye candy to keep part of the male audience who struggle with plots engaged.  I don’t doubt the young ladies ability she seemed very good but its not the funny, kooky plain northern lass obsessed with making tea entrenched in routine to cope with her death and being tied to the house.

Anyone who did watch, what do you think ? Does it measure up to the pilot ?

Anyway, I can be thankful for iPlayer and will watch all of it tonight.

Technorati Tags:

Blue Monday

Other than a chest infection, which was quite bad and making me very sick monday morning, enough to take a day sick and the last resort book a doctors appointment, I thought it’s not that bad, after all I have a job at the moment, I don’t spend what I don’t have (usually) so I’m not in huge credit card debt, I get paid early in the month too.  So not much to worry about at all.

Till I got out of bed.  I phoned work to let them know I was sick and also off to the quacks.  I booked the appointment at the doctors, and got a good slot 9.50am unheard of.  Apart from the retching cough things were looking up the prospect of being cured and getting back to normal.

Then the phone rings.  Childminder, can’t have little’un today our ceiling is leaking.  So that messes up the wife’s morning.  Still I can watch him while off sick, all I have to do is lie on the floor to be at his level and play with his toys with him shouldn’t be too taxing, at least I’m in the warm and getting better.

Get in car to go to doctors, turn key, "whheeeeeeeeeee", "Wheeeeeeee". Damn. Starter motor.

Come back from docs, biotics to cure, maybe, its amoxicillin which hardly ever works for me, and as it should start working feel free to go back to work, I like my job so not too bad, but what about the car ? I wonder. 

Get garage to come get car, should be about 190 quid mate.  I’ll phone you later.

One exhausting day saying, get down, don’t touch, chest feels better though, ring ring.

"Got some bad news mate", "You’re fly wheel is damaged and sent bits flying into starter motor, we can replace it but won’t warranty it and that’s 250 quid or we do it properly new clutch, new flywheel and new motor £960, but your rear sub frame bushes although need doing we can leave them for a bit longer" , "Ok then", "Oh and it won’t be done till wednesday".

So blue Monday got its revenge on me, big bill to come, no savings to pay it, credit card gonna take a hit. 

Tues. So I’m here at work after an hours drive in freezing weather with icy roads on my motorbike. My legs are still cold.  But the cough is getting better at least and I got some interesting Sharepoint work to do, and Ashleigh has figured out whats wrong with my media pc, so at least I can cancel "Sky" to help pay for the damn car.  Gotta look on the bright side I suppose.

Focus on that Bug – TFS

image One problem I find since I started using TFS is I don’t focus on one bug, I often solve several at a time sometimes interconnected sometimes not, often down to which one I feel like fixing as that, for me, yields better results.  However its not always the best way, especially when working with others.  Most of the time I don’t play with others so it works for me.

But I have to train myself to use this thing (TFS) better and part of that is pick a bug/task and stick to it.

So I came up with the simplest of things to help with this.  Visual Studio windows.

Simply pick the bug your working on select the code and create a new horizontal tab group and drag it to the top till you only see the tile of the task in yellow. 

Simple but effective, well not that effective cos here I am blogging it instead of coding.

Create a free website or blog at WordPress.com.

Up ↑