Search

Binary Jam

Simon's blog, SharePoint, Arduino type things.

Category

Sharepoint

Adventures in BrowserSync

I’m real new to browsersync and node development. So this has been a pretty steep learning curve, but I thought I’d document something I had to figure out as the documentation and guides on the web are hard to find or just missing.

For those who don’t know and are new to this javascript lark, browsersync is tool that runs under node to create a mini web server, but also it injects javascript into your pages and communicates to the server when the file watcher sees a change to a file.

The effect of this is you can configure it, then run this thing to point at the files in your directory that you are editing, it will fire up a browser and as soon as you save a file it will reload the page.  A real cool feature is called hot reloading, in certain circumstances and configuration it can detect you have changed say an image or css file and it will only change that item in the page, it uses JS to mangle it to the new version and won’t do a full page reload.

I’m using a modified version of browsersync called lite-server, by john papa, just because it was the one I came across first. I’ll be honest I’m not sure what lite-server gives me over browsersync native, it’s just where I started.  That said, you will spend a lot of time reading the browsersync docs not the lite-server page.

The main point of me writing this article was that as well as serving pages and auto reload, browsersync gives me the ability to handle API calls and proxy them to local files (possible another server but I’m not there yet).

In the framework I’m writing, to mimic the new SP framework (early days though) experience but on legacy stuff to deliver a sandbox WSP, the example code makes a call using SPServices library (this could be REST) that call as you may know has the path _vti_bin in it.  So my browsersync config has code in it (the config is javascript) that can intercept this and deliver my content instead.

Below is the bs-config.js file I wrote to achieve this.

The module.exports is the standard bit that configures bs with what files to the watch and how to configure the mini server

The special part is the middleware setting. I have set it so that the 2nd param points to my handleApi function call.  The reason I set the 2nd param (thats the “1:” bit) is that if you clear the 1st parameter then it no longer logs to the console the items its serving, which is handy.

As you can see the handleApiCall function is real simple, it detects the “_vti_bin” in the path and reads a file from a specific place and puts it out in the response stream along with the correct headers for xml.

This could be improved, lots, it could read the request object and parse it to determine what file to send back.

Of course someone has probably already done something like this, but I needed to do something quickly and there is enough to learn.

Saything that I will be looking into proxy-middleware a module for express/browsersync that will likely proxy to a real server not just my local files.

Alternatively https://www.npmjs.com/package/apimock-middleware.

You learn there are so many OS projects out there in npm land so its hard to find the right things.

// jshint node:true
function handleApiCall(req, res, next) {
    
    if (req.url.indexOf('_vti_bin') !== -1) {
        var fs = require("fs");
        fs.readFile("./WebComponents/.container/.mockapi/1.xml",function (err, data) {
            if (err) throw err;
            res.setHeader('Content-Type', 'text/xml');
            res.end(data.toString());
        });
     
    }
    else{
        next();
    }
}

module.exports = {
    'port': 8000,
    'files': [
        './WebComponents/src/**/*.*'
    ],
    'server': {
        'baseDir': './WebComponents/src',
        'middleware': {            2:handleApiCall        }
    }
};

Advertisements

SharePoint 2013 App – AngularJs, BootStrap and ngGrid example

I’ve created a SP2013 App including all the code and published it on Codeplex so anyone can take a look and steal the code get ideas.

It has an example of two data fetch techniques (see my earlier blog post for the third external data using the proxy)

using $http to get REST data or $.ajax to get legacy WebService Data.  With the appropriate angular code to handle either, no antipatterns here.

Perhaps I should have used SPServices instead of $.ajax it would have made it easier and I would not have blatantly nicked Marcs getZrows function (thanks Marc 😉  )

https://spappnggrid.codeplex.com/

Capture

Last Update:14/10/2014
Organised into folders and separate files for controllers and services. Changed Service to Factory.
(Service code left in project for example purposes)

 

 

Detecting the Language in a DVWP

I have been hunting all morning on how to do this.  I can do it in a CQWP with parameterbinding set correctly but no-one, no-one has put any example code on how to do this in a DVWP.  I’ve read many an article talking about ddwrt functions lists of variables which are not accessible even if you include the xslt namespace.

Eventually I figured something out.  It’s not pretty but then again, what SharePoint is doing isn’t exactly too far removed.

In order for SharePoint to know what browser is being used and what language the browser has to send this information via http headers so we have all the info we need.

 

In you DVWP start by adding a Parameter (I called mine Param1)

image

Set it to a Server Variable

Type in HTTP_ACCEPT_LANGUAGE

and give a a default value, mine says none, but set it to your default language e.g. “en-GB”

That will get you the language codes you need into your XSLT.

 

However those strings can be quite large, e.g.

    en-GB,de-DE, {lots of other stuff}

The bit your interested in, well that’s up to you in my case I care about language, and being British there are no such things as regions just ours and everyone else that’s doing it wrong.

So I have in my XSLT


This grabs the “en” from the string.  If I switch to German then I get “de”

So now I have my language code I can do conditional XSLT based on a language code.

 

This has allowed me to create multi lingual Content web parts in WSS 3. Which is handy.

It’s simple, if someone can point me at a better way please do, I haven’t tested this thoroughly with lots of different browsers and languages so I may need to get a bit cleverer that this simple example.  But for the many of you searching for how to do it, this might be an option for you.

 

Technorati Tags:

List of JS Libraries I’m using / looking into

This is more of a note to myself so that I can remember the JavaScript libraries I’m interested in and what they do and maybe a related article.  These are mainly in dealing with SharePoint but could be anything really.  Not everything is compatible with everything else remember 🙂

 

KnockoutJs – Data binding library, works with jQuery, great for a true single page app, IE no routing just data binding.  Yes I know SPA’s pages are called views.

AngularJS – Proper SPA framework, there’s Durandal but I’?m not going there even though I love knockout.

BreezeJs

    – Linq Like queries, does need server side integration, not for local objects

Bootstrap – For that nice CSS layout grids and things.

Bootstrap UI – Directives for Angular using bootstrap

Angular Maps – Google maps directives for angular, something I’ve used already.

 

LinqJs – Linq for JavaScript, will work on JS objects, doesn’t do fetch for you

Js Loaders – http://requirejs.org/  and  http://labjs.com/

jQuery – Well how could I not mention it.

jQuery form validators

Sliders – http://slippry.com/ , http://bxslider.com/, http://workshop.rs/projects/coin-slider/

fontawesome – No idea, well something to do with a shed load of CSS icons, vectors (no IE7)

Charts – jqPlot, http://www.flotcharts.org/, hicharts

Spinner – svg/vml Spinner, easier than a gif ?

 

Stuff to investigate

 

Not a library but a list of handy SP2013 dev tools

Zimmergrens SP2013 Tools Page

SharePoint Designer 2013 – Working round some problems

UPDATE: Really Big Hint, if you are in SPDesigner messing with forms then you’re likely doing it wrong. Seriously, Im not kidding, DON’T crack open SPD and mess with DVWP’s look at Display Templates / JS Link every single time. If you have too then this is still a handy article.

Designer is Buggy. So here are some hints when doing DVWP or DFWP including filtering lookups, where to put the cursor + others.

Continue reading “SharePoint Designer 2013 – Working round some problems”

How to get the SiteCollection Url in XSLT

I found this way to get the root site collection url into a DVWP

There are Global parameters available but you have to mess about with the bindings to use them.

 

So for this one you need

<ParameterBinding Name="RootSiteUrl" Location="WPProperty[RootSiteUrl]"/>

 

Then at the top of the XSL (make it global to all templates)

<xsl:param name="RootSiteUrl"></xsl:param>

 

Then in your XSL you can use it

<xsl:value-of select="$RootSiteUrl" />

 

That’s it. Well it worked for me, but SP2013 and designers is so damn flakey it might not work for you, this was done on a WPPage not a wiki page that causes all manner of hell using webpatrs in those things.

SharePoint Apps and AngularJS – SP.WebProxy Invocation using promises

Recently I’ve been trying to create a SharePoint 2013 app using AngularJS and angularui-bootstrap.

It’s been going well thanks to Jeremy Thake’s (@jthake) original demo.

But I wanted more! More than just access to the local site, I wanted access to the web, but I wanted to do it in the right AngularJs way, using the service so later when I figure out how to do DI testing I can, using promises too, which of course SharePoint doesn’t return in a way we can use in AngularJS.

So this code snippet (not complete app) will give you a clue on a way of doing it, there may be a better way to do this in AngularJS Im no expert, I see references to module.Factory calls in other examples, but I’m sticking to Jeremy’s starter code for now.

This example uses UK police data, details of the license are here http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2

'use strict';
var myApp = angular.module("myApp", []);

function myAppCtrl($scope, $myDataService) {
	$scope.getPoliceClick = function () {

		//Whoops, edited this line as it was wrong from original post
		var promise = $myDataService.getPolice($scope);
		promise.then(
			//Success callback, check the status = 200 and go mad
			function (response) {
				//...
			},
			//Epic Fail callback
			function (response) {
				//..
			}
		);
	};
};

//this method signature is same as Jeremy"s thats why the $http is there, I use it for lists as well
//just not in this code sample
myApp.service("$myDataService) ", function ($q, $http) {
	this.getPolice = function ($scope) {
		var deferred = $q.defer();
		var context = SP.ClientContext.get_current();
		var request = new SP.WebRequestInfo();
		request.set_url("http://data.police.uk/api/bedfordshire/57");
			request.set_method("GET");
		// We need the response formatted as JSON.
		request.set_headers({
			"Accept": "application/json;odata=verbose"
		});
		var response = SP.WebProxy.invoke(context, request);
		context.executeQueryAsync(
			function () {
				//Notice the scope apply, because the async call is made from outside of angular
				//just resolving will not work
				$scope.$apply(deferred.resolve(response));
			},
			function () {
				$scope.$apply(deferred.reject(response));
			}
		);
		return deferred.promise;
	};
});

SharePoint 2010/2013 Open a Form on the browse tab

This is something I regularly search for and more and more often I’m finding people posting code versions when all I really want is the URL parameter to force it. So luckily I stumbled across SharePoint Den page that posts the following

http://site/List1/Forms/DispForm.aspx/&InitialTabID=Ribbon.Read

 

So cheers chap, the more places this version is shown I hope helps someone else find the way correct for them

Technorati Tags:

SharePoint 2010/13 Getting the Default Disp Page in JSOM

Being pretty new to JSOM, thought I might write this down so I don?t forget again.

JSOM is just quite a bit different to REST or SPServices or just ferreting around the old server API, so it’s going to take some time.  Give me REST any day, but today I find myself altering some one else’s code.

I needed to find the default display page Url

Well it’s pretty simple, but web examples are gathering all list information the code I had was getting a specific list, not sure that they are still not getting all lists, but hey.

Adding the paramter “Include(DefaultDisplayFormUrl)” into the getByTitle function, instructs CSM that you want this bit of info.

 

   

   <script>


 targetList = clientContext.get_web().get_lists().getByTitle("Glossary", "Include(DefaultDisplayFormUrl)");  


</script> 

 

But you can’t access it immediately.

No you have to wait until after the executeQueryAsync only then can you call the function on the targetList variable, so watch those scopes,

   <script>

 
  targetList = clientContext.get_web().get_lists().getByTitle("Glossary", "Include(DefaultDisplayFormUrl)");  
 
  
  clientContext.executeQueryAsync(
      Function.createDelegate(this, function() { alert( targetList.get_defaultDisplayFormUrl();) } ),
      Function.createDelegate(this, function() {alert("failed")})
  );	

</script> 
Technorati Tags: ,,

Create a free website or blog at WordPress.com.

Up ↑