Blog

Do Not Trigger Real Event Names with jQuery!

I post this link because I was writing some code earlier in the week and I was about to do exactly what this article tells us all not to do. Then I happened upon David Walsh’s article here and it actually led me to an even better solution than the one he suggests.

Until I read this I had no idea you could define your own custom events in jQuery and then trigger them later, but the winning solution is actually proposed by somebody in the comments section on David’s site: you can namespace your custom-named events. So:

$('#element').on('click.tabs', function() {
   ....
}

gets triggered when the element is actually clicked, or can be triggered programmatically with

$('#element').trigger('click.tabs');

the beauty here is that no other click events assigned to that element or its parents get triggered – we’re specifically targeting the namespaced event. If you’ve accidentally defined two .click() handling functions, or if there’s a .click() function on the parent element, the programmatic trigger doesn’t flow through to them.

Here’s a demo of what I’m talking about. Check out the difference between the three “trigger” links.

Do Not Trigger Real Event Names with jQuery!

Blog

SPServices addAttachment jQuery Example

Update: I’ve posted some example code that works in Internet Explorer 9!

If you’re having a few issues adding attachments via ajax and SPServices on SharePoint have a look over the code snippets below.

To upload a file to a list you need to make use of the fileReader javascript class, using the readAsDataURL method and stripping the first part off the dataurl to get the base64 component. Then submit this to SPServices.

I’ve been asked a few times to add the ability to upload attachments to SharePoint tools that I’ve created, and I’ve never been able to achieve it until I eventually came across this blog post last week.

If (like me) you’re developing in a front-end only way without any server-side programming then it seems like this is the way to upload files and attach them to SharePoint list items.

It relies on the javascript fileReader feature so your users will need a fairly modern browser… which is where I ran into trouble. The default browser deployed within my company is Internet Explorer 9, and that doesn’t have fileReader support.

With much work and even more googling I was able to get this technique to work in Internet Explorer 9. In the future I’ll write more about how I managed it, and how you can too!

SPServices addAttachment jQuery Example

Blog

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.

Blog

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!

Blog

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!

Blog

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  Â