SharePoint Development: Lesson 4

Welcome back to my ongoing series on SharePoint development!

I promised last week that I’d follow up lesson three within a week, so here we are! In that previous lesson everything we did was in relation to setting the stage for what we’re going to tackle today, so I’ve got no doubt that you’ve been waiting with barely contained anticipation to get back to writing some code.

Because all the steps from last week were fairly standard SharePoint stuff, if you’re pretty familiar with the platform you may well have skimmed through it. That’s fine, but for everything we do today to be successful we’re going to need to make sure that:

  • We’ve created and populated a list of shipping prices, with different shipping profiles (in our example, these different profiles are based on destination).
  • Uploaded the SPServices library minified javascript to our “web” document library.
  • Located and noted the GUID of the shipping prices list, so that we can programmatically reference it in our code.

With those steps done everything is in place, so let’s not waste any more time!

The HTML

The HTML portion of our code hasn’t changed very much since we wrote it way back in lesson one, and it doesn’t change much today either. That being said, we do have an additional option that forms part of our calculation this time around, so we’ll add a form element for that.

Destination province:
Please wait, loading data...

Item weight:
lbs

Shipping cost: $0

As you can see, we’ve added a drop-down menu that allows for the selection of the destination province. In the HTML it has a single entry in the list that says “Please wait, loading data…” As you might anticipate, we’re going to remove this option later on and replace it with the actual choices, but it’s probably good practice to have something there because the SPServices library is going to read from our list with an AJAX HTTP request – in other words the page will load first (with our “please wait” message), and the data to populate the list will be loaded afterwards. Hopefully it will all happen so fast that nobody ever really sees the “loading” message, but you never know.

The JavaScript

OK, now we’re really going to start getting into some changes in functionality! First things first, though. We need to include the external libraries we’re going to be using. jQuery has been there from the start of our journey, but SPServices is new for today.

/web/js/jquery-1.11.0.min.js
/web/js/jquery.SPServices-2014.01.min.js

The other thing I’m going to do at the beginning of my main block is declare a global variable in which to store list data. There are probably better approaches than this, but for the sake of keeping my code relatively simple this is one I’m taking.

var shippingData = false;

Loading Data from our SharePoint List

Next is where the SPServices magic happens. Immediately inside our jQuery document ready function we’re going to call SPServices and grab the data from our list, putting the result of that request inside our shippingData variable. SPServices has many available options that get passed as an object to its main function and more details can be found in the documentation on their website. Like I said though, I’m keeping things simple:

$().SPServices({
   operation: 'GetListItems',
   listName: '{4883AC18-E2A5-4EAF-8446-23B15B43861A}',
   completefunc: function(xData, Status) {
      if (Status == 'success' && ($(xData.responseXML).find('ErrorCode').text() == '0x00000000' || $(xData.responseXML).find('ErrorCode').text() == '')) {
         shippingData = $(xData.responseXML).SPFilterNode('z:row');
         populateDropdown();
      } else alert('Something went wrong!');
   }
});

Not bad, eh? Ten lines of code and we’ve read all the data from our SharePoint list. Let’s look at what we’ve done in a bit more detail.

The code we’ve written can be summarized as:

$().SPServices(obj);

All we’re doing is calling the SPServices plugin and passing in a javascript object that contains all the options it needs to understand what we want it to do. There are many options we could pass to it, and you’ll find more detailed documentation on the SPServices homepage. I’ve kept things as simple as possible and passed in the bare minimum.

Operation: ‘GetListItems’

In our example we’re dealing with items in a list. GetListItems is the operation we need to read data from a SharePoint list into our webapp. There are many other types of operation related to lists that SPServices could do for us – creating entirely new lists, adding or removing list fields, deleting lists, etc. Essentially almost anything you could do manually on SharePoint could be done programmatically with SPServices. If we wanted to write data back to a list then UpdateListItems would be the operation we’d use.

ListName: '{4883AC18-E2A5-4EAF-8446-23B15B43861A}'

The ListName parameter could take one of several formats. A simple string containing the name of the list will work, but to avoid any kind of confusion between similarly named lists my preference is to pass in the GUID of the list. Remember that the GUID of your list will be different to mine. SPServices can also take a WebURL parameter that tells it which site in your SharePoint collection the list can be found on, but since we’re using a GUID that’s unique across all sites in the collection we don’t need that.

completefunc:  function(xData, Status)

This is where the real magic happens. The completefunc parameter represents a callback function that SPServices executes once data has been loaded, and it takes two parameters: xData and Status.

Our completefunc does some basic error handling, and then calls another function to do the dirty work.

if (Status == 'success' && ($(xData.responseXML).find('ErrorCode').text() == '0x00000000' || $(xData.responseXML).find('ErrorCode').text() == ''))…

For the Status parameter that’s passed in to completefunc, we’re looking for it to contain a value of ‘success’. We have to be a little careful about exactly what this means though: To SPServices success means that it’s passed a query to SharePoint and received a response. It doesn’t mean that our query was well formed, or that we received any useful data back. Basically you’ll always get a successful status unless SharePoint is down – in which case our webapp probably wouldn’t be available to users anyway.

To check that our query has truly been executed successfully by SharePoint, we look in the responseXML for an error code. Depending on the version of SharePoint we’re running, that will either be 0x00000000 or blank.

shippingData = $(xData.responseXML).SPFilterNode('z:row');

There are few ways we could approach what happens next. My goal was to keep my code as simple as possible so I’m doing some things that may not be best practice. This is one of them: we take the data SPServices has returned and put it into a global variable.

The data SharePoint has passed back to us is in XML format and contains a wealth of information about our query, metadata about the response, and so on. We don’t really need any of this stuff – we just want the data itself – so SPServices has a function called SPFIlterNode that helps us filter the returned data down to what we actually care about. We’re filtering here by z:row. Each z:row returned represents one entry from our SharePoint list.

populateDropdown();

Now that we have our data in a globally accessible variable, I’m outsourcing the processing of it to another function: populateDropdown. That last step for our completefunc is to call this function.

Populating the Dropdown List

OK! So now we have the data we need loaded from our SharePoint list and resident in memory (in our shippingData global variable) so that we can manipulate it and our users can interact with it. The first step of this process is to populate the relevant options into the select box we created in our HTML. I’m doing that (surprise surprise) with the populateDropdown function.

function populateDropdown() {
   $('select#destination option').remove();

   for (i = 0; i ' + $(shippingData[i]).attr('ows_Title') + '');
   }
}

If you recall, the dropdown list initially contains a single option with the text Please wait, loading data…. At this point in the story our data is loaded, so let’s get rid of that option first:

$('select#destination option').remove();

Done! Good. The next step is to loop through each of the items we’ve loaded into our shippingData variable, and add them as an option in the dropdown. We do this with a standard for loop:

for (i = 0; i 

If you’re not familiar, this construct sets a variable i to zero, then loops through the following block of code multiple times, as long as i is less than shippingData.length, which is the number of items in our shippingData variable. On each iteration i is incremented by one (i++).

On each loop we add an item to our dropdown, using jQuery to append the relevant HTML. Based on the data that exists within our SharePoint list, we end up with these options in our dropdown:

Each $(shippingData[n]) has an attribute for each of the columns in our list. These attributes all have the prefix ows_, and, as mentioned in lesson 3, they are all referenced by the original name of that column (even if it’s been renamed since it was created). That’s why we’re using the attribute ows_Title to get at the data that’s in our Province column: the column was called Title when the list was created, and we renamed it.

Performing the Calculation

With any luck everything in our story up to this point will have happened in a split second, but regardless we’re now ready for user input. The user selects the destination province, inputs the weight of the item being shipped, and hits the calculate button.

The calculation itself is really no different from the one we built in lesson 1, the difference being that our variables are defined by the list data rather than hardcoded in.

We still identify that the Calculate button has been pressed through the use of the jQuery $(‘input#calculate’).click(function() {});, but our first step is now to set some variables based on whatever is selected in the destination province dropdown at the time.

bp = parseFloat($(shippingData[$('select#destination').val()]).attr('ows_BasePrice'));
bw = parseInt($(shippingData[$('select#destination').val()]).attr('ows_BaseWeight'));
ap = parseFloat($(shippingData[$('select#destination').val()]).attr('ows_AdditionalPrice'));
aw = parseInt($(shippingData[$('select#destination').val()]).attr('ows_AdditionalWeight'));

We set each of these variables by reading the relevant attribute (representing the column in our SharePoint list) from $(shippingData[n]), where n is the value of the destination dropdown, $('select#destination’).val(). After that, it’s business as usual:

var shippingcost = bp;

if ($('input#itemweight').val() > bw) {
   shippingcost += (Math.ceil(($('input#itemweight').val() - bw) / aw) * ap);
}

$('span#shippingcost').html(shippingcost);

Putting it All Together

And we’re done! The completed code block – including all the javascript and HTML – that we copy and paste into our content editor webpart is as follows:

/web/js/jquery-1.11.0.min.js
/web/js/jquery.SPServices-2014.01.min.js

   var shippingData = false;

   $(document).ready(function() {
      $().SPServices({
         operation: 'GetListItems',
         listName: '{4883AC18-E2A5-4EAF-8446-23B15B43861A}',
         completefunc: function(xData, Status) {
            if (Status == 'success' && ($(xData.responseXML).find('ErrorCode').text() == '0x00000000' || $(xData.responseXML).find('ErrorCode').text() == '')) {
               shippingData = $(xData.responseXML).SPFilterNode('z:row');
               populateDropdown();
            } else alert('Something went wrong!');
         }
      });

      $('input#calculate').click(function() {
         bp = parseFloat($(shippingData[$('select#destination').val()]).attr('ows_BasePrice'));
         bw = parseInt($(shippingData[$('select#destination').val()]).attr('ows_BaseWeight'));
         ap = parseFloat($(shippingData[$('select#destination').val()]).attr('ows_AdditionalPrice'));
         aw = parseInt($(shippingData[$('select#destination').val()]).attr('ows_AdditionalWeight'));

         var shippingcost = bp;

         if ($('input#itemweight').val() > bw) {
            shippingcost += (Math.ceil(($('input#itemweight').val() - bw) / aw) * ap);
         }

         $('span#shippingcost').html(shippingcost);
      });
   });

   function populateDropdown() {
      $('select#destination option').remove();

      for (i = 0; i ' + $(shippingData[i]).attr('ows_Title') + '');
      }
   }


Destination province:
Please wait, loading data...

Item weight:
lbs

Shipping cost: $0

Taking it Further

The next steps with our shipping calculator app would be to add some additional error-checking and handling, and maybe amend the code to avoid using unnecessary global variables. I’ve kept things as simple as possible here for the sake of example.

After that? As I mentioned earlier, there’s a lot of cool stuff we can do with SPServices. Where you go from here is really up to you, but hopefully you can see some possibilities. Even with the basic building blocks of reading from and writing to lists, it’s possible to build some really cool stuff on top of SharePoint, possibly even taking the approach of using SharePoint as a database for a webapp that has its own look and feel.

Enjoy!

SharePoint Development: Lesson 3

Welcome back to my continuing series on SharePoint development!

If you’ve been following along with lesson one and lesson two then this post has probably been a long time coming, but we’re now at the point where we’ve built a pretty useful tool for calculating shipping costs, and we’ve integrated it into our existing SharePoint site to make it easily accessible to everyone in our team who might benefit from it.

Here’s the thing, though. If your organization is anything like mine, then SharePoint is a tool that they’ve made available to everybody. You’re using it for some cool stuff, but writing code probably isn’t your day job – you’re the techy guy or gal in your group who’s found an opportunity to make everybody’s life a little easier with technology, and the beautiful part is that you can do it all without needing to engage your company’s IT team (who are busy with large-scale projects involving a contribution to your company’s bottom line, which your idea for a shipping calculator would need to be prioritized against).

There’s nothing wrong with any of that. Something like this really shouldn’t be a thing that your company’s IT team get involved with in the exact same way that helping you craft an especially complex excel formula shouldn’t be a job for them either. If you’ve ever crafted an especially complex excel formula in a workbook that’s shared throughout your group though then you may already have identified the downside to this approach: things change.

Our tool is built on a fixed model for calculating shipping costs of $19.99 for the first 20lbs and $3 for every 5lbs (or part thereof) over and above that. That rule is embedded within your code now, you’re the only one around with the necessary technical knowledge to update it when shipping costs change, and you have a day job to worry about too. If updating SharePoint tools is not how you like to spend your weekends, then we need a different approach.

What we need, then, is a solution where the average SharePoint user can make changes to key pieces of data, and our tool needs to be smart enough to read that data so that it can be used in calculations. And, while we’re at it, let’s expand the tool so that it can handle a few different shipping profiles (which could represent different couriers or, in our example, destinations).

Enter the SPServices library. SPServices is a jQuery plugin that’s used to expose SharePoint data to our jQuery apps, including (amongst other functions) reading from and writing to SharePoint lists in SharePoint 2007, 2010 and 2013.

This is a significant step up from where we were at the end of lesson two (which is probably why I’ve been procrastinating over writing it for so many weeks). I’ve split it into parts. Today we’re going to set the stage and prepare our data, and this time next week (I promise!) we’re going to get our hands dirty with some code.

Nevertheless, both this post and its successor are probably going to be longer than those that have gone before, so be forewarned, go grab yourself a cup of coffee, and let’s dive in!

Creating the List

First things first, we need a list to hold our data. This list is where our less-technical colleagues will come when changes need to be made and we’ll keep it fairly straightforward.

Much like we did to create our document library in lesson one, go to Site Actions > View All Site Content and hit the Create button. This time we’re going to choose Custom List as the type of entity we’re going to create. We need to give the list a name, so let’s call it “Shipping Prices.” For the time being we’ll leave the description blank, and we’ll hide our list from the Quick Launch bar. We can always change these options later.

image

When you hit the Create button the list will be created and will have a single column (“Title”). We need to add a few more columns, so choose List Settings from the toolbar or the Actions menu (depending on your version of SharePoint). The first thing we’re going to do is rename the “Title” column to “Province” by clicking it in the list, then we’re going to add four more columns by clicking the Create Column link and adding them one by one. Here’s where we want to end up:

image

An Important Note Regarding Column Names

With this the basic framework for our data is in place. You may notice that none of our column names have spaces in them. That’s because SharePoint in the backend does strange things with spaces. As you’ll see later we can programmatically read from a column called “BasePrice” by referring to it exactly in that way, whereas a column called “Base Price” would need to be referred to in our code as “Base_x0020_Price.”

That being said, we can leverage a bit of trick here if want to improve readability for people who will interact with this list directly (our less-technical colleagues, remember). Behind the scenes (and in our code) SharePoint will always know the column by its original name, even if it’s subsequently been renamed. If we go back and spaces now, the internal name of the “BasePrice” column will remain “BasePrice,” even if its display name is changed to “Base Price.”

This is helpful in this scenario, but can easily be a bit of a gotcha – you need to remember the original name of all your columns, because that’s how your code will reference them. Remember the “Title” column we renamed to “Province?” It’s still “Title” behind the scenes.

Populating the Data

There are many ways to get data into a SharePoint list, and I’m not going to go into a great amount of detail here. You can add each item row by row with the built-in list forms, you can use SharePoint’s datasheet view to edit many rows at once, or you can use a third party tool. Our example is probably a little basic to warrant breaking out a special third-party tool for, but nevertheless as you do more complex stuff in the future I’m a fan of SharePoint List Item Editor. It does exactly what its name suggests, gives you a spreadsheet-like interface for editing items in SharePoint lists, and makes it easy to copy and paste many rows at once.

Regardless of how we do it, here’s the data I’m going to put into my list for the purposes of this example.

image

With this data in place you’re probably starting to get a sense of where things are going with this example. The BasePrice is the cost of shipping the first BaseWeight pounds, and the AdditionalPrice is the cost of each AdditionalWeight pounds or part thereof.

In many ways it’s no different from what we’d created by the end of lesson two, but with one critical difference – none of these variables are going to live in our code anymore. They’re all factored out into the list where they’re easily editable when things need adjusting in the future.

image

Find The GUID of the List

Everything we’ve done so far is fairly standard SharePointy stuff, but you’ll notice we’ve had one eye on the end goal of programmatically interfacing with this data throughout. Finding the GUID of the list we’ve created is an important step in this process.

A GUID is a globally unique identifier, and every SharePoint list (or calendar, or document library, etc) on our SharePoint site collection has one. There are several ways we can connect our front-end custom interface to our back-end data, but the GUID is probably the most reliable because as the name implies, it’s globally unique. It’s also not affected if our list gets renamed later.

There are several ways to find it, but my favourite is to use a simple tool I found for the purpose. Open the app and plug in the URL of your SharePoint site. Hit the Display List Titles and IDs button, and grab the relevant ID (including the opening and closing braces).

image

For me {4883AC18-E2A5-4EAF-8446-23B15B43861A} is what I need. For you it will be different. You may notice that the tool can also find the GUID of a list view. We don’t need this because we’re going to use the default view. I’m not going to get into it right now, but if you’re unfamiliar SharePoint views define things like the sort order and filter that’s applied to a list, and each list can have multiple views defined. If you want to programmatically access data that’s filtered out of your default view then the simplest method is probably to create a new, unfiltered, public view and reference it by its GUID in your code. The documentation for SPServices will tell you more.

…and Talking of SPServices

Now is probably a good time to download the library and place the minified javascript file in the “web” document library we created in lesson one, in the “js” subfolder alongside the jQuery library that’s already there. At the time of writing this file is called jquery.SPServices-2014.01.min.js. With that our stage is set and we’re ready to rewrite the code in our content editor web part to interface with it, but that was a lot to take in so we’ll get to that next week.

SharePoint Development: Lesson 2

Welcome back to my series of posts on SharePoint development!

At the end of lesson one we’d used some basic HTML, javascript and jQuery skills to create a tool for calculating shipping costs, and we’re hosting the tool on our team SharePoint site so that everybody who needs it has access.

image

This is great and all, but as we noted – it doesn’t exactly feel like our tool is a part of SharePoint. That might be fine if we’d built something extremely complex where having it as a self-contained webapp of sorts made a lot of sense, but it seems wrong for our purposes.

What we need to do is somehow build the tool into the main page of our SharePoint site so our users don’t even have to think if they want to use it – it’s just right there waiting for them.

The Content Editor Web Part

Believe it or not, we laid the groundwork for this in lesson 1 even without knowing it. The final step last time was to add a content editor web part to our page with a link to the tool in it.

image

The content editor webpart is much more powerful than that though, and we’ve barely scratched the surface. First, let’s take a closer look at what we have there already.

image

From the web part’s menu, choose the Edit Web Part option. An options pane will appear on the right of the screen.

If you’re using SharePoint 2007 there’s a button in the options pane called Source Editor, and this is where you’ll want to go. On SharePoint 2010 you’ll need to click into the web part first of all so that the ribbon appears at the top of the screen, then select HTML and Edit HTML Source from the Format Text ribbon.

Right now, my source looks like this:

​<a class="ms-rteFontSize-7" href="/web/shipping.aspx">Shipping Cost Calculator</a>

Simple enough, but hopefully you’re beginning to see where I’m going with this. The content of the web part is rendered inline as part of the HTML of the overall page, and we can put whatever we want in there. We can only edit this one snippet of the page where the web part lives, but that’s OK – it’s good enough.

Last time we included a reference to the jQuery library in the <head> section of the page, but does it actually need to be in the head? It may not be semantically great code, but we can put that reference anywhere. And once we have we’ll have all the power of jQuery at our disposal to manipulate the main page of the site however we see fit.

For now, let’s modify the code we used in lesson one to make it appropriate for inclusion in the middle of a page:

/web/js/jquery-1.11.0.min.js

   $(document).ready(function() {
      $('input#calculate').click(function() {
         var shippingcost = 19.99;
         
         if ($('input#itemweight').val() > 20) {
            shippingcost += (Math.ceil(($('input#itemweight').val() - 20) / 5) * 3);
         }
         
         $('span#shippingcost').html(shippingcost);
      });
   });

Item weight:
lbs

Shipping cost: $0

Paste that in to the content editor web part’s source, and save. On my installation of SharePoint 2010 a warning pops up telling me my HTML may have been edited. I don’t know why SharePoint feels the need to do this, but it doesn’t seem to matter.

Our shipping cost calculator is now looks like it’s really a part of our site homepage, and we’re done another quick lesson!

image

Taking it Further

What we’ve done here is great for our purposes, but we’ve actually opened up a world of extra possibility here.

As I noted, the HTML and javascript we’ve pasted into our content editor web part goes directly into the page, inline. In some respects that’s not the best – we have script tags in the middle of the page which isn’t really the correct approach, but in other ways it’s extremely powerful.

We can use our script to manipulate the page however we choose. If the approach we’ve chosen to take is to include our code in a web part then we probably don’t want to go nuts and change everything, but if you want to manipulate, say, the document’s title? Easy!

document.title = 'Site Home and Shipping Calculator'

If you want to include a custom CSS file? Done!

$("head").append("<link rel='stylesheet' href='/web/css/example.css' type='text/css' media='screen'>");

And if you have another web part that you want to use jQuery in, there’s no need to include a second reference to the library – one per page is all you need. You can easily have one content editor web part that influences another.

Conclusion

So, in lesson one we built a simple tool and now in lesson two we’ve integrated it right into our SharePoint page. There’s a lot you can do with this knowledge. In lesson three we’ll go deeper still though, and begin to use data from SharePoint lists in our tool with the help of the SPServices jQuery add-on.

SharePoint Development: Tools of the Trade

As I noted in my last post, lesson two of my SharePoint development series is still nothing more than an item in the “someday” section of my to-do list at the moment, but in the meantime I thought I’d share a few tools that I find invaluable when I’m doing SharePoint development work.

  • Notepad++
    Any good text editor with a focus on code will do, but Notepad++ is my tool of choice, not least because it’s available in a portable version that I can run on my work computer without having to ask our IT department to install anything for me (not that I would ever run unapproved software, obviously. I’m just saying you could).
  • SPServices jQuery Library
    I’ll be introducing this little gem in lesson 3, if/when I get around to writing it.
  • Find List and View GUIDs
    SharePoint lists and views all have unique IDs assigned to them by the system, and it’s useful (again, for reasons that will become clear later) to be able to find them. This simple tool does just that.
  • SharePoint List Item Editor
    Another simple but extremely useful tool. This one presents lists in a grid view which is great for mass-editing, copying and pasting from Excel, etc, etc.

Enjoy!

Update:

I’d previously also listed SharePoint CAML Query Helper in this list, with the caveat that I hadn’t actually tried it but screenshots I’d seen made me hopeful that it would make the process of building CAML queries (which are the method by which you can control what data from a list is returned to you when you’re using SPServices) easier.

It’s is a worthwhile tool to have in your toolbox and it’s great for testing CAML queries, but it didn’t make building them as easy as I’d hoped.

What I want is a tool that lets me select a list field, enter the criteria by which I want to filter on that field, and then spits out the CAML query that I need to use. If anybody knows of such a tool please let me know in the comments!

SharePoint Development: Lesson 1

Welcome to lesson 1 of my mini-series on SharePoint development! This is the first post where we really dive in and get our hands dirty, although I did previously write about installing SharePoint in a Virtual Machine. Anyway, I’ve been threatening to write about this stuff for quite some time now, so it’s probably about time I got started.

I’m going to assume as I write this that you already have at least a little familiarity with SharePoint and it’s capabilities, as well as some experience with HTML, javascript and jQuery. With these assumptions in place what I’m going to help you do is tie everything together to create some cool SharePoint-based tools, but don’t worry – we’re going to start off slowly.

SharePoint Document Libraries

Document libraries are a feature of SharePoint that you probably already know about. They’re a great way to store Microsoft Office documents that should be shared with a wider audience throughout a team or an organization. You can enable version control, and there are features to prevent clashes in situations where multiple users may try to work on the same document at once.

For our purposes we don’t care about most of that, but SharePoint document libraries can contain any type of file – not just office documents. For today, we’re going to use a document library simply as storage for an HTML document and the jQuery library, and we’re going to build a simple tool to calculate shipping costs. Over time we’re going to integrate this same tool more tightly into our SharePoint site, and begin to leverage more and more of SharePoint’s functionality.

But like I said, we’re starting slowly.

Creating a Document Library

Creating a new document library is a fairly simple affair. Some versions of SharePoint (2010 onward) have a shortcut for it in the Site Actions menu, but regardless of the version you’re running if you to Site Actions > View All Site Content and then hit the Create button you’ll find what you need. Select Document Library from the list of things that you can create.

Next, give the document library a name. It really doesn’t matter what you call it because we’re not going to send people to the document library itself – just to content within it. The name will feature in the URL of files that we store though, so for simplicity I’d recommend a name without any spaces. I always call mine “web,” but that’s just personal preference.

Under Display this document library on the Quick Launch? we’re going to select No. Choosing yes places a link to the library on the main page of the site, but as I noted – we don’t really want people to visit the library directly.

For Create a version each time you edit a file in this document library? you can select No here also – as we move through successive lessons in this series we’ll end up using the library only to store assets like scripts and images, so we don’t really need this feature. You can leave the Document Template drop-down at it’s default value – this setting won’t be relevant to us either.

Finally, hit the Create button at the bottom of the window.

image

The document library is now created. The first thing we’re going to do is create a folder for javascript files. Hit the New Folder button and create a folder called js. For today, this is the only folder we’re going to need. Download the jQuery library from the web, and upload the javascript file to the js folder.

Creating the HTML Page

I’m not going to dwell too much on this section because you can find much better tutorials out there for this than I could write, but I’m going to create a simple tool that asks for an item’s weight and then spits out a shipping cost.

For the sake of the example, I’m going to calculate shipping costs as follows: costs are $19.99 for anything up to 20lbs, and then an extra $3 per 5lbs (or part thereof) for anything heavier.

I’ve kept the code extremely simple with no error checking or any such niceties (in a real world tool you’d want to be more robust), and here it is:

<!DOCTYPE html>
<html>
<head>
   <title>Shipping Cost Calculator</title>
   /web/js/jquery-1.11.0.min.js
   
      $(document).ready(function() {
         $('input#calculate').click(function() {
            var shippingcost = 19.99;
         
            if ($('input#itemweight').val() > 20) {
               shippingcost += (Math.ceil(($('input#itemweight').val() - 20) / 5) * 3);
            }
        
            $('span#shippingcost').html(shippingcost);
         });
      });
   
</head>
<body>
   <h1>Shipping Calculator</h1>
   

Item weight:
lbs

Shipping cost: $0

</body> </html>

The only really notable part here is that we’re linking to the javascript file we uploaded earlier:

/web/js/jquery-1.11.0.min.js

Save the file as shipping.aspx, upload it to the root of the web document library, and that’s pretty much it!

Why the “aspx” File Extension?

On SharePoint 2007 and earlier linking to an html file in a document library will open the file (which is what we want to happen), but on 2010 onward the file will be downloaded instead. Using the aspx file extension solves this problem.

Linking to the Tool

OK, so we’ve created a useful tool and we’ve made it available on SharePoint, but it’s in a document library that’s hidden from view – a typical user would never find it.

So how do we make this available to a wider audience? Well there are several ways, but I’m going to add a new webpart to the main page of my SharePoint site and put a big, bold link in it.

Back on the main page of our SharePoint site choose Edit Page from the Site Actions menu and click the Add a Web Part button. We’re going to add a Content Editor webpart. You’ll get a word-style editor where you can insert text, images, tables, etc… and crucially links. I’m going to insert a link to the HTML file we’ve just uploaded, and increase the font size to make it stand out on the page. If you’ve been following along exactly then the address of the uploaded file will be /web/shipping.aspx.

You’ll probably also want to go to the Appearance section of the webpart properties and give it a custom title.

image

Conclusion

So, we’ve built a simple webpage with some javascript in there to calculate things for us and we’ve deployed it SharePoint, making it available to site visitors. This is great and all, but it doesn’t really feel like the page is a part of SharePoint. It doesn’t look or feel the same, and from a user experience point of view it seems as though we’re leaving the SharePoint site when we use our calculator tool.

That’s OK though! Today was just about getting started. In part two we’ll take the functionality we’ve just built and integrate it much more tightly into SharePoint itself. Stay tuned!

Installing SharePoint Foundation in a VirtualBox Virtual Machine

For a while now I’ve been vaguely threatening to write a post or two about my work with SharePoint, but so far I haven’t actually managed to get around to it.

The reason is essentially simple: SharePoint is a huge tool my company makes available to me, and everybody else that works there. They installed and maintain it on their servers, and I am but a lowly user.

That’s fine. The whole point of the development work I do on top of SharePoint is that anybody could do it. I don’t need any special admin rights and I don’t need to get the technical guys involved. The problem is that when it comes to blogging about my work on SharePoint, all my work is on my company’s internal intranet. If I wanted a SharePoint site for testing purposes I’d have to put a request in and I’m not sure it would be approved, I don’t want to build test things on an existing site, and I certainly don’t want to risk accidentally revealing some proprietary information in a screenshot or something.

So, I’m going to install my own copy of SharePoint in a virtual machine and take you through it in this blog post.

Wait, what? Why?

SharePoint server is a big, enterprise-grade tool that powers intranet and internet sites across the world. Why would I want to install it at home? Well aside from using it to blog about my work, I plan on using it to help me work.

When I develop new SharePoint tools for my job I keep then hidden at the start. It’s kind of a security-through-obscurity type deal, and even though I’m typically developing on a live site your average SharePoint user won’t find what you’re working on if there isn’t a link to it on their screen. This is great when you’re launching new things, but if you want to update a tool that’s already been rolled out and is in use it presents some challenges. What do you do in this situation? The choices are either to create an entirely new version of the tool and possibly a duplicate of the data that powers it, or just bite the bullet and make changes to the live production code. I’d rather have my own sandbox environment I can play in without fear of breaking something.

Isn’t SharePoint server expensive?

Yes. But also no! There’s a version called SharePoint Foundation that Microsoft makes available for free, and it’s perfect for our needs. It’s designed to run on Windows Server 2008 or 2012, but it can also be installed on 64-bit versions of Vista or Windows 7, which is what I’m going to do.

Why a virtual machine?

To setup SharePoint server you do need to install some pre-requisites and change some operating system options, and I don’t want to do that on my desktop computer.

OK, I’m in. Let’s go!

Great!

Start by downloading and installing some virtualization software. My environment of choice is VirtualBox so that’s what I’m going to be using. If you don’t have an existing preference for something else, then I’d recommend you do the same.

Creating the VirtualBox VM

  1. Open VirtualBox and hit the new button in the top left
  2. Give your virtual machine a name, select the correct OS type (Microsoft Windows) and version (Windows 7 64 Bit), and hit next.
    image
  3. Set the VM’s memory size. Microsoft says SharePoint foundation requires 4gb of RAM. In a bold decision that may come back to bite me later on, I’m going to give it 1gb.
    image
  4. Complete the remainder of the VM provisioning with the default options. You’ll end up with a 25gb virtual hard drive, but it’s dynamically sized so it won’t take up 25gb of your real-life hard drive.
  5. Your now back to the main VirtualBox window, and your virtual machine has been created – but is empty.  It’s time to install Windows 7. Right-click your new virtual machine at the left of the VirtualBox window, go to the storage tab, select the DVD drive and click the little disc icon on the far-right of the window to point the virtual drive to the Windows 7 install media. This could be a physical disc in your drive, or an ISO disc image.
    image
  6. Back at the main VirtualBox window, hit the start button up top. The virtual machine will open, and the windows install will begin. I’m not going to take you through all the install steps, but it’s no different to installing Windows 7 on a real computer. When you create a user you can call it whatever you want, but you must set a password.
    image

Installing prerequisites and configuring windows

image

Now that we have Windows 7 installed and running in our virtual machine, it’s time to install a few prerequisites before we dive into installing SharePoint itself.

If you’ve already downloaded SharePoint Foundation then you may have noticed it includes an option entitled Install Prerequisites. Bad news – this only works on Windows Server and not Windows 7 or Vista, so you have some work to do.

You’ll need to download and install:

Next, we need to set a few options in the operating system. Open up control panel and go to Turn Windows features on or off.

Here are the options we’re going to set:
image
image

Time to install SharePoint

Finally, we’re ready!

  1. If you haven’t done so already, download SharePoint Foundation 2010 from Microsoft’s website. Make sure you save the file rather than running it, because…
  2. …running it doesn’t work. As I noted, SharePoint is designed to be a server application available to large groups of people, and it requires Windows Server as a result. Except it doesn’t. Read on.
    image
  3. What we need to do is manually unpack the installation file, and change a setting before we can install.
    1. Move the downloaded file into a folder somewhere (on your desktop is fine), open a command prompt, and navigate to that folder.
    2. Type the following command, and extract the files from the archive into the same folder
      SharePoint_SP2_en-us /extract

      image

    3. The installation files are now extracted into the folder. Navigate to the FilesSetup folder. There’s a file in there called config.xml. Open this with a text editor (notepad is fine)
    4. Inside the <Configuration> tag, paste the following line:
      <Setting id=”AllowWindowsClientInstall” Value=”True” />

      Save and close the file, and navigate back to the root of the folder you created.

  4. Run setup.exe by double-clicking, and we’re pretty much good to go! When asked to choose the installation you want, make sure you select Standalone
    image

It may take a while, but if you’ve followed all the steps correctly, SharePoint Foundation 2010 will now install correctly. The final step of the installation is a configuration wizard. Don’t skip this step! Despite its name there are no options you need to select, but you do need to make sure that you run it. It will set everything up for you, and we’re done! When the configuration wizard is complete it will open the site automatically. You may need to log in with your windows username and password.

image