An opinion on including multiple JS files in your project

There are many ways to solve an issue. Some work better than others though their pureness may be questionable. Getting many JS scripts and modules loaded is one such puzzle. I’m not a huge fan of require.js for a number of reasons that are already clearly, and eloquently, expressed by others. It is great at what it does, just not what I really want to use.What I do like is using a tool such as YUI compressor to facilitate delivering robust production code.

The following code is something I found on http://www.laurencegellert.com/ which I have since extended and included into my own projects.

#!/bin/bash

# This script generates the following:
# Combined and minified javascript file for use in the app

echo
"Combining JavaScript into temp files."

# temp.js is the uncompressed file with everything combined
cat
./app/js/jquery.js
./app/js/file1.js
./app/js/scriptX.js
./app/js/xyz.js
> ./app/js/temp.js

echo
"Compressing Combined JavaScript."
java
-jar yuicompressor-2.4.7.jar --type js -o ./app/js/temp.js --charset utf-8 ./app/js/combined.min.js

echo
"Cleaning up temporary files."

rm
./app/js/temp.js

And yes, I do work on OSX as well as Win8.

Tabbing web parts in a SharePoint web part page using jQuery and jQueryUI

Like many others I found EasyTabs to be a great fix. It has matured into something really great but that is not always the right tool for me so I went looking for a simpler solution. I wrote some jQuery that trawled the page and moved content around. It worked just fine but then I came across some very similar code but that used jqueryUI to create more elegant tabs.

The original source for this along with some good comments can be found here.

The final code I used is below.

< !– Reference the jQueryUI theme’s stylesheet on the Google CDN. Here we’re using the “Start” theme — > 
< link  type=”text/css” rel=”stylesheet” href=”//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/start/jquery-ui.css” / > 
< script type=”text/javascript” src=”//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js”>< /script>
< script type=”text/javascript” src=”//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js”>< /script> 

< script type=”text/javascript”>
    jQuery(document).ready(function($) {
// Visible title of each web part goes here.
        liTargetForTabs([“Web Part Title 1″,”Web Part Title 2”]);
    });

    function liTargetForTabs(TitlesOfWebParts)
    {
        for(index in TitlesOfWebParts)
        {
            var titlePassed = TitlesOfWebParts[index];
            $(“#liTargetForTabs”).append(‘< li>< a href=”#Tab’+index+'”>’+titlePassed+'< /a>< /li>’).after(‘< div id=”Tab’+index+'”>< /div>’);
            $(“span:contains(‘”+titlePassed+”‘)”).each(function(){
                if ($(this).text() == titlePassed){
                    $(this).closest(“span”).hide().closest(“[id^=’MSOZoneCell_WebPart’]”).appendTo($(“#Tab” + index));  }
            });
        }
        $(“#targetForTabs”).tabs();
}
< /script>
< div id=”targetForTabs”>
< ul id=”liTargetForTabs”>< /ul>
< /div>


SharePoint 2010 and JQuery

Recently somebody wanted to know how they could streamline activity on a site starting with reducing the overall page refresh count. Put simply, jQuery really is a lifesaver for this stuff. Combined with SharePoints web services and SPServices there is a huge amount that you can do without having to resort to writing any C#. The challenge, as with most things, is how to get started. Below are some simple examples of functional code that will work if you copy and paste correctly.

Example 1: Getting items from a list, in this case called “TestList1”, and output the raw response into a div tag called “demodiv1”
$(document).ready(function() {
$().SPServices({
debug: true,
operation: “GetList”,
listName: “TestList1”,
completefunc: function (xData, Status) {
var out = $().SPServices.SPDebugXMLHttpResult({
node: xData.responseXML
});
$(“#demodiv1”).html(“”).append(“This is the output from the GetList operation:” + out);
}
});
});

Example 2:  Getting all sub sites from a URL, in this case called “http://testserver/webapp1”, and output the raw response into a div tag called “demodiv2”
NOTE: The URL for the site can be defined in two ways, both shown. The one that is not commented is persistent – therefore rather useful!

$(document).ready(function() {
$().SPServices.defaults.webURL = “http://testserver/webapp1”;
$().SPServices({
debug: true,
operation: “GetWebCollection”,
//webUrl: “http://testserver/webapp1”,
completefunc: function (xData, Status) {
var out = $().SPServices.SPDebugXMLHttpResult({
node: xData.responseXML
});
$(“#demodiv2“).html(“”).append(“This is the output from the GetList operation:” + out);
}
});
});

Example 3: What kind of data exactly is being returned? Okay so if you have tried the first two examples you will have noted that the data really is kind of raw. Let’s see it in a popup. In this case the same code as above with a difference… Instead of updating a DIV tag we just populate a popup by using an alert.
Note: Play around with alert(“XML=” + xData.responseXML.xml); and alert(“xData: ” + xData.responseText);

$(document).ready(function() {
$().SPServices.defaults.webURL = “http://testserver/webapp1”;
$().SPServices({
debug: true,
operation: “GetWebCollection”,
completefunc: function (xData, Status) {
alert(“Status=” + Status + ” XML=” + xData.responseXML.xml);
});
}
});
});

Example 4: Okay, so now lets take the same data and wrap the title of each returned site in its respective URL inside of a DIV called tasksUL.

$(document).ready(function() {
$().SPServices.defaults.webURL = “http://testserver/webapp1”;
$().SPServices({
debug: true,
operation: “GetWebCollection”,
completefunc: function(xData, Status) {
// now iterate through the results
$(xData.responseXML).find(“[nodeName=Web]”).each(function () {
// for each one found get the title and wrap it with the respective Url
$(“” + $(this).attr(“Title”) + ““).appendTo(“#tasksUL”);
                });
}
});
});

Creating a site tour with jQuery

Sometimes when you build a custom solution end users need a little bit of help, or time, in order to determine where everything is. Grounding them within the actual environment rather than within help pages is the fastest way in my opinion to get them up to speed. A great option is jQuery site tour.

Working either manually or in a timed fashion it highlights predetermined classes with text and images. Tooltips on steroids in a way… To use it, you simply have to add certain class to any elements that you want to describe in the walk-through. E.g. “tour_1″, “tour_2″ would look like:

1 <div class="box left">
2     <h2 class="tour_1">Create a tour>
3     <p>Far far away, behind the word mountains, ...p>
4 >

The following parameters can be set:

  • name: the class given to the element where you want the tooltip to appear
  • bgcolor: the background color of the tooltip
  • color: the color of the tooltip text
  • text: the text inside of the tooltip
  • time: if automatic tour, then this is the time in ms for this step
  • position: the position of the tip

Resources
There is a full article with a functional demo here: http://tympanus.net/codrops/2010/12/21/website-tour/

Smartupdater: A JQuery periodical updating mechanism

I often need to implement some kind of periodical updating functionality from client to server and vice versa. Aka a classic polling mechanism. Smartupdater is a jQuery plugin which simplifies the process of sending regular requests to a server (polling) and handling the responses. I have found it very useful, and easy to work with. It can be started or stopped on any event and the interval of the polling periods can be redefined as well as controlled remotely.

A simple example would be how to display the remote time on a server with a polling interval of 5 seconds. Note that the remote script is returning a JSON format like this: “{“servertime”:”hh:mm:ss”}”

$("#example1").smartupdater({
  url : 'gettime_json.php',
  dataType:'json',
  minTimeout: 5000 // 5 seconds
  }, function (data) {
    $("#example1").html(data.servertime);
  }
);

The returned results can then be displayed in a div tag…

    
      Time on server: hh:mm:ss

Download link: https://code.google.com/p/smartupdater/

MongoDB: installing on windows as a service and your first database

MongoDB is an document-oriented DBMS. Think of it as MySQL but JSON (actually, BSON ) as the data model, not relational. There are no joins. If you have used object-relational mapping layers before in your programs, you will find the Mongo interface similar to use, but faster, more powerful, and less work to set up. In fact it is so easy to get running that I’m going to show you how to get it up and running as a Windows service in a few minutes.

But first, why would you ever want to use MongoDB?

The goal of MongoDB is to bridge the gap between key-value stores (which are fast and highly scalable) and traditional RDBMS systems (which provide rich queries and deep functionality). MongoDB is designed for problems that aren’t easily solved by traditional RDBMSs, including problems that require databases to span many servers.

MongoDB is a document-oriented database. This means that unlike a relational database management system, MongoDB manages collections of JSON-like documents. This allows many applications to model data in a more natural way, as data can be nested in complex hierarchies and still be query-able and indexable.

MongoDB supports an automated sharding architecture, enabling horizontal scaling across multiple nodes. For applications that outgrow the resources of a single database server, MongoDB can convert to a sharded cluster, automatically managing failover and balancing of nodes, with few or no changes to the original application code.

Moving on…

1: Getting the binaries…
Download the windows version here and be sure to get the 64bit version. The 32bit version has a limit of about 2.5Gb whereas the 64bit version has almost none… The reason for this is that the MongoDB storage engine uses memory-mapped files for performance and the goal for the engines code was to keep it as uncluttered as possible.

2: Create some folders
Before opening the downloaded archive you have to create a folder with content at the root of C: called “data”. Inside that create a folder called “db” Note that from now on I’m going to be giving the equivalent of shell commands highlighted and as you continue to read you will see why.

Start -> Run -> CMD
C:
cd C:
mkdir data
mkdir datadb
mkdir datalogs

At this point you should now have this structure on your file system.

3: Extract the downloaded files
You should have downloaded something named like this “mongodb-win32-x86_64-1.4.4.zip”

Extract the archive and move its contents to C: so you should see this type of structure:

4: Set MongoDB as a Windows Service
Looking inside of “bin” we can see a few .exe files. Our focus for now is going to be on “mongod.exe”

Setting it up as a service requires a couple of decisions. At a minimum:

  1. Where shall the logs go? In this example c:mongologs
  2. Where shall the data go? In this example c:mongodata 
  3. What port do want to run the web service on? In this example 1001.

With that decided creating the service is as easy as running the below from the command line.

mongod –bind_ip 127.0.0.1 –logpath c:datalogs –logappend –dbpath c:data –directoryperdb -port 1 –install

! If you wish to remove it just use: mongod –remove

So now Mongo should be visible in Services

Note the path to the executable and the fact that the service is not yet started…

Start the service and go here: http://127.0.0.1:1001/ where you should see the following information.

5: Accessing database
Accessing the database is done via mongo.exe found in bin
Run
C:
cd mongodbbin
mongo

and you should now be in the administrative shell like this.

! If you get an error like below just remove the service and redo without the port definition.

MongoDB shell version: 1.4.4
url: test
connecting to: test
Tue Jul 13 14:44:59 JS Error: Error: couldn’t connect: couldn’t connect to server 127.0.0.1 127.0.0.1:27017 (anon):952
Tue Jul 13 14:44:59 User Exception 12513:connect failed

Saving and retrieving is as easy as below.
db.foo.insert( { a : 1 } )
db.foo.find()

I have also included what the file systems should look like as well for this example.



And that’s it. You now have a working MongoDB service on your Windows machine!
Things to note

  • A performance environment would not have everything on C: 
  • Run binmongd -h for more options, there are not that many…
  • Defining the port rather than running it on the default 27017 requires some extras. Expect errors if you do not read up a bit more on MongoDB.
  • Did you notice that the administrative shell is a JavaScript interface..?

Resources

Improving the user experience with password entry

Sometimes deploying a forms based registration / login solution for SharePoint, or anything else, makes me somewhat weary. Specifically, creating the system that enforces, for sometimes tens or hundreds of thousands of people, the mundane action of having to add a password no less than twice after panning ones brain for a username when registering for an account just seems so old schoolish and tedious…

Adding a bit of colour, literally, here is a good thing. Not to much, not too little and you can add the equivalent of a breath of fresh air. One great tool for this job is Chroma-Hash.

Chroma-Hash is a jQuery plugin that aims to offer a better password input experience with a standard password field replaces the entered characters with “●” characters. The problem is “we never know if we made a typo or not until the form is submitted & a reply is received from the server”. Chroma-Hash, “converts the values entered” into a colored visualization.

A user filling the password field can easily recognize that if the colors are the usual equivalents of the password or not. And, anyone who sees the colors won’t have any idea what the actual password is.

The script can also be used to visualize password confirmations (password & confirm password fields).

A detailed info on the method & security concerns can be found at thedeveloper’s related post.

http://mattt.github.com/Chroma-Hash/

AeroWindow 2.0 – Cool Windows 7 style modal popups

AeroWindow is a jQuery plugin for creating Windows 7-like aero style modal pop-ups complete with the minimize, zoom, maximize and close functions. There can be multiple pop-ups in one page where the active one is highlighted visually. All on the screen can be resized, drag’n dropped and maximized with double-clicks.