Arquivo da Categoría: Desenvolvemento SharePoint

Coidado con alteracións feitas a ItemStyle.xsl

Eu estaba a traballar con ItemStyle.xsl para personalizar a aparencia dunha web Part de Contido da consulta e da dereita sobre a hora do xantar, 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, notou esta mensaxe aparecer unha chea de lugares:

Non é posíbel mostrar este web Part. Para corrixilo, abrir esta páxina web nun editor de Windows SharePoint Services compatible con HTML, como Microsoft Office SharePoint Deseño. Se o problema persiste, contacte co administrador do servidor web.

Eu culpaba ao cliente (non entendendo aínda que a culpa era miña, neste punto) but eventually noticed that visual studio intellisense was warning me that I had malformed XSL. I corrected it and everything started working.

Sexa enervante coidado ao traballar con ItemStyle.xsl (e calquera dos arquivos globais XSL) — rompe-los afecta moitos artefactos no conxunto de sitios.

</ Comezo>

Dar a coñecer o contido da consulta Resultados web Part nunha reixa / Táboa

Descricións e Obxectivo

Fóra da caixa, Moss’ Content Query web Part (CQWP) exhibe os seus resultados nun formato de lista, similar to search results. It is also possible to display the results in a grid format (i.e. HTML formato de táboa). Grid formats are better in some circumstances. I describe how to achieve that effect in this article.

Escenario empresarial

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, como título, orzamento, data de conclusión prevista, remaining budget and other summary type fields. By "singleton" I mean a custom SharePoint list guaranteed to contain only one item. Simplistically, parece que esta:

imaxe

O enfoque técnico é do mesmo xeito como se describe aquí (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:

imaxe

HTML como este que xera resultado:

<html>
 <corpo>
 <centro>
 <mesa fronteira= 1>

<!-- Etiquetas ->
 <tr bgcolor= Blue>
 <td><fonte cor= Branco><b>Nome do Proxecto</b></fonte></td>
 <td aliñar= Right><fonte cor= Branco><b>Data completar</b></fonte></td>
 <td aliñar= Right><fonte cor= Branco><b>Orzamento</b></fonte></td>
 <td aliñar= Right><fonte cor= Branco><b>Gasto real</b></fonte></td>
 <td><fonte cor= Branco><b>Estado xeral</b></fonte></td>
 </tr>

<tr>
 <td>Sala de informática Re-wire.</td>
 <td aliñar= Right>02/01/08</td>
 <td aliñar= Right>22,500.00</td>
 <td aliñar= Right>19,000.00</td>
 <td>En marcha</td>
 </tr>

<tr>
 <td>Provisionar servidores SQL para actualización</td>
 <td aliñar= Right>04/01/08</td>
 <td aliñar= Right>7,500.00</td>
 <td aliñar= Right>0.00</td>
 <td>Planeado</td>
 </tr>

</mesa>
 </centro>
 </corpo>
</html>

Aproximación

Siga estes pasos para crear a reixa:

  1. Identificar os compoñentes da reixa (liñas / columnas).
  2. Definir e crear columnas de sitio necesarias.
  3. Crear sitios sub para os proxectos e listas únicas.
  4. Engadir o CQWP a unha páxina web e configuralo para buscar as súas listas.
  5. Modificar XML do CQWP para recoller as columnas adicionais.
  6. Editar o XSL para xerar unha táboa.

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 aquí (http://msdn2.microsoft.com/en-us/library/bb897399.aspx) e blog de Heather Solomon aquí (http://www.heathersolomon.com/blog/articles/CustomItemStyle.aspx).

Porcas e parafusos

Comezar e aplicar medidas de un a cinco anos segundo a documentación do MSDN e artigo de Heather Solomon.

Neste punto, engadiu o CQWP á páxina e ten a súa <CommonViewFields> configurar que corresponda.

Seguindo os pasos habituais, Eu recibín estes resultados intermedios:

1. Crear un tipo de contido, a templatized custom list for that content type and two sites. Here is the content type:

imaxe

Aquí está a estrutura do sitio:

imaxe

2. Engadir o CQWP despois de crear os meus subsites proxecto e únicas proxecto listas sumarias:

imaxe

3. Fai toda a información adicional que quero vía <CommonViewFields>:

        <propiedade nome="CommonViewFields" tipo="corda">Project_x0020_Name;Project_x0020_Expenses;Project_x0020_Status;Project_x0020_Start_x0020_Date;Project_x0020_End_x0020_Date;Project_x0020_Budget</propiedade>

Nótese que eu tiña que manter todos os campos de propiedade nunha liña ou que non ía funcionar (CQWP iría me dicir que a consulta non devolveu elementos).

4. Neste punto, 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 para crear un personalizado / unghosted version of ItemStyle.xsl. I follow Heather’s advice, ata a etapa 11 e obter eses resultados intermedios:

4.1: O nome do meu template XSL como segue:

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

I tamén modificar lixeiramente a súa suxerido <XSL:a-cada …> pola adición dun <br /> etiqueta para fornecer unha listaxe máis limpo:

    <XSL:a-cada seleccionar="@ *">
      P:<XSL:valor de seleccionar="nome()" /><br/>
    </XSL:a-cada>

4.2: Eu modificar a parte web, go to appearance and select my "Grid" estilo:

imaxe

Aplicar o cambio e aquí está o resultado:

imaxe

Podemos ver enriba que os campos que queremos (Nome do proxecto, gasto, Estado, 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. Por exemplo, we reference Project Status as "Project_x005F_x0020_Name".

Neste punto, partimos do blog de Heather e dos ombros destes xigantes, Eu podo engadir o meu propio pouco.

ContentQueryMain.xsl

NOTA: Ao facer cambios en ambos ContentQueryMain.xsl así como ItemStyle.xsl, ten que comprobar os arquivos de volta antes de ver o efecto das súas alteracións.

Para fins de reixa de decisións, 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 <mesa> cita antes emitindo a primeira liña de datos e do peche <mesa> tag after emitting the last row. To accomplish this, ContentQueryMain.xsl is modified to pass two parameters to our "grid" modelo no ItemStyle.xsl, "last row" and "current row". ItemStyle.xsl uses these to conditionally emit the necessary tags.

Empregando a técnica de Heather Solomon, we locate ContentQueryMain.xsl. It is located in the same place as ItemStyle.xsl. This screen shot should help:

imaxe

Temos que facer os seguintes cambios:

  • Modificar un modelo XSL, "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 <mesa> Tag.
  • Modify another bit of ContentQueryMain.xsl that calls the "CallItemTemplate" to pass it a "LastRow" parámetro para que LastRow pode ser repassada ao noso modelo de Reixa.

Locate the template named "OuterTemplate.CallItemTemplate" identificado pola cadea:

  <XSL:modelo nome="OuterTemplate.CallItemTemplate">

Substituír todo o modelo como segue:

  <XSL:modelo nome="OuterTemplate.CallItemTemplate">
    <XSL:paran nome="CurPosition" />

    <!--
      Add the "LastRow" parámetro.
      We only use it when the item style pass in is "Grid".
    -->
    <XSL:paran nome="LastRow" />

    <XSL:escoller>
      <XSL:cando proba="@ Style = 'NewsRollUpItem'">
        <XSL:apply-templates seleccionar="." xeito="ItemStyle">
          <XSL:con-paran nome="Modo Edición" seleccionar="$cbq_iseditmode" />
        </XSL:apply-templates>
      </XSL:cando>
      <XSL:cando proba="@ Style = 'NewsBigItem'">
        <XSL:apply-templates seleccionar="." xeito="ItemStyle">
          <XSL:con-paran nome="CurPos" seleccionar="$CurPosition" />
        </XSL:apply-templates>
      </XSL:cando>
      <XSL:cando proba="@ Style = 'NewsCategoryItem'">
        <XSL:apply-templates seleccionar="." xeito="ItemStyle">
          <XSL:con-paran nome="CurPos" seleccionar="$CurPosition" />
        </XSL:apply-templates>
      </XSL:cando>

      <!--
              Pase posición actual e LastRow ao modelo ItemStyle.xsl Reixa.
              ItemStyle.xsl vai usar isto para obter a apertura e peche <mesa> Tag.
      -->
      <XSL:cando proba="@ Style = 'Grid'">
        <XSL:apply-templates seleccionar="." xeito="ItemStyle">
          <XSL:con-paran nome="CurPos" seleccionar="$CurPosition" />
          <XSL:con-paran nome="Último" seleccionar="$LastRow" />
        </XSL:apply-templates>
      </XSL:cando>

      <XSL:se non>
        <XSL:apply-templates seleccionar="." xeito="ItemStyle">
        </XSL:apply-templates>
      </XSL:se non>
    </XSL:escoller>
  </XSL:modelo>

As observacións describen o efecto do cambio.

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

<XSL:modelo nome="OuterTemplate.Body">

Desprácese entre as instruccións OuterTemplate.Body e introducir o parámetro LastRow como segue (aparece como un comentario en cursiva):

<XSL:call-template nome="OuterTemplate.CallItemTemplate">
  <XSL:con-paran nome="CurPosition" seleccionar="$CurPosition" />
  <!-- Insire o parámetro LastRow. -->
  <XSL:con-paran nome="LastRow" seleccionar="$LastRow"/>
</XSL:call-template>

Despois de todo isto, Finalmente temos cousas configurado correctamente para que o noso ItemStyle.xsl pode emitir <mesa> etiquetas no lugar seguro.

ItemStyle.xsl

NOTA: De novo, facturación ItemStyle.xsl despois de facer todos os cambios para que vexa o efecto desas mudanzas.

Temos dúas tarefas aquí:

  • 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. (Pode dicir que eu teño unha alza tenue en XSL).

Primeiro, na parte superior ItemStyle.xsl, engadir esta liña:

  <!-- Algúns patranhas que nos permite visualizar U.S. moeda. -->
  <XSL:decimal-formato nome="persoal" díxito="D" />

  <XSL:modelo nome="Omisión" corresponden="*" xeito="ItemStyle">

Teña en conta que eu engade-o directamente antes da <XSL:template name="Default" …> definición.

Seguinte, go back to our Grid template. Replace the entire Grid template with the code below. It is thoroughly commented, pero non dubide en me enviar correo-e ou deixar un comentario no meu blog, se ten dúbidas.

  <XSL:modelo nome="Reixa" corresponden="Liña[@ Style = 'Grid']" xeito="ItemStyle">

    <!--
      ContentMain.xsl pasa CurPos e última.
      Nós usalos para emitir condicional a ceo aberto e peche <mesa> Tag.
    -->
    <XSL:paran nome="CurPos" />
    <XSL:paran nome="Último" />

    <!-- As seguintes variables son non modificados a partir do patrón de ItemStyle.xsl -->
    <XSL:variable nome="SafeImageUrl">
      <XSL:call-template nome="OuterTemplate.GetSafeStaticUrl">
        <XSL:con-paran nome="UrlColumnName" seleccionar="'ImageUrl'"/>
      </XSL:call-template>
    </XSL:variable>
    <XSL:variable nome="SafeLinkUrl">
      <XSL:call-template nome="OuterTemplate.GetSafeLink">
        <XSL:con-paran nome="UrlColumnName" seleccionar="'LinkUrl'"/>
      </XSL:call-template>
    </XSL:variable>
    <XSL:variable nome="DisplayTitle">
      <XSL:call-template nome="OuterTemplate.GetTitle">
        <XSL:con-paran nome="Título" seleccionar="@ Título"/>
        <XSL:con-paran nome="UrlColumnName" seleccionar="'LinkUrl'"/>
      </XSL:call-template>
    </XSL:variable>
    <XSL:variable nome="LinkTarget">
      <XSL:se proba="@ OpenInNewWindow = 'True'" >_blank</XSL:se>
    </XSL:variable>

    <!--
      Aquí imos definir unha variable, "tableStart".  Este contén o código HTML
      .  Nótese que se CurPos = 1, inclúe o HTML nunha etiqueta CDATA.
      En caso contrario, estará baleiro.

      O valor de tableStart é emited cada vez ItemStyle chámase través
      .
    -->
    <XSL:variable nome="tableStart">
      <XSL:se proba="$CurPos = 1">
        <![CDATA[
        <borde da táboa = 1>
          <tr bgcolor="blue">
            <td><font color="white"><b>Nome do Proxecto</b></fonte></td>
            <td align="right"><font color="white"><b>Data completar</b></fonte></td>
            <td align="right"><font color="white"><b>Orzamento</b></fonte></td>
            <td align="right"><font color="white"><b>Gasto real</b></fonte></td>
            <td><font color="white"><b>Estado xeral</b></fonte></td>
          </tr>
        ]]>
      </XSL:se>
    </XSL:variable>

    <!--
      Outra variable, tableEnd define simplemente tag mesa de clausura.

      Igual que tableStart, sempre emited.  É por iso que o seu valor é
      .
    -->
    <XSL:variable nome="tableEnd">
      <XSL:se proba="$CurPos = $ Última">
        <![CDATA[ </mesa> ]]>
      </XSL:se>
    </XSL:variable>

    <!--
      Sempre liberan o contido da tableStart.  Se este non é o primeiro
      , entón sabemos o seu valor
      .

      Desactivar saída fuxir porque cando tableStart non en branco, el
      .  Se
      , it will generate
      stuff like "&lt;mesa&gt;" instead of "<mesa>".
    -->
    <XSL:valor de seleccionar="$tableStart" disable-output-escapar="si"/>


    <tr>
      <!--
      P:Project_x005F_x0020_Name
      :Project_x005F_x0020_End_x005F_x0020_Date
      :Project_x005F_x0020_Budget
      :Project_x005F_x0020_Expenses
      :Project_x005F_x0020_Status
      -->
      <td>
        <XSL:valor de seleccionar="@ Project_x005F_x0020_Name"/>
      </td>

      <td aliñar="dereito">
        <XSL:valor de seleccionar="@ Project_x005F_x0020_End_x005F_x0020_Date"/>
      </td>

      <td aliñar="dereito">
        <XSL:call-template nome="FormatCurrency">
          <XSL:con-paran nome="valor" 
seleccionar="@ Project_x005F_x0020_Budget"></XSL:con-paran> </XSL:call-template> </td> <td aliñar="dereito"> <XSL:call-template nome="FormatCurrency"> <XSL:con-paran nome="valor" seleccionar="@ Project_x005F_x0020_Expenses">
</XSL:con-paran> </XSL:call-template> </td> <td> <XSL:valor de seleccionar="@ Project_x005F_x0020_Status"/> </td> <!-- Todo o que sigue é comentado para aclarar as cousas. Con todo, trae-lo de volta e enche-lo nun <td> para ver a súa         . --> <!-- <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}"/> </un> </p> </XSL:se> <div class="link-item"> <XSL:call-template
name="OuterTemplate.CallPresenceStatusIconTemplate"/> <a href="{$SafeLinkUrl}"
target="{$LinkTarget}" title="{@ LinkToolTip}"> <XSL:value-of select="$DisplayTitle"/> </un> <div class="description"> <XSL:value-of select="@Description" /> </p> </p> </p>
--> </tr> <!-- Emitir tag mesa de clausura. Se non estamos na última liña, este quedará en branco. --> <XSL:valor de seleccionar="$tableEnd" disable-output-escapar="si"/> </XSL:modelo> <XSL:modelo nome="FormatCurrency"> <XSL:paran nome="valor" seleccionar="0" /> <XSL:valor de seleccionar='formato de número($valor, "$DDD,DDD,DDD.DD", "staff")' /> </XSL:modelo>

Estándar do WSS / Moss pantallas de entrada de datos non soportan a fervenza drop-Downs (ou outro intra-de comunicación)

Actualización (04/2008): Esta entrada de blogue gran mostra unha visión baseada en JavaScript bo a este problema: http://webborg.blogspot.com/2008/04/add-functions-and-events-to-sharepoint.html

Actualización II: (04/2008): Este blog parece prometedor, así: http://www.cleverworkarounds.com/2008/03/13/free-mosswss-2007-web-part-hide-controls-via-javascript/

Varias veces por semana, se non diariamente, forum users describe a requirement that would normally be met via cascading drop-downs. Por exemplo, Eu teño dous desplegable controis:

  • Lista de U.S. estados
  • Lista de 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. En realidade, 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. Neste caso, 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 Neste artigo (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.

</ Comezo>

Crear gráficos de barras en SharePoint

Visión global:

(Actualización 12/04/07: Engadido outro recurso interesante a finais ligazón a outro blog que aborda esta vía a parte da web moi interesante)

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.

Escenario empresarial / Instalación:

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:

imaxe

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 aquí (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. Para min, this looks something like this:

imaxe

Neste punto, 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. (Ver aquí 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

No meu caso, parece que esta:

imaxe

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.

Para este fin, 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>
<corpo>
<centro>
<table width=80%>
<tr><td><centro>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 = vermello><td>&nbsp;</td></tr></mesa></td>
</tr>
<tr>
<td width=10%>Pechado</td>
<td><table cellpadding="0" cellspacing="0" border=0 width=25%><tr bgcolor = vermello><td>&nbsp;</td></tr></mesa></td>
</tr>
<tr>
<td width=10%>Stalled</td>
<td><table cellpadding="0" cellspacing="0" border=0 width=25%><tr bgcolor = vermello><td>&nbsp;</td></tr></mesa></td>
</tr>
</mesa>
</td>
</tr>
</mesa>
</corpo>
</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: A finais, 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). Con todo, 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. Entón, remove my calls and insert your own calls to "ShowBar".
  • The drill down works by creating an <a href> así: http://server/List?FilterField1=fieldname&FilterValue1=actualFilterValue. This technique may be of value in other contexts. A principio, 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 versión="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:áspide="http://schemas.microsoft.com/ASPNET/20" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:o="urn:schemas-microsoft-com:oficina" 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 método="html" indent="no" /> <XSL:decimal-formato NaN="" /> <XSL:paran nome="ListUrlDir"></XSL:paran> <!-- I need this to support a drill-down. --> <XSL:modelo corresponden="/" xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:__designer=http://schemas.microsoft.com/WebParts/v2/DataView/designer xmlns:áspide="http://schemas.microsoft.com/ASPNET/20"
> <XSL:variable nome="dvt_StyleName">Táboa</XSL:variable> <XSL:variable nome="Rows" seleccionar="/dsQueryResponse/Rows/Row" /> <XSL:variable nome="dvt_RowCount" seleccionar="count($Rows)" /> <XSL:variable nome="IsEmpty" seleccionar="$dvt_RowCount = 0" /> <XSL:variable nome="dvt_IsEmpty" seleccionar="$dvt_RowCount = 0" /> <XSL:escoller> <XSL:cando proba="$dvt_IsEmpty"> There is no data to graph!<br/> </XSL:cando> <XSL:se non> <!-- 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 nome="totalProposed" seleccionar="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'Proposed'])" /> <XSL:variable nome="percentProposed" seleccionar="$totalProposed div $dvt_RowCount" /> <XSL:variable nome="totalInProcess" seleccionar="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'In Process'])" /> <XSL:variable nome="percentInProcess" seleccionar="$totalInProcess div $dvt_RowCount" /> <XSL:variable nome="totalStalled" seleccionar="count(/dsQueryResponse/Rows/Row[normalize-space(@Status) = 'Stalled'])" /> <XSL:variable nome="percentStalled" seleccionar="$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. --> <mesa ancho="100%" cellspacing="0" cellpadding="2" estilo="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 aliñar="centro"> <mesa fronteira="1" ancho="100%"> <!-- For each status that we want to graph, we call the "ShowBar" modelo. 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 nome="ShowBar"> <XSL:con-paran nome="BarDisplayLabel" seleccionar="'Proposed'"/> <XSL:con-paran nome="BarPercent" seleccionar="$percentProposed"/> <XSL:con-paran nome="QueryFilterFieldName" seleccionar="'Status'"/> <XSL:con-paran nome="QueryFilterFieldValue" seleccionar="'Proposed'"/> <XSL:con-paran nome="TotalItems" seleccionar="$totalProposed"></XSL:con-paran> </XSL:call-template> <XSL:call-template nome="ShowBar"> <XSL:con-paran nome="BarDisplayLabel" seleccionar="'Stalled'"/> <XSL:con-paran nome="BarPercent" seleccionar="$percentStalled"/> <XSL:con-paran nome="QueryFilterFieldName" seleccionar="'Status'"/> <XSL:con-paran nome="QueryFilterFieldValue" seleccionar="'Stalled'"/> <XSL:con-paran nome="TotalItems" seleccionar="$totalStalled"></XSL:con-paran> </XSL:call-template> <XSL:call-template nome="ShowBar"> <XSL:con-paran nome="BarDisplayLabel" seleccionar="'In Process'"/> <XSL:con-paran nome="BarPercent" seleccionar="$percentInProcess"/> <XSL:con-paran nome="QueryFilterFieldName" seleccionar="'Status'"/> <XSL:con-paran nome="QueryFilterFieldValue" seleccionar="'In Process'"/> <XSL:con-paran nome="TotalItems" seleccionar="$totalInProcess"></XSL:con-paran> </XSL:call-template> </mesa> </td> </tr> </mesa> </XSL:se non> </XSL:escoller> </XSL:modelo> <!-- This template does the work of displaying individual lines in the bar graph. You'll probably do most of your tweaking here. --> <XSL:modelo nome="ShowBar"> <XSL:paran nome="BarDisplayLabel" /> <!-- label to show --> <XSL:paran nome="BarPercent"/> <!-- Percent of total. --> <XSL:paran nome="QueryFilterFieldName"/> <!-- Used to jump to the query & filter --> <XSL:paran nome="QueryFilterFieldValue"/> <!-- Used to jump to the query & filter --> <XSL:paran nome="TotalItems" /> <!-- total count of this barlabel --> <tr> <!-- The bar label itself. --> <td clase="ms-formbody" ancho="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:texto disable-output-escapar="si"> <![CDATA[<a href ="]]></XSL:texto> <XSL:valor de seleccionar="$ListUrlDir"/> <XSL:texto disable-output-escapar="si"><![CDATA[?FilterField1=]]></XSL:texto> <XSL:valor de seleccionar="$QueryFilterFieldName"/> <XSL:texto disable-output-escapar="si"><![CDATA[&FilterValue1=]]></XSL:texto> <XSL:valor de seleccionar="$QueryFilterFieldValue"/> <XSL:texto disable-output-escapar="si"><![CDATA[">]]></XSL:texto> <XSL:valor de seleccionar="$BarDisplayLabel"/> <XSL:texto disable-output-escapar="si"><![CDATA[</un>]]></XSL:texto> <!-- The next bit shows some numbers in the format: "(total / % of total)" --> (<XSL:valor de seleccionar="$TotalItems"/> / <!-- This creates a nice percent label for us. Grazas, Microsoft! --> <XSL:call-template nome="percentformat"> <XSL:con-paran nome="percent" seleccionar="$BarPercent"/> </XSL:call-template>) </td> <!-- Finalmente, emit a <td> tag for the bar itself.--> <td> <mesa cellpadding="0" cellspacing="0" fronteira="0" ancho="{round($BarPercent*100)+1}%"> <tr bgcolor="red"> <XSL:texto disable-output-escapar="si"><![CDATA[&nbsp;]]></XSL:texto> </tr> </mesa> </td> </tr> </XSL:modelo> <!-- This is taken directly from some XSL I found in an MS template. --> <XSL:modelo nome="percentformat"> <XSL:paran nome="percent"/> <XSL:escoller> <XSL:cando proba="formato de número($percent, '#,##0%;-#,##0%')= 'NaN'">0%</XSL:cando> <XSL:se non> <XSL:valor de seleccionar="formato de número($percent, '#,##0%;-#,##0%')" /> </XSL:se non> </XSL:escoller> </XSL:modelo> </XSL:stylesheet>

The Results:

The XSL from above generates this graph:

imaxe

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

imaxe

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 enviar correo-e 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.

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

        <XSL:variable nome="totalProposed" 
seleccionar="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 nome="totalProposed" 
seleccionar="count(/dsQueryResponse/Rows/Row[normalize-space(@Status_x0020_Code) = 'Proposed'])" />

Segundo, 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. Por exemplo, if the percentage of "stalled" AFE’s is > 10% then show it red, otherwise show it in black. Usar <XSL:escoller> to accomplish this.

Other Resources:

Happy transforming!

</ Comezo>

Rexístrate para o meu blog!

Present OM Data Vía a Custom List (ou, Yet Another OM Datos Displayor [como Yacc, pero distinto])

Hoxe, 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."

A columna en cuestión podería crear, apagados e recriados noutro ambiente, so I knew it wasn’t a reserved name. Con todo, Eu simplemente non podía atopar a columna en calquera lugar a través da interface de usuario por defecto do SharePoint en calquera sitio na colección web.

Eu postei a Foros de MSDN aquí eo indomável Andrew Woodward me apuntou na dirección dos datos do modelo subxacente obxecto.

Fun codeplex para atopar algunhas ferramentas que me axudarían a perscrutar os datos subxacentes OM e me axudar a atopar o problema.

Tente varias ferramentas e eles estaban moi legal e interesante, pero ao final, the UI wasn’t good enough for my purpose. I’m not criticizing them by any means, pero está claro que as ferramentas decisores non teñen o meu problema en mente cando creou a súa interface de usuario :). Most people seem to be investing a fair amount of time and effort in creating workstation / aplicacións cliente que ofrecen vistas de árbores, right-click context menus and so forth. These are nice and all, pero é unha chea de traballo para crear un principio de liña a experiencia do usuario que tamén é moi flexible.

Realmente precisaba unha resposta a este problema. Houbo-me que se eu puidese obter toda a columnas de sitio na colección sitio a unha lista personalizada, Eu podería filtrar, clasificar e crear exhibicións que ía me axudar a atopar esta columna supostamente existente (o que fixo, BTW). I went ahead and did that and an hour or two later, tiña todas as columnas do meu sitio cargado nunha lista personalizada con agrupación, sorting and so forth. I found my answer five minutes later.

E cando eu conseguir conquistar o mundo, I think I will decree that all SharePoint tools providers must seriously consider surfacing their object model data in a custom list. That way, Eu teño o poder para buscar todas as maneiras que quero (constrangido, claro, pola norma SharePoint características).