Category Archives: SharePoint Development

Beware Breaking Changes to ItemStyle.xsl

I was working with ItemStyle.xsl to customize the look of a Content Query Web Part and right about lunch time, I made a breaking change to the xsl.  I didn’t realize it, but this had far reaching effects throughout the site collection.  I went off to lunch and upon my return, noticed this message appearing in a bunch of places:

Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Windows SharePoint Services-compatible HTML editor such as Microsoft Office SharePoint Designer. If the problem persists, contact your Web server administrator.

I blamed the client (not realizing as yet that it was my fault at this point) but eventually noticed that visual studio intellisense was warning me that I had malformed XSL.  I corrected it and everything started working.

Be darned careful when working with ItemStyle.xsl (and any of the global XSL files) — breaking them affects many artifacts in the site collection.

<end/>

Display Content Query Web Part Results in a Grid / Table

Overview and Objective

Out of the box, MOSS’ Content Query Web Part (CQWP) displays its results in a list format, similar to search results.  It is also possible to display the results in a grid format (i.e. HTML table format).  Grid formats are better in some circumstances.  I describe how to achieve that effect in this article.

Business Scenario

I have worked with a client on an enterprise-wide MOSS rollout.  We have designed their taxonomy such that projects are first class citizens in the hierarchy and have their own top level site.  Project managers maintain a singleton list of project summary information, such as title, budget, expected completion date, remaining budget and other summary type fields.  By "singleton" I mean a custom SharePoint list guaranteed to contain only one item.   Simplistically, it looks like this:

image

The technical approach is much the same as described here (http://paulgalvin.spaces.live.com/blog/cns!1CC1EDB3DAA9B8AA!447.entry).  The CQWP uses an XSL transform to emit HTML for the browser to render.

I always envision the result before diving into the XSL because XSL is a nightmare.  Here’s my desired result:

image

HTML like this generates that result:

 
<html>
 <body>
 <center>
 <table border=1>

<!-- Labels -->
 <tr bgcolor=blue>
 <td><font color=white><b>Project Name</b></font></td>
 <td align=right><font color=white><b>Complete Date</b></font></td>
 <td align=right><font color=white><b>Budget</b></font></td>
 <td align=right><font color=white><b>Actual Expense</b></font></td>
 <td><font color=white><b>Overall Status</b></font></td>
 </tr>

<tr>
 <td>Re-wire computer room.</td>
 <td align=right>02/01/08</td>
 <td align=right>22,500.00</td>
 <td align=right>19,000.00</td>
 <td>In Progress</td>
 </tr>

<tr>
 <td>Provision servers for SQL Upgrade</td>
 <td align=right>04/01/08</td>
 <td align=right>7,500.00</td>
 <td align=right>0.00</td>
 <td>Planned</td>
 </tr>

</table>
 </center>
 </body>
</html>

Approach

Follow these steps to create the grid:

  1. Identify the components of the grid (rows/columns).
  2. Define and create necessary site columns.
  3. Create sub sites for the projects and singleton lists.
  4. Add the CQWP to a web page and configure it to search for your lists.
  5. Modify the CQWP’s XML to gather up the additional columns.
  6. Modify the XSL to generate a table.

I’m going to concentrate on number six.  Numbers one through four are straight-forward and something that any CQWP user has already done.  Number five has been well-documented by others including this exhaustive screen-shot laden article from MSDN here (http://msdn2.microsoft.com/en-us/library/bb897399.aspx) and Heather Solomon’s blog here (http://www.heathersolomon.com/blog/articles/CustomItemStyle.aspx).

Nuts And Bolts

Begin and implement steps one through five as per the MSDN documentation and Heather Solomon’s article.

At this point, you’ve added your CQWP to the page and you have your <CommonViewFields> configured as necessary.

Following the usual steps, I get these intermediate results:

1. Create a content type, a templatized custom list for that content type and two sites.  Here is the content type:

image

Here is the site structure:

image

2. Add the CQWP after creating my project subsites and singleton project summary lists:

image

3. Add all the additional information I want via the <CommonViewFields>:

        <property name="CommonViewFields" type="string">Project_x0020_Name;Project_x0020_Expenses;Project_x0020_Status;Project_x0020_Start_x0020_Date;Project_x0020_End_x0020_Date;Project_x0020_Budget</property>

Note that I had to keep all the property fields on one line or it would not work (CQWP would tell me that the query returned no items).

4. At this point, we’re ready to move beyond the MSDN article and flip on over to Heather Solomon’s article.  Follow her steps starting near step #5 to create a customized / unghosted version of ItemStyle.xsl.  I follow Heather’s advice, up through step 11 and get these intermediate results:

4.1: Name my XSL template as follows:

<xsl:template name="Grid" match="Row[@Style=’Grid’]" mode="itemstyle">

I also slightly modify her suggested <xsl:for-each …> by adding a <br/> tag to provide a cleaner listing:

    <xsl:for-each select="@*">
      P:<xsl:value-of select="name()" /><br/>
    </xsl:for-each>

4.2: I modify the web part, go to appearance and select my "Grid" style:

image

Apply the change and here is the result:

image

We can see from the above that the fields we want (Project name, expense, status, etc) are available for us to use when we emit the HTML.  Not only that, but we see the names by which we must reference those columns in the XSL.  For example, we reference Project Status as "Project_x005F_x0020_Name".

At this point, we depart from Heather’s blog and from the shoulders of these giants, I add my own little bit.

ContentQueryMain.xsl

NOTE: When making changes to both ContentQueryMain.xsl as well as ItemStyle.xsl, you need to check those files back in before you see the effect of your changes.

For grid-making purposes, MOSS uses two different XSL files to produce the results we see from a CQWP.  To generate the previous bit of output, we modified ItemStyle.xsl.  MOSS actually uses another XSL file, ContentQueryMain.xsl to in conjunction with ItemStyle.xsl to generate its HTML.  As its name implies, ContentQueryMain.xsl is the "main" XSL that controls the overall flow of translation.  It iterates through all the found items and passes them one by one to templates in ItemStyle.xsl.  We’ll modify ItemStyle.xsl to generate the open <table> tag before emitting the first row of data and the closing <table> tag after emitting the last row.  To accomplish this, ContentQueryMain.xsl is modified to pass two parameters to our "grid" template in ItemStyle.xsl, "last row" and "current row".  ItemStyle.xsl uses these to conditionally emit the necessary tags.

Using Heather Solomon’s technique, we locate ContentQueryMain.xsl.  It is located in the same place as ItemStyle.xsl.  This screen shot should help:

image

We need to make the following changes:

  • Modify an xsl template, "CallItemTemplate" that actually invokes our Grid template in ItemStyle.xsl.  We will pass two parameters to the Grid template so that it will have the data it needs to conditionally generate opening and closing <table> tags.
  • Modify another bit of ContentQueryMain.xsl that calls the "CallItemTemplate" to pass it a "LastRow" parameter so that LastRow may be passed on to our Grid template.

Locate the template named "OuterTemplate.CallItemTemplate" identified by the string:

  <xsl:template name="OuterTemplate.CallItemTemplate">

Replace the whole template as follows:

 
  <xsl:template name="OuterTemplate.CallItemTemplate">
    <xsl:param name="CurPosition" />

    <!--
      Add the "LastRow" parameter.
      We only use it when the item style pass in is "Grid".
    -->
    <xsl:param name="LastRow" />

    <xsl:choose>
      <xsl:when test="@Style='NewsRollUpItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="EditMode" select="$cbq_iseditmode" />
        </xsl:apply-templates>
      </xsl:when>
      <xsl:when test="@Style='NewsBigItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
        </xsl:apply-templates>
      </xsl:when>
      <xsl:when test="@Style='NewsCategoryItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
        </xsl:apply-templates>
      </xsl:when>

      <!--
              Pass current position and lastrow to the Grid itemstyle.xsl template.
              ItemStyle.xsl will use that to emit the open and closing <table> tags.
      -->
      <xsl:when test="@Style='Grid'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
          <xsl:with-param name="Last" select="$LastRow" />
        </xsl:apply-templates>
      </xsl:when>

      <xsl:otherwise>
        <xsl:apply-templates select="." mode="itemstyle">
        </xsl:apply-templates>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

The comments describe the purpose of the changes.

Of course, the "OuterTemplate.CallItemTemplate" is itself called from another template.  Locate that template by searching for this text string:

<xsl:template name="OuterTemplate.Body">

Scroll through the instructions in OuterTemplate.Body and insert the LastRow parameter as follows (shown as a comment in italics):

<xsl:call-template name="OuterTemplate.CallItemTemplate">
  <xsl:with-param name="CurPosition" select="$CurPosition" />
  <!-- Insert the LastRow parameter. -->
  <xsl:with-param name="LastRow" select="$LastRow"/>
</xsl:call-template>

After all of this, we finally have things set up properly so that our ItemStyle.xsl can emit <table> tags at the right place.

ItemStyle.Xsl

NOTE: Again, check in ItemStyle.xsl after making any changes so that you see the effect of those changes.

We have two tasks here:

  • Replace the entire Grid template.  You can copy/paste from below.
  • Add some mumbo jumbo outside the template definition that enables "formatcurrency" template to work.  (You can tell that I have a tenuous handle on XSL).

First, near the top of ItemStyle.xsl, add this line:

  <!-- Some mumbo jumbo that enables us to display U.S. currency. -->
  <xsl:decimal-format name="staff" digit="D" />

  <xsl:template name="Default" match="*" mode="itemstyle">

Note that I added it directly before the <xsl:template name="Default" …> definition.

Next, go back to our Grid template.  Replace the entire Grid template with the code below.  It is thoroughly commented, but don’t hesitate to email me or leave comments on my blog if you have questions.

 
  <xsl:template name="Grid" match="Row[@Style='Grid']" mode="itemstyle">

    <!--
      ContentMain.xsl passes CurPos and Last.
      We use these to conditionally emit the open and closing <table> tags.
    -->
    <xsl:param name="CurPos" />
    <xsl:param name="Last" />

    <!-- The following variables are unmodified from the standard ItemStyle.xsl -->
    <xsl:variable name="SafeImageUrl">
      <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="SafeLinkUrl">
      <xsl:call-template name="OuterTemplate.GetSafeLink">
        <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="DisplayTitle">
      <xsl:call-template name="OuterTemplate.GetTitle">
        <xsl:with-param name="Title" select="@Title"/>
        <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="LinkTarget">
      <xsl:if test="@OpenInNewWindow = 'True'" >_blank</xsl:if>
    </xsl:variable>

    <!--
      Here we define a variable, "tableStart".  This contains the HTML
      that we use to define the opening of the table as well as the column
      labels.  Note that if CurPos = 1, it includes the HTML in a CDATA tag.
      Otherwise, it will be empty.

      The value of tableStart is emited every time ItemStyle is called via
      ContentQueryMain.xsl.
    -->
    <xsl:variable name="tableStart">
      <xsl:if test="$CurPos = 1">
        <![CDATA[
        <table border=1>
          <tr bgcolor="blue">
            <td><font color="white"><b>Project Name</b></font></td>
            <td align="right"><font color="white"><b>Complete Date</b></font></td>
            <td align="right"><font color="white"><b>Budget</b></font></td>
            <td align="right"><font color="white"><b>Actual Expense</b></font></td>
            <td><font color="white"><b>Overall Status</b></font></td>
          </tr>
        ]]>
      </xsl:if>
    </xsl:variable>

    <!--
      Another variable, tableEnd simply defines the closing table tag.

      As with tableStart, it's always emited.  This is why its value is
      assigned conditionally based upon whether we've been passed the last
      row by ContentQueryMain.xsl.
    -->
    <xsl:variable name="tableEnd">
      <xsl:if test="$CurPos = $Last">
        <![CDATA[ </table> ]]>
      </xsl:if>
    </xsl:variable>

    <!--
      Always emit the contents of tableStart.  If this is not the first
      row passed to us by ContentQueryMain.xsl, then we know its value
      will be blank.

      Disable output escaping because when tableStart it not blank, it
      includes actual HTML that we want to be rendered by the browser.  If
      we don't tell the XSL parser to disable output escaping, it will generate
      stuff like "&lt;table&gt;" instead of "<table>".
    -->
    <xsl:value-of select="$tableStart" disable-output-escaping="yes"/>


    <tr>
      <!--
      P:Project_x005F_x0020_Name
      P:Project_x005F_x0020_End_x005F_x0020_Date
      P:Project_x005F_x0020_Budget
      P:Project_x005F_x0020_Expenses
      P:Project_x005F_x0020_Status
      -->
      <td>
        <xsl:value-of select="@Project_x005F_x0020_Name"/>
      </td>

      <td align="right">
        <xsl:value-of select="@Project_x005F_x0020_End_x005F_x0020_Date"/>
      </td>

      <td align="right">
        <xsl:call-template name="formatcurrency">
          <xsl:with-param name="value" 
select="@Project_x005F_x0020_Budget"></xsl:with-param> </xsl:call-template> </td> <td align="right"> <xsl:call-template name="formatcurrency"> <xsl:with-param name="value" select="@Project_x005F_x0020_Expenses">
</xsl:with-param> </xsl:call-template> </td> <td> <xsl:value-of select="@Project_x005F_x0020_Status"/> </td> <!-- All of the following is commented out to clarify things. However, bring it back and stuff it into a <td> to see its effect. --> <!-- <div id="linkitem" class="item"> <xsl:if test="string-length($SafeImageUrl) != 0"> <div class="image-area-left"> <a href="{$SafeLinkUrl}" target="{$LinkTarget}"> <img class="image-fixed-width" src="{$SafeImageUrl}"
alt="{@ImageUrlAltText}"/> </a> </div> </xsl:if> <div class="link-item"> <xsl:call-template
name="OuterTemplate.CallPresenceStatusIconTemplate"/> <a href="{$SafeLinkUrl}"
target="{$LinkTarget}" title="{@LinkToolTip}"> <xsl:value-of select="$DisplayTitle"/> </a> <div class="description"> <xsl:value-of select="@Description" /> </div> </div> </div>
--> </tr> <!-- Emit the closing table tag. If we are not on the last row, this will be blank. --> <xsl:value-of select="$tableEnd" disable-output-escaping="yes"/> </xsl:template> <xsl:template name="formatcurrency"> <xsl:param name="value" select="0" /> <xsl:value-of select='format-number($value, "$DDD,DDD,DDD.DD", "staff")' /> </xsl:template>

Standard WSS/MOSS Data Entry Screens Do Not Support Cascading Drop-downs (or other intra-from communication)

 

UPDATE (04/2008): This great blog entry shows a good javascript based approach to this problem: http://webborg.blogspot.com/2008/04/add-functions-and-events-to-sharepoint.html

UPDATE II: (04/2008): This blog entry looks promising as well: http://www.cleverworkarounds.com/2008/03/13/free-mosswss-2007-web-part-hide-controls-via-javascript/

Several times a week, if not daily, forum users describe a requirement that would normally be met via cascading drop-downs.  For example, I have two drop-down controls:

  • List of U.S. states
  • List of U.S. cities.

As responsible UI providers, we want it to operate like this:

  • Paul selects a U.S. state from the drop-down. 
  • This causes the cities drop-down to filter only those cities that belong to the selected state. 
  • Paul selects a city from this filtered list.

There is no out-of-the-box support for this feature.  In fact, there is no OOB support for any kind of direct intra-form communication.  This includes programmatically hiding/enabling/disabling fields in response to field changes elsewhere on the form.

The real objective of this article to to describe possible solutions and these are the options as I know them:

  1. Develop a custom column type.  As a custom-column-developer, you have full control over the "world" of that custom column.  You can implement a cascading drop-down that way. 
  2. Consider using workflow.  In some cases, you want to automatically assign a value to field based on another field’s value.  In this case, you would normally try to use a calculated column, but some times, it just won’t get the job done.  SharePoint Designer workflow is a relatively administer-friendly alternative to dropping down into code and visual studio.  If you go this route, be aware of the issue addressed by this article (http://paulgalvin.spaces.live.com/blog/cns!CC1EDB3DAA9B8AA!405.entry).
  3. Event handlers: Like workflow, this is an after-the-fact solution.  Your event handler is a .NET assembly (C#, VB.NET) to which SharePoint passes control.  The object you develop has access to the data of the list (and the whole object model) and can do any needed calculation.
  4. Use SharePoint Designer to create custom entry forms.  I don’t have direct experience with this approach, but I hear they are doing good things with NewForm.aspx these days 🙂
  5. Roll your own ASP.NET data entry function (as a stand-alone web page or as a web part) and use that instead.

If anyone knows other and/or better options, please post a comment and I’ll update the body of this post.

<end/>

Technorati Tags:

Create Bar Graphs in SharePoint

Overview:

(UPDATE 12/04/07: Added another interesting resource at the end linking to another blog that addresses this via a very interesting web part)

This blog entry describes how to create a bar graph in SharePoint.  This works in both WSS and MOSS environments as it only depends upon the data view web part.

The overall approach is as follows:

  1. Create a list or document library that contains the data you want to graph.
  2. Place the associated document library / custom list onto a page and convert it to a data view web part (DVWP).
  3. Modify the DVWP’s XSL to generate HTML that shows as a graph.

Business Scenario / Setup:

I have created a custom list with the standard Title column and one additional column, "Status".  This models (very simplistically) an "Authorization For Expense" scenario where the title represents the project and the Status a value from the list of:

  • Proposed
  • In Process
  • Stalled

The objective is to produce an interactive horizontal bar graph that shows these status codes.

I have populated the list and it looks like this:

image

Create Data View Web Part:

Create the DVWP by adding the custom list to a page (site page in my case) and follow the instructions here (http://paulgalvin.spaces.live.com/blog/cns!1CC1EDB3DAA9B8AA!395.entry).

In addition to simply creating the DVWP, we also need to set the paging property to show all available rows.  For me, this looks something like this:

image

At this point, I always close SPD and the browser.  I then re-open the page using the browser.  This avoids accidentally mucking up the web part layout on the page.

Modify the XSLT:

It’s now time to modify the XSLT.

I always use visual studio for this.  (See here for an important note about intellisense that will help you a lot).

I create an empty project add four new files (replacing the words "Original" and "New" as appropriate):

  • Original.xslt
  • New.xslt
  • Original Params.xml
  • New Params.xml

In my case, it looks like this:

image

Modify the web part and copy the params and XSL to the "Original" version in Visual Studio.

The objective here is to cause the XSL to transform the results we get back from the DVWP query into HTML that renders as a graph.

To this end, it helps to first consider what the HTML should look like before we get confused by the insanity that is known as "XSL".  (To be clear, the following is simply an example; don’t type it or copy/paste into visual studio.  I provide a full blow starting point for that later in the write-up).  The following sample graph is rendered as per the HTML immediately following:

Sample Bar Graph

Corresponding HTML:

  <html>
  <body>
    <center>
    <table width=80%>
      <tr><td><center>Horizontal Bar Graph</td></tr>
      <tr>
        <td align="center">
          <table border="1" width=80%>
           <tr>
              <td width=10%>Open</td>
              <td><table cellpadding="0" cellspacing="0" border=0 width=50%><tr bgcolor=red><td>&nbsp;</td></tr></table></td>
            </tr>
            <tr>
              <td width=10%>Closed</td>
              <td><table cellpadding="0" cellspacing="0" border=0 width=25%><tr bgcolor=red><td>&nbsp;</td></tr></table></td>
            </tr>
            <tr>
              <td width=10%>Stalled</td>
              <td><table cellpadding="0" cellspacing="0" border=0 width=25%><tr bgcolor=red><td>&nbsp;</td></tr></table></td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>

I used a dead simple approach to creating my bars by setting the background color of a  row to "red". 

The take-away here is this: In the end, all we are doing is creating HTML with rows and columns.

Template XSLT:

I’ve copied the XSLT that generates a horizontal bar graph.  It’s fairly well commented so I won’t add much here except for these notes:

  • I started with the default XSL that SharePoint Designer gave me when I first created the DVWP.
  • I was able to cut this down from SPD’s 657 lines to 166 lines. 
  • I didn’t mess around with the parameters XML file (which is separate from the XSL and you’ll know what I mean when you go to modify the DVWP itself; there are two files you can modify).  However, in order to simplify it, I did remove nearly all of them from the XSL.  This means that if you want to make use of those parameters, you just need to add their variable definitions back to the XSL.  That will be easy since you will have the original XSL variable definitions in your visual studio project.
  • You ought to be able to copy and paste this directly into your visual studio project.  Then, remove my calls and insert your own calls to "ShowBar".
  • The drill down works by creating an <a href> like this: http://server/List?FilterField1=fieldname&FilterValue1=actualFilterValue.  This technique may be of value in other contexts.  At first, I thought I would need to conform to a more complex format: http://server/List/AllItems.aspx?View={guid}&FilterField1=blah&FilterValue1=blah, but in my environment that is not necessary.  The List’s URL is passed to us by SharePoint so this is quite easy to generalize.

Here it is:

 
<xsl:stylesheet version="1.0" exclude-result-prefixes="rs z o s ddwrt dt msxsl" 
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:o="urn:schemas-microsoft-com:office" xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"
xmlns:ddwrt2="urn:frontpage:internal"
> <xsl:output method="html" indent="no" /> <xsl:decimal-format NaN="" /> <xsl:param name="ListUrlDir"></xsl:param> <!-- I need this to support a drill-down. --> <xsl:template match="/" xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:__designer=http://schemas.microsoft.com/WebParts/v2/DataView/designer xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
> <xsl:variable name="dvt_StyleName">Table</xsl:variable> <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row" /> <xsl:variable name="dvt_RowCount" select="count($Rows)" /> <xsl:variable name="IsEmpty" select="$dvt_RowCount = 0" /> <xsl:variable name="dvt_IsEmpty" select="$dvt_RowCount = 0" /> <xsl:choose> <xsl:when test="$dvt_IsEmpty"> There is no data to graph!<br/> </xsl:when> <xsl:otherwise> <!-- The interesting stuff begins here. We need to define a pair of variables for each row in the graph: total number of items and percent of total. --> <xsl:variable name="totalProposed" select="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'Proposed'])" /> <xsl:variable name="percentProposed" select="$totalProposed div $dvt_RowCount" /> <xsl:variable name="totalInProcess" select="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'In Process'])" /> <xsl:variable name="percentInProcess" select="$totalInProcess div $dvt_RowCount" /> <xsl:variable name="totalStalled" select="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'Stalled'])" /> <xsl:variable name="percentStalled" select="$totalStalled div $dvt_RowCount" /> <!-- We define our HTML table here. I'm borrowing from some standard SharePoint styles here to make it consistent. I think it will honor changes to the global css file as well as theme overrides. --> <table width="100%" cellspacing="0" cellpadding="2" style="border-right: 1 solid #C0C0C0; border-bottom: 1 solid #C0C0C0; border-left-style: solid; border-left-width: 1; border-top-style: solid; border-top-width: 1;"> <tr> <td align="center"> <table border="1" width="100%"> <!-- For each status that we want to graph, we call the "ShowBar" template. We pass it: 1. A label for the row. This is transformed into a hyperlink. 2. The percent (variable from above). 3. The actual field name of the code from the underlying list. This does not need to match the display label. 4. Field value matched for #3. 5. Total items of this status code (not the grand total of all status codes). It emits a <tr></tr> and the horizontal bar graph line. We call this template for each status code we want to view. --> <xsl:call-template name="ShowBar"> <xsl:with-param name="BarDisplayLabel" select="'Proposed'"/> <xsl:with-param name="BarPercent" select="$percentProposed"/> <xsl:with-param name="QueryFilterFieldName" select="'Status'"/> <xsl:with-param name="QueryFilterFieldValue" select="'Proposed'"/> <xsl:with-param name="TotalItems" select="$totalProposed"></xsl:with-param> </xsl:call-template> <xsl:call-template name="ShowBar"> <xsl:with-param name="BarDisplayLabel" select="'Stalled'"/> <xsl:with-param name="BarPercent" select="$percentStalled"/> <xsl:with-param name="QueryFilterFieldName" select="'Status'"/> <xsl:with-param name="QueryFilterFieldValue" select="'Stalled'"/> <xsl:with-param name="TotalItems" select="$totalStalled"></xsl:with-param> </xsl:call-template> <xsl:call-template name="ShowBar"> <xsl:with-param name="BarDisplayLabel" select="'In Process'"/> <xsl:with-param name="BarPercent" select="$percentInProcess"/> <xsl:with-param name="QueryFilterFieldName" select="'Status'"/> <xsl:with-param name="QueryFilterFieldValue" select="'In Process'"/> <xsl:with-param name="TotalItems" select="$totalInProcess"></xsl:with-param> </xsl:call-template> </table> </td> </tr> </table> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- This template does the work of displaying individual lines in the bar graph. You'll probably do most of your tweaking here. --> <xsl:template name="ShowBar"> <xsl:param name="BarDisplayLabel" /> <!-- label to show --> <xsl:param name="BarPercent"/> <!-- Percent of total. --> <xsl:param name="QueryFilterFieldName"/> <!-- Used to jump to the query & filter --> <xsl:param name="QueryFilterFieldValue"/> <!-- Used to jump to the query & filter --> <xsl:param name="TotalItems" /> <!-- total count of this barlabel --> <tr> <!-- The bar label itself. --> <td class="ms-formbody" width="30%"> <!-- This next set of statements builds a query string that allows us to drill down to a filtered view of the underlying data. We make use of a few things here: 1. We can pass FilterField1 and FilterValue1 to a list to filter on a column. 2. SharePoint is passing a key parameter to us, ListUrlDir that points to the underlying list against which this DVWP is "running". Isn't XSL fun? --> <xsl:text disable-output-escaping="yes"> <![CDATA[<a href="]]></xsl:text> <xsl:value-of select="$ListUrlDir"/> <xsl:text disable-output-escaping="yes"><![CDATA[?FilterField1=]]></xsl:text> <xsl:value-of select="$QueryFilterFieldName"/> <xsl:text disable-output-escaping="yes"><![CDATA[&FilterValue1=]]></xsl:text> <xsl:value-of select="$QueryFilterFieldValue"/> <xsl:text disable-output-escaping="yes"><![CDATA[">]]></xsl:text> <xsl:value-of select="$BarDisplayLabel"/> <xsl:text disable-output-escaping="yes"><![CDATA[</a>]]></xsl:text> <!-- The next bit shows some numbers in the format: "(total / % of total)" --> (<xsl:value-of select="$TotalItems"/> / <!-- This creates a nice percent label for us. Thanks, Microsoft! --> <xsl:call-template name="percentformat"> <xsl:with-param name="percent" select="$BarPercent"/> </xsl:call-template>) </td> <!-- Finally, emit a <td> tag for the bar itself.--> <td> <table cellpadding="0" cellspacing="0" border="0" width="{round($BarPercent*100)+1}%"> <tr bgcolor="red"> <xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text> </tr> </table> </td> </tr> </xsl:template> <!-- This is taken directly from some XSL I found in an MS template. --> <xsl:template name="percentformat"> <xsl:param name="percent"/> <xsl:choose> <xsl:when test="format-number($percent, '#,##0%;-#,##0%')= 'NaN'">0%</xsl:when> <xsl:otherwise> <xsl:value-of select="format-number($percent, '#,##0%;-#,##0%')" /> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet>

The Results:

The XSL from above generates this graph:

image

Drill down to the underlying data by clicking on the status code:

image

Concluding Thoughts:

Can This Be Generalized?

I love this graphing concept, but I hate the fact that I have to go in and do so much hand-coding.  I’ve given a little thought to whether it can be generalized and I’m optimistic, but I’m also a little fearful that there may be a brick wall somewhere along the path that won’t offer any work-around.  If anyone has some good ideas on this, please make a note in the comments or email me.

Vertical Graphs:

This is a horizontal bar graph.  It’s certainly possible to create a vertical graph.  We just need to change the HTML.  I would start the same way: Create an HTML representation of a vertical bar graph and then figure out how to get that via XSL.  If anyone is interested in that, I could be persuaded to try it out and work out the kinks.  If someone has already done that, please let me know and I’ll gladly link to your blog 🙂

I think that challenge with a vertical graph is that the labels for the graph are more difficult to manage, but certainly not impossible.

Field Name Gotcha’s:

There are at least two things to look out for with your field names.

First, a field name with a space has to be escaped in the XSL.  This will probably be an issue here:

        <xsl:variable name="totalProposed" 
select="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'Proposed'])" />

If your "Status" column is actually named "Status Code" then you need to reference it as "Status_x0020_Code":

   <xsl:variable name="totalProposed" 
select="count(/dsQueryResponse/Rows/Row[normalize-space(@Status_x0020_Code) = 'Proposed'])" />

Second, and I’m a little fuzzy on this, but you also need to be on the alert for field name changes.  If you name your field "Status Code" and then later on, rename it to "AFE Status", the "internal name" does not change.  The internal name will still be "Status Code" and must be referenced as "Status_x0020_Code".   The "other resources" links may help diagnose and correct this kind of problem.

About that Color:

I picked "red" because it’s pleasing to me at the moment.  It would not be a big deal to show different colors so as to provide more than just a visual description of a number, but to also provide a useful KPI.  For example, if the percentage of "stalled" AFE’s is > 10% then show it red, otherwise show it in black.  Use <xsl:choose> to accomplish this.

Other Resources:

Happy transforming!

<end/>

 Subscribe to my blog!

Present OM Data Via a Custom List (or, Yet Another OM Data Displayor [like YACC, but different])

Today, I spent a handful of hours tracking down the root cause behind the message "The column name that you entered is already in use or reserved.  Choose another name."

The column in question could be created, deleted and re-created in another environment, so I knew it wasn’t a reserved name.  However, I simply couldn’t find the column anywhere via the standard SharePoint user interface at any site in the site collection.

I posted to MSDN forums here and the indomitable Andrew Woodward pointed me in the direction of the underlying object model data.

I went off to codeplex to find some tools that would help me peer into the underlying OM data and help me locate the trouble.

I tried several tools and they were very cool and interesting but in the end, the UI wasn’t good enough for my purpose.  I’m not criticizing them by any means, but clearly the tool-makers didn’t have my problem in mind when they created their UI :).  Most people seem to be investing a fair amount of time and effort in creating workstation / client applications that provide tree views, right-click context menus and so forth.  These are nice and all, but it’s a lot of work to create a top-of-the-line user experience that is also very flexible.

I really needed an answer to this problem. It occurred to me that if I could get all of the site columns in the site collection into a custom list, I could filter, sort and create views that would help me find this supposedly existing column (which it did, BTW).  I went ahead and did that and an hour or two later, had all my site columns loaded into a custom list with grouping, sorting and so forth.  I found my answer five minutes later.

If and when I successfully take over the world, I think I will decree that all SharePoint tools providers must seriously consider surfacing their object model data in a custom list.  That way, I have the power to search any way I want (constrained, of course, by standard sharepoint features).