Contents tagged with Scripting

  • Working with URLs in SharePoint 2010 JavaScripts

    Tags: Scripting, SharePoint 2010

    The SharePoint 2010 user interface relies heavily on JavaScripts, just take a look at the Ribbon which is completely generated by a bunch of JavaScripts. Often customizations of SharePoint also involve JavaScripts. You need it to open modal dialogs, add notifications, create Ribbon Page Components etc. etc.. JavaScript is just one of the programming languages you must know as a SharePoint developer - and you can do amazing stuff with it (just take a look at SPServices by Marc D Anderson).

    SharePoint 2010 JavaScript awesomeness

    In SharePoint 2010 the SharePoint product team (finally) spent some time making a nice and decent JavaScript API (not just the ECMAScript Client Object Model stuff). This API contains quite a few nuggets and gems that can be used to simplify the SharePoint JavaScript tasks. Unfortunately they are not well documented if at all, but fortunately they have me to do it for them. In this post I will show you some good scenarios where you can take advantage of using the SharePoint 2010 JavaScript API.

    Application Page links

    Many SharePoint solutions contains application pages (aka layout pages) that are used for different administrative tasks. A good approach is to open these application pages using the Modal Dialog Framework. To redirect the user to an application page using JavaScript or open a Modal Dialog box with an application page, you need to construct the URL in JavaScript. This is often done using string concatenation using the current site URL and application page URL - but here's a better way:

    You can use the SP.Utilities.Utility.getLayoutsPageUrl(pageName) method to get the correct URL to the application page. For instance like this.

    var layoutsUrl = SP.Utilities.Utility.getLayoutsPageUrl('DemoPage.aspx');
    var options = {
      title: "My Dialog",
      url: layoutsUrl

    Using this method you will always get the correct application page URL to your page in the correct site. If you are using localized versions of the application page there is a localized equivalent of the method called SP.Utilities.Utility.getLocalizedLayoutsPageUrl(pageName) to use.

    Concatenating URLs

    Once you have the link to your application page you most often need to send parameters to it, such as the current list id or the item id. That's when you start concatenating strings again. Not that difficult, but you need to take care of encoding of the values.

    To build URLs you can use the SP.Utilities.UrlBuilder JavaScript object. This object contains quite a few useful methods. First of all it contains three"static" methods:

    • url = SP.Utilities.UrlBuilder.replaceOrAddQueryString(url, key, value): This method takes a URL as input and a query string key-value pair. It either appends the query string key-value pair or replaces the value of an existing key. It returns the modified URL as a string
    • url = SP.Utilities.UrlBuilder.removeQueryString(url, key): This method removes a query string key and value pair from a URL and returns the modified string.
    • url = SP.Utilities.UrlBuilder.urlCombine(url1, url2): Combines the two URLs, making sure that there are no redundant slashes when merging them.

    You can also use the UrlBuilder as an object. Take a look at this sample:

       1:  var layoutsUrl = SP.Utilities.Utility.getLayoutsPageUrl('DemoPage.aspx');
       2:  var urlBuilder = new SP.Utilities.UrlBuilder(layoutsUrl);
       3:  var listId = new SP.Guid(SP.ListOperation.Selection.getSelectedList());
       4:  urlBuilder.addKeyValueQueryString('list', listId.toString('B'));                
       5:  var options = {
       6:      title: "My Dialog",
       7:      url: urlBuilder.get_url()
       8:  }
       9:  SP.UI.ModalDialog.showModalDialog(options);

    It's the same sample as before but this time we add a parameter to the dialog URL with the currently selected List ID. On line 2) a UrlBuilder object is created from the application page URL. In line 3) I use another SharePoint JavaScript object called SP.Guid, which is very similar to the .NET System.Guid object, to store the currently selected list ID. The list ID is then added to the UrlBuilder object using the addKeyValueQueryString() method, on line 4). This method makes sure that both the key and value are correctly URL encoded. Finally in line 7) the URL is retrieved from the UrlBuilder object.

    Note: You must encode Guids when they are formatted with curly brackets. Curly brackets are according the the specification of URLs not allowed. If you're only been developing for IE previously that's not a problem, since IE can handle it anyways But better be safe than sorry...

    The UrlBuilder contains the following methods and properties:

    • combinePath(path): appends a path to the UrlBuilder path
    • addKeyValueQueryString(key, value): adds a key-value query string pair to the Url and correctly encodes the key and value
    • get_url() or toString(): returns the URL as a string

    With these tools in your hands you should be able to produce safe and correct URLs at all time when building JavaScripts for SharePoint 2010.

  • Minifying custom JavaScript files in SharePoint 2010

    Tags: Visual Studio, Scripting, AJAX, SharePoint 2010

    As you know the usage of JavaScript has been more and more used in web applications over the past years for technologies such as AJAX. JavaScript can accomplish really cool stuff on the client side and make the user interface more interactive and responsive. Just take a look at SharePoint 2010 - that's some heavy JavaScripts there (a bit to heavy IMHO).

    So lets assume that you are building some new cool stuff, in SharePoint of course, and why not a Page Component for a contextual Web Part. That's a lot of JavaScript (apart from the server side XML chunks)! So now you are making your web page payload even heavier. This is when minifying comes in. Minifying is a way to minimize the payload of a resource such as removing unnecessary comments and whitespace, shortening function and variable names etc - all to make the payload as small as possible. The only problem with these minified scripts are that they are virtually impossible to debug (and believe me if you are building a Page Component for SharePoint - you need to debug).

    If you have noticed SharePoint 2010 supports production and debug JavaScripts side-by-side. When you are debugging your SharePoint site you will see that all JavaScript files have a name like SP.debug.js, SP.Ribbon.debug.js etc. These are files that you actually can debug (even though they are obfuscated somewhat). All this is thanks to the SharePoint ScriptLink control which loads the production or debug version depending on if you are debugging or not.

    To use minified JavaScrips (or CSS files) in your SharePoint 2010 solutions you can do it easy with the Microsoft Ajax Minifier 4.0 and a pre-build event in Visual Studio 2010. Just follow these simple steps when you have installed the Minifier.

    Layouts folderCreate a new SharePoint 2010 project (farm solution - ScriptLink is not supported in the Sandbox)and then add the Layouts SharePoint Mapped folder to the project. Add two empty JavaScript files to the folder that is created. One with the .js extension and one ending with debug.js.

    Add some smart JavaScript code to the debug.js file - this is the file that you will edit from now on. The .js file will automatically be updated with the minified code. Then head on over to Project Properties and the Build Events tab. In the pre-build event enter the following:

    "C:\Program Files (x86)\Microsoft\Microsoft Ajax Minifier 4\ajaxmin.exe" 
        -JS $(ProjectDir)\Layouts\Wictor.Minified\TheScript.debug.js 
        -out $(ProjectDir)\Layouts\Wictor.Minified\TheScript.js  

    This will before building the project invoke the Ajax Minifier and create/update the minified JavaScript file. The -CLOBBER option allows the minifier to overwrite existing files. Replace the file name and folder with your file name and folder.

    Then add a Visual Web Part to your project and add code as follows:

    <SharePoint:ScriptLink runat="server" Name="Wictor.Minified/TheScript.js" Localizable="false"/>
    <asp:Button runat="server" Text="Click me!" OnClientClick="thisIsMyFunction('Hello mini!');" />

    The ScriptLink control will load the correct version of the script. Notice that you do not specify the debug version. Also Localizable is set to false here, since this is not a localized JavaScript (the Ajax Minifier actually supports localization of your JavaScripts - cool huh).

    Make sure that your SharePoint web application does not have debugging configured in the web.config and hit Ctrl-F5. This will start Internet Explorer and you can add the Web Part to a page. Then take a look at the source and look for your script. It should look something like this.

    Uses minified JavaScript file Then you go back to Visual Studio and compare the two JavaScript files. In my case it looks like this:

    Visual Studio 2010 comparing JavaScript files

    The debug JavaScript is 380 characters and the minified is only 147!

    Then hit F5 to run the project in debug mode and inspect the source of the page. You can now see that the debug version is loaded.

    And now in debug mode...

    That's it! Simple! Now go on minifying!

  • Internet Explorer 8 Beta 1 vs Firefox 3 Beta 4 JavaScript Performance

    Tags: Internet Explorer, Scripting

    Mozilla Links has an article about the Firefox ultimate feature - Performance, in which they compare the JavaScript performance on different web browsers. Firefox 3 beta 4 as some really impressive JavaScript performance and outruns Internet Explorer 7 with about 700%.

    But the article did not test Internet Explorer 8 beta, which I think should have been there (at least for reference). Since the IE8 team claims the performance is so much better, and my feeling after a few days of IE8 usage says so I had to do some testing on my own.

    I used the same JavaScript benchmarking tool that was used in the article - SunSpider JavaScript Benchmark.

    The results was not as I expected - yes, I did expect IE8 to perform better!

    IE8b1 vs FF3b4 JS performance

    The results show that Firefox 3 beta 4 performs 2-3 (or more) times better than Internet Explorer 8. It's an improvement since IE7, but not as good as I was expecting.

    Now we have to consider that this is the first beta of IE8 and its beta 4 of Firefox 3, which means that we will see some changes in this test in the near future. Just look at the graph in the article and see the improvement from FF3 beta 3 to beta 4, about 200%.

    Worth to notice is also that the script running times with IE8 was steadily increasing!

    Another interesting thing is that Internet Explorer 8 had a test deviation of about 60-70% while Firefox 3 had about 20%.

    I did the test on my Windows Vista Ultimate SP1 machine and run the tests on clean browsers one test at a time and then switched browsers.

    I think it is great that the two major browsers get heavily improved JavaScript performance in their upcoming versions, especially Internet Explorer which really sucked on this point.

    On the other side, I consider myself an optimization nerd sometimes and really like to do high- and well-performing JavaScript coding. This will not be that visible anymore :-(

  • Install script for the SharePoint Application Templates

    Tags: SharePoint, Scripting

    The Application Templates for Windows SharePoint Services 3.0, also known as the Fab40, is a set of forty different templates that can be used within a SharePoint environment.

    These templates are good to use as a starter when creating new SharePoint sites or custom solutions and I recommend that you install them into your test or development environment. But the download contains 40 different .wsp and .stp files which has to be installed one at a time; either using STSADM or using the web interface.

    Why not using a script?

    And here is one...

       1:  @SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm"
       3:  for %%f in (*.wsp) do %STSADM% -o addsolution -filename %%f
       5:  for %%f in (*.wsp) do %STSADM% -o deploysolution -allowgacdeployment -immediate -name %%f
       7:  for %%f in (*.stp) do %STSADM% -o addtemplate -filename %%f -title %%f
       9:  pause
      11:  IISRESET

    Just create a .bat (or .cmd) file and copy the text from above and save the file.

    Open up a command prompt and run the file and wait for the script to finish.



  • A Cheat sheet of Cheat sheets

    Tags: .NET, C#, SharePoint, Visual Studio, Microsoft Office, Scripting, AJAX

    Here is a list of cheat sheets for the Windows and .NET platform that I frequently use and I think are of great interest.

    Visual Studio 2005 Keyboard Shortcut References

    SharePoint and Office stuff

    Web and ASP.NET stuff

    Other stuff

  • Snap Preview Anywhere updated

    Tags: Internet and the Web, Scripting, Website

    The Snap Preview Anywhere (SPA), as I earlier removed from this site, has been updated with some new functionality to make it better for site owners who don't want their homepages cluttered with previews or users that do not want to see the previews.

    As a site owner you can now put up an option for your users to turn on or off the SPA:

    SPA Options

    And there is also an option to have the preview to trigger on an icon instead of the whole link:

    One step forward, and I really like that the SPA team has listened to the community. Maybe the SPA will be back on my site in the future...

  • ASP.NET AJAX 1.0 Released

    Tags: .NET, XML, Scripting, AJAX

    AJAX or AJAX? Finally ASP.NET AJAX 1.0, known as Atlas, is released in a fully supported version. The Download is available at

    Here's a summary from Scott's blog:

    The ASP.NET AJAX 1.0, which is available for free with full Microsoft support, can be extended with the ASP.NET AJAX Control Toolkit - a set of more than 30 controls for ASP.NET.

    Microsoft also releases the client-side ASP.NET AJAX JavaScript library under the Microsoft Permissive License (Ms-PL) which allows you to modify the library and the server-side code is released under Microsoft Reference License (Ms-RL) so your debugging will be easier.

  • JSON vs XML - final debate?

    Tags: XML, Scripting, AJAX

    We have been doing a lot of work, on our product, with dynamic updates of web pages - you know the AJAX stuff. Most of the server side results are returned as XML and are delivered from different Web Services. Since I really like optimizations and like good and nice looking code I have been going back and forth in decision of how to return data to the client; XML or JSON. JSON are in some cases more effective but when the object model it tries to represent gets more complex you neither get nice looking code nor saves that much bytes.

    Don Box led me to an interesting article which really shows this. This is exactly why I am using XML instead of the JSON notation.

  • New beta of IE Developer Toolbar

    Tags: Internet Explorer, Scripting

    The IEBlog announced that the IE Developer Toolbar Beta 3 is available now.

    Toolbar icon It contains some nice updates such as new interface with an icon in the command bar for easy access to the DOM Explorer and finally a great HTML source viewer.

    Time will also tell if the R-character hijack bug is still left, I have not noticed it yet...

    Note: You have to uninstall previous betas of the IE Developer Toolbar, otherwise you will have some nice crashes of Internet Explorer when trying to access the toolbar.

  • JavaScript closures

    Tags: Scripting, AJAX

    Ever wondered what JavaScript closures are? Morris Johns has put togehter a nice introduction to the mysterious closures - JavaScript closures for dummies. Make sure to read it before you do any more JavaScripting.

    Understanding JavaScript closures will make your JS programming more efficient and you can avoid the dreaded memory leaks in Internet Explorer especially when making home brewed Ajax applications. And of course learning this stuff is fun for us developers...

About Wictor...

Wictor Wilén is the Nordic Digital Workplace Lead working at Avanade. Wictor has achieved the Microsoft Certified Architect (MCA) - SharePoint 2010, Microsoft Certified Solutions Master (MCSM) - SharePoint  and Microsoft Certified Master (MCM) - SharePoint 2010 certifications. He has also been awarded Microsoft Most Valuable Professional (MVP) for seven consecutive years.

And a word from our sponsors...