Search

Binary Jam

Simon's blog, SharePoint, Arduino type things.

Tag

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

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

CEWP – Making Use of Coin Slider II – SPServices Version

Part II of the blog posts now, adding a quick tweak to auto populate the images from an ImageLibrary.

In the last post we created all the elements needed for this next piece, if you have that working then great.

First a couple of things

Get the latest SPServices version be sure to match the versions correctly especially where jQuery 1.7 and SPServices versions are concerned, changes in jQuery caused some problems in peoples libraries.  Put that library in the place you like to store them (_layouts, portal root, site collection, doc lib which ever I stuck it in my SPFolder in the site collection)

Add a new field to your Image Library, a checkbox and call it active.

Paste this code (after you modify the include statements to point at the places you stored them).

 

I haven’t put any error trapping in this code or loading pictures or messages to say activate at least one image you idiot but you can and I would if this was going on a real site. You could extend this code to get descriptions from the image library and if there was one add it to the slider text.

 







<div id="gamesHolder" style="width:468px;height:280px;overflow-y:hidden;">
    <div id="games">
    </div>
</div>

jQuery(function($) {
 
    $().SPServices(
       {         
         operation: "GetListItems",         
         async: true,         
         listName: "ImageLibrary", 
         CAMLQuery : "1",        
         CAMLViewFields: "",         
         completefunc: function(data) 
           {
                var theMiddle="";
                $(data.responseXML).find("z\:row, row").each(function(){
                    var getimage= "/" + $(this).attr("ows_FileRef").substring( $(this).attr("ows_FileRef").indexOf("#") +1 );

                    theMiddle +='<a href="' + getimage + '" target="_blank"><img src="' + getimage + '" /></a>';

                });

                $(theMiddle).appendTo('#games');
                $('#games').coinslider({ hoverPause: false, height:246, width:618});

            }
       }
    ); 


});


CEWP – Making use of Coin Slider jQuery

This post is how to use a small jQuery library within a CEWP to provide sliders.

First some pre-reqs.

Download jQuery (latest) and Coin Slider jQuery plugin.

Place the jQuery library in a

Choose one.

  • SPFolder
  • _layouts
  • Document Library
  • Any old web you have access to

 

You need to choose a location, I prefer master pages and putting things in _Layout, but if you dont have access to the server then you could utilise SharePoint Designer to create a folder in a site collection, again here I prefer the top top top  level Site Collection so that anywhere I use this the same js files come from the same place and get cached.

Place the CoinSlider CSS and JS files either in the same location (not master page though) or perhaps in the local site collection you are about to create this content in.

In my Code example I have already a jQuery in my masterpage, so I dont load it again.  I put the other files in an SPFolder in the site collection call jQueryExtras, you can reference them  from where you put them.

 

Next you need an Image Library, just create one somewhere, ideally unique for the content you are to display, as later on I might get to publish the next article that loads the images using SPServices, but then I might not.

In this image library place the images you want to slide, these should ideally be “landscape” style better still CinemaScope style. Those long thin pictures just work better in sliders. All these images MUST be the same size.

I used images from another sliders content (the nivo slider which I struggled to get to work, it was just easier than trying to find content) you could use images from your own stock or the demo just remember to change the image sizes in the right places (css/js).

Now that you have your JS and CSS includes in your locations and your image library populated with images we can create a CEWP, so on the page you want this go create one and hit the EDIT Source Editor

 

Paste this lot in, it is important that you set the height and width in the javascript to match your images, if you don’t expect lots of formatting issues. I tried this on MOSS and in IE7+ it wornt work in IE6, which is a pain for me as I have to find another slider now.

 <link rel="stylesheet" href="/sites/SliderDemo/jQueryExtras/coin-slider-styles.css">
<script src="/sites/SliderDemo/jQueryExtras/coin-slider.min.js"></script>

<div id="gamesHolder">
    <div id="games">
       <a href="http://www.binaryjam.com/" target="_blank">
          <img alt="Wall-E" src="/sites/SliderDemo/SliderImages/walle.jpg"> 
          <span><b>Wall-E</b><br>A Film about a robot. </span>
       </a>
       <a href="http://www.binaryjam.com/" target="_blank">
          <img alt="Finding Nemo" src="/sites/SliderDemo/SliderImages/nemo.jpg"> 
       </a>
       <a href="http://www.binaryjam.com/" target="_blank">
           <img alt="Toy Story" src="/sites/SliderDemo/SliderImages/toystory.jpg"> </a>
       <a href="http://www.binaryjam.com/" target="_blank">
           <img alt="Up" src="/sites/SliderDemo/SliderImages/up.jpg"> </a>
    </div>
</div>
<script>jQuery(function($) {
	$('#games').coinslider({ hoverPause: false, height:246, width:618});
});
</script>

<!-- -->

<!- Force Stupid blog code window to be bigger -->

<!-- -->

Have fun

jQuery autocomplete for SharePoint Search Box

Whether or not SharePoint actually needs an autocomplete for it’s search box could be debated, and the manner in which I’m about to implement it, well that could be debated also. 

The point of this post was to use jQuery techniques to query a list via its web services and do something flash.  I’m doing it SharePoint 2007 as that is what I have handy and working. 

I will be upfront and honest right now, the code for this is a Mashup from two sources, Jan Tielens and the jQueryUI demo itself, both needed tweaking to come up with something new, but just so you know it’s not been rocket science, hard work was done for me, cheers Jan. 

Continue reading “jQuery autocomplete for SharePoint Search Box”

WSS3 – ItemAdded – deadlocked on lock

I’ve been having a problem with an app I wrote.  It works great, 99% of the time, but sometimes the ItemAdded event appears not to fire.

Now this is using a list with over 20,000 entries in it and its growing all the time.  An associated list that references this list as a lookup has over 144,000 entries in it.

The event firing problem is becoming more frequent now as more users start using the system, there are at least 20 occurances in that 20,000 items, so it has to be fixed.

Managed to track down an error in the log

System.Data.SqlClient.SqlException: Transaction (Process ID 61) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

It’s stack trace was similar too this (I cut it down a bit and changed some names, my naming is not this bad)

at Microsoft.SharePoint.SPListItemCollection.EnsureListItemsData()
   at Microsoft.SharePoint.SPListItemCollection.get_Item(Guid uniqueId)
   at BinaryJam.Core.Code.TicketListReceiver.ItemReceiver.ItemAddedActual(Guid SiteId, Guid ListItemId, String UserDisplayName)
   at BinaryJam.Core.Code.TicketListReceiver.ItemReceiver.<>c__DisplayClass11.<ItemAdded>b__e()
   at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state)
   at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
   at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
   at BinaryJam.Core.Code.ItemListReceiver.ItemReceiver.ItemAdded(SPItemEventProperties properties)

So as you can see, it explodes on the GetItem.

This was my stupid mistake, a mistake I bet many of you are making every day.

SPListItem item = List.Items[listItemId];

This I believe is the primary cause of the problem as this statement loads the complete List before returning the specific item I needed and as this list grows, remember 20,000 items already, its going to get worse.  Now for most of you this won’t be a problem as you will be just getting the ListItem from the parameters, in my case I have to run as elevated as Im doing lots of stuff with Security Groups, that the entering user may not be in, hence my needing to re-get the List Item in the right security context.

So if your having a problem like this remember, Always use the

List.GetItemByID(id); //Or
List.GetItemByUniqueId(guid);

This may or may not solve my problem I believe it will, if it doesn’t it’s still going to improve the performance of my application.  If your wondering, this is the only time I use this and don’t know why I did, the rest of the App uses getby id or SPQueries.

A Good Article on Performance I did actually read, hence the app performs pretty well, except for this one bug, which is now hopefully fixed.

 

 

 

 

WSS Problem with Provisioning

Been having a problem with SiteProvisioningProvider. Well I haven’t but apparently it causes problems down the line if things are not done in a specific order.

A nice man at microsoft diagnosed the problem and came up with the code you should run to ensure your not messing up the Web.

Here is a posting of the proposed solution to the bug we found (I don’t care if they don’t think its a bug, not sure if they do or don’t but I do!)

http://blogs.msdn.com/joerg_sinemus/archive/2009/11/24/overwriting-spwebprovisioningprovider-provision.aspx

Sharepoint and ResX and a little tool

I am doing lots of work in Sharepoint that requires resource files in english and german.

With a variety of developers before me different styles of editing the foreign language files emerged.

I think that much better tool support for managing resx’s is required,  and I recently found one that is a great help to us with a vareity of resx’s in various states of translation and existence.

http://resxtranslator.codeplex.com/

This resx tool allows you to pick a file and it displays the nuetral and foreign side by side along with comments and allows you to edit them all at once.  Corking piece of work, some polish would go amiss but Im hard pushed to say where as it does exactly what I need it to do and I can pass it to a non-techie developer.  It still down to me to edit the comments first to identify what needs translating and what definately needs leaving alone.

If you doing multi-language work go and check this tool out it might just help.

Using a ListViewWebPart for Search Results

I have had to try and create a Search page that displays its result set in the style of a ListViewWebPart.  This has proven quite tricky.

After a lot of Searching I found various articles on using SPQuery and then the List.RenderAsHtml(Query) to achieve this.  However I found a rather large problem with this method, whilst it queries what I want it to the resulting HTML looks nice but does not do any kind of paging also whilst the sort and filter  drop downs appear at the top of the columns, they don’t actually do any sorting or filtering.

Now that was completely unacceptable.

Continue reading “Using a ListViewWebPart for Search Results”

Create a free website or blog at WordPress.com.

Up ↑