Wednesday, November 12, 2008

jQuery in SharePoint Example - Rounded Corners

A recent project involved the branding of MOSS to incorporate custom design elements as supplied in a PhotoShop page mockup. One of these design requirements was rounding the external corners of the quick launch menu.

Hmmm, what to do. There are plenty of techniques discussed on the web for achieving this outcome, but often the basis for these techniques is to start with clean, web-standards compliant HTML. That's certainly not what SharePoint provides - I needed to work with the HTML that is created by the mixture of master pages and user controls, and did not want to override standard elements for this styling exercise. One aim was to minimize the changes, if any, to the master page.

Many of the rounded corner approaches use JavaScript. And I was, at the time of this project, starting to see the potential of jQuery combined with SharePoint. So a little more research located a neat way forward - the jQuery.Round plug-in.

After a few minutes (hours?) experimentation I derived the jQuery statements to apply rounded corners to the menu. This of course also required adding references to the jQuery and jQuery.round libraries in the master page - so it was necessary after all to change that page!

The statements were:

function AddQuickLaunchCorners()
{
    $(".ms-quicklaunchouter").corner("10px");
    $("div.ms-quickLaunch h3.ms-standardheader span div.ms-quicklaunchheader").css("background-color", "#c1ecff").corner("top 7px");
    $("table.ms-recyclebin:last td").corner("bottom 7px");
}

Note the assumption in the last JavaScript statement that the recycle bin will be the bottom row in the quick launch menu.

These statements, together with modifications to some of the other CSS styles, resulted in the following look for the quick launch menu:




But then I came across a very annoying behaviour. Imagine the following scenario:

  • I view a page containing this menu in one tab in IE7
  • Then I open another tab in IE7 and navigate around any page in that second tab

Not an unusual behaviour really. But on returning to the first tab displaying the SharePoint page with menu, this is what the menu then looked like:


Yeuch! More "minutes" of investigation lead to the inclusion of the following code in the JavaScript file applying the dynamic styling to the page:

window.onfocus = ReapplyQuickLaunchCorners;

function ReapplyQuickLaunchCorners()
{
    RemoveQuickLaunchCorners();
    AddQuickLaunchCorners();
}

function RemoveQuickLaunchCorners()
{
    $("div.ms-quicklaunchouter>div:not(.ms-quickLaunch)").remove();
    $("div.ms-quickLaunch h3.ms-standardheader span div.ms-quicklaunchheader>div").remove();
    $("table.ms-recyclebin:last td>div").remove();
}

Not a nice solution (OK, it's a hack!) but it works and I ran out of time.

So where am I leading with this post - well, just to illustrate the great things you can do with jQuery to mould SharePoint. Sometime I'll blog about using jQuery for AJAX calls to the MOSS profile search web services, but that's for another time.....

Sunday, November 2, 2008

jQuery Introduction Talk at Christchurch Code Camp

Gave a 5 minute lightning talk on "A Brief Introduction to jQuery" at the Christchurch Code Camp on Saturday - didn't quite get to my last slide in the 5 minutes and Dave Mateer took great delight in "riffing" me off the stage with his electric guitar turned up loud!

Really like the lightning talk concept - you don't need to be an expert on the subject, and they are very easy to prepare for, given that you can run through the slides lots of times beforehand (though having said that, I obviously didn't practice enough to get my talk short enough!).

I have published the slide deck from my talk - it includes an overview of a couple of ways in which I recently solved SharePoint UI requirements using jQuery, including a way of adding rounded corners to the quicklaunch menu using the jQuery.Corner library.

Amongst the talks on the day were:

Just wanted to say well done to the small team of organisers who did a great job in a short time - those half million listeners of Dot Net Rocks who heard the announcement about the camp but who didn't attend missed out on a treat!

Monday, October 20, 2008

Revisiting ddwrt and FormatDate

I have had some feedback on the my posting in May 2007 about the ddwrt FormatDate function, including a request to see additional formats.

Therefore I had a play with some reflection code, and have created a little command line application that can be used to see the available date formats output by the ddwrt utility.

Note that this code could be used to experiment with the output of some of the other ddwrt functions in the Microsoft.SharePoint.WebPartPages.DdwRuntime library - to see a list of the other functions, open up the Microsoft.SharePoint dll in Reflector.

One other tip - a list of the LCID values is available in this post on my blog


using System;

using System.Collections.Generic;

using System.Globalization;

using System.Linq;

using System.Reflection;

using System.Text;

 

namespace DDWRT.FormatDate

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                CultureInfo ci = new CultureInfo(1031);

                Console.WriteLine(RunDDWRT("05-09-2007 11:00", ci));

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.ToString());

            }

            Console.ReadLine();

        }

 

        public static string RunDDWRT(string szDate, CultureInfo ci)

        {

            string fullName = "Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";

 

            StringBuilder sb = new StringBuilder();

 

            //Load the SharePoint Assembly

            Assembly assem = Assembly.Load(fullName);

 

            // Reference the DDWRT namespace

            Type type = assem.GetType("Microsoft.SharePoint.WebPartPages.DdwRuntime", true, true);

 

            //Find the sought method in DDWRT (the "FormatDateTime" method)

            MethodInfo methodInfo = null;

            MethodInfo[] methods = type.GetMethods();

            foreach (MethodInfo method in methods)

            {

                //Uncomment the next line to see a list of all the methods available in the ddwrt class

                //sb.AppendLine(string.Format("  {0}", method.Name));

 

                if (method.Name == "FormatDate")

                    methodInfo = method;

            }

 

            if (methodInfo != null)

            {

                object objectInstance = Activator.CreateInstance(type);

 

                sb.AppendLine("ddwrt.FormatDate Test");

                sb.AppendFormat("\r\n");

                sb.Append("Locale LCID:");

                sb.AppendFormat("\t");

                sb.Append(string.Format("{0} ({1})", ci.LCID.ToString(), ci.Name));

                sb.AppendFormat("\r\n");

                sb.Append("Date to format:");

                sb.AppendFormat("\t");

                sb.Append(szDate);

                sb.AppendFormat("\r\n");

                sb.AppendFormat("\r\n");

 

                sb.Append("FormatFlag");

                sb.AppendFormat("\t");

                sb.Append("Formatted Date");

                sb.AppendFormat("\r\n");

                sb.AppendFormat("\r\n");

                for (long formatFlag = 1; formatFlag < 16; formatFlag++)

                {

                    try

                    {

                        string formattedDateTime = (string)methodInfo.Invoke(objectInstance, new Object[] { szDate, ci.LCID, formatFlag });

                        sb.Append(formatFlag);

                        sb.AppendFormat("\t\t");

                        sb.Append(formattedDateTime);

                        sb.AppendFormat("\r\n");

                    }

                    catch

                    {

                        sb.Append(formatFlag);

                        sb.AppendFormat("\t\t");

                        sb.Append("--------");

                        sb.AppendFormat("\r\n");

                    }

                }

            }

            return sb.ToString();

        }

 

    }

}

Wednesday, October 1, 2008

Displaying the Raw Search Results

Here's a little tidbit I usually end up searching for when manipulating search results - so it must be time to link to it here:
How to: View Search Results XML Data
(Also see Customize the People Search Results)

This gives a rundown on the XSL to use to show the raw XML that is returned to a search results web part (such as the "CoreResultsWebPart").

Basically, use the following:
<xsl:stylesheet version="1.0" xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes">
<xsl:template match="/">
<xmp><xsl:copy-of select="*"></xmp>
</xsl:template>
</xsl:stylesheet>

Custom Web Part Pages Template Woes

Seems to have been plenty of people that have tried to extend the list Web Part Page templates made available on the spcf.aspx page. And it seems that the approach outlined in the Microsoft article "Creating Custom Web Part Page Templates for Microsoft SharePoint Products and Technologies" just doesn't work with SharePoint v3.

The approach of adding an additional option to the list of templates in a custom custspcf.aspx page seems to fail (with the "Invalid URL Parameter" message) for the following reason: according to the WSS SDK, the NewWebPage RPC method accepts a value for the WebPartPageTemplate of between 1 and 8.

That must explain why adding a ninth template to the list fails - the call to the NewWebPage method OWSSVR.DLL doesn't expect a number above 8. For the background, here is a discussion on OWSSVR by Joel Oleson.

So I guess the options if different Web Part Page templates are required are to either
  • Replace the standard ones that are located in 12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS, or to
  • Create a completely custom template selection page - but I am finding that there are some real oddities in the names of pages that appear in search results when web part pages are created in a custom manner.

Another area that needs attention in vNext!

Tuesday, August 5, 2008

Adding Default Content to a SharePoint Wiki

If you create a new Wiki through a list instance in a feature, through a site definition or programmatically, the default How To and Home page will not appear in that Wiki.

To add those page, the Microsoft.SharePoint.Utilities.SPUtility class offers the following public static method:

AddDefaultWikiContent(SPList wikiList)

Call this method to add those default pages. Or if you want more control over the content of the provisioned pages, use Reflector to disassemble the following DLL and have a look at the code in that method to see how it is done:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.SharePoint.dll

Another Way to Enrich Your SharePoint Forms - JQuery

I'm still enjoying that honeymoon period with a new tool in my SharePoint developer "bag of tricks" - JQuery. Such a powerful library!

As an example of its usefulness, in a recent project I needed to modify the behaviour of search scope checkboxes on an advanced search page in SharePoint (enforcing that the 'All Sites' checkbox is ticked if the user clears all other checkboxes).

Here's the steps I took using JavaScript plus JQuery:
1. Encapsulate the minified JQuery library in a SahrePoint feature in order to deploy across the farm.
2. Add a script tag referencing the JQuery JS file in the 'PlaceHolderTitleAreaClass' content placeholder of the search page.
3. Add a Content Editor Web Part to the search page, and open the source view for that web part.
4. Add the following JavaScript function to the content editor source (to enable custom JavaScript to be called on page load):

    1 function addLoadEvent(func){


    2     var oldonload = window.onload;


    3     if (typeof window.onload != 'function') {


    4         window.onload = func;


    5     } else {


    6         window.onload = function () {


    7             if (oldonload) {


    8                 oldonload();


    9             }


   10             func();


   11         }


   12     }


   13 }



5. Call a click handler processing function on page load with the following:
addLoadEvent(AddOnClickHandlers);

6. Add a function to assign onclick handlers to the targetted checkboxes. This is where the power of JQuery shines through - notice the short expression in line 5 that retrieves references to only the checkboxes I am seeking (these checkboxes are contained in table cells attributed with the class 'ms-advsrchText')

    1 //Add an onclick event handler for each of the checkboxes in the search form


    2 //(the checkboxes are identified by the 'ms-advsrchText' class applied to their containing table cells)


    3 function AddOnClickHandlers() {


    4   //Get the checkboxes in the form


    5   var chks = $('td.ms-advsrchText').find(':checkbox').get();


    6   for(var i=0;i<chks.length;i++)  {


    7     chks[i].onclick = SetFormState;


    8   }


    9 }



7. Write the onclick event handler - this needs to find the check box labelled "All Sites" and check its status. I have not included all the code, just a few lines showing more use of JQuery. Line 12 builds a selection expression to get the next sibling for each check box; the next sibling is a label whose text contains the scope name (e.g. "All Sites").

    1 function SetFormState() {


    2   //... OTHER CODE ...


    3 


    4   //Get the scope checkboxes in the search form


    5   var chks = $('td.ms-advsrchText').find(':checkbox').get();


    6 


    7   //Enumerate through the check boxes


    8   for(var i=0;i<chks.length;i++) {


    9 


   10     //Get the next sibling to the checkbox, which is a label element that contains the descriptive text.


   11     //This text is assumed to always be 'All Sites' for the main search scope


   12     var lbl = $('#' + chks[i].id + ' ~ label').get(0);


   13 


   14     //Save the reference to the All Sites checkbox


   15     if (lbl.innerText == 'All Sites') {




So, the actual code to get at the required elements on the page is very brief, and the range of JQuery selectors makes getting to the elements easy.

One tip - notice the use of the Get() method call at the end of the JQuery expressions. This returns DOM elements that can then be manipulated with normal DOM scripting.