Home RSS 2.0 ATOM 1.0  CDF  
 
CodeSegment - Carlos Segura Sanz (blog)
 

This is other sample of how I am using Ajax in my SharePoint environment (see Using Ajax to query Exchange Server Part 1 and Part 2) , now I'm using it to improve my searches in SPS.



First I have added a new page to make the searches, this new page runs under SPS context and it is stored under Layouts directory. This is very basic search page that look at the "DAV:displayname" field to locate files that contains a keyword in the name. This page use a query string to get the keyword and the results are written in HTML. (You can use other queries here).
 

csegAjaxSearch.aspx

<%@ Page language="C#" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, 
Microsoft.SharePoint,Version=11.0.0.0, Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
Assembly="Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePointPortal" Namespace="Microsoft.SharePoint.Portal" 
Assembly="Microsoft.SharePoint.Portal, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %> 
<%@ Import Namespace="Microsoft.SharePoint.Portal" %>
<%@ Import Namespace="Microsoft.SharePoint.Portal.Topology" %>
<%@ Import Namespace="Microsoft.SharePoint.Portal.Search" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Text" %>
 
<%
    TopologyManager topology = new TopologyManager();
    PortalSite portal = topology.PortalSites[new Uri("<USE YOUR SERVER HERE>")];
    PortalContext context = PortalApplication.GetContext(portal);
    QueryProvider qp = new QueryProvider(context.SearchApplicationName);
 
    string keyword = Request["k"];
    
    if(keyword!=null && keyword.Trim()!="")
    {
        string queryTemplate = "SELECT \"DAV:href\", " +
                               "\"DAV:displayname\", " +
                               "\"urn:schemas.microsoft.com:fulltextqueryinfo:description\", " +
                               "\"urn:schemas-microsoft-com:office:office#ows_SiteName\" " +
                               "FROM ( TABLE Portal_Content..Scope() " +
                               "UNION ALL TABLE Non_Portal_Content..Scope() ) " +
                               "WHERE CONTAINS(\"DAV:displayname\", '\"*" + 
                               keyword.Replace("'", "''").Replace("\"", "\"\"") + "*\"') ";
        Response.Write(queryTemplate);
        
        DataSet ds = qp.Execute(queryTemplate);
 
        StringBuilder sb = new StringBuilder();
    
        if(ds != null)
        {
           sb.Append("<UL>");
           foreach(DataRow dr in ds.Tables[0].Rows)
           {
              sb.AppendFormat("<LI><A href='{0}'>{1}</A><BR/>{2}<BR/>{3}<BR/></LI>",
                 SPEncode.HtmlEncode(dr["DAV:href"].ToString()),
                 SPEncode.HtmlEncode(dr["DAV:displayname"].ToString()),
                 SPEncode.HtmlEncode(dr["urn:schemas.microsoft.com:fulltextqueryinfo:description"].ToString()),
                 SPEncode.HtmlEncode(dr["urn:schemas-microsoft-com:office:office#ows_SiteName"].ToString()));
           }
           sb.Append("</UL>");
        }
        else
        {
           sb.Append("<P>No results</P>");
        }
      
        Response.Write(sb.ToString());
    }
%>   

In a new area of my SPS server I have added a Html Form webpart, that use ajax to return the results. Here is the code.


<script language="javascript">
var xmlHttpReq;
 
function initHttpRequest()
{
    try 
    {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(ex)
    {
        xmlHttpReq = null;
    }    
}
 
function sendQuery(keywords)
{
    var serverUrl = "http://YOUR SERVER/_layouts/csegAjaxSearch.aspx?k=" + keywords;
    
    initHttpRequest();
   
    if (xmlHttpReq != null)
    {
        xmlHttpReq.onreadystatechange = checkState;
        xmlHttpReq.open("GET", serverUrl, true);
        xmlHttpReq.send(null);
    }    
}
 
function checkState()
{
    // Load completed
    if (xmlHttpReq.readyState == 4)  
    {
        // Status OK
        if (xmlHttpReq.status == 200)
        {
            document.getElementById("Results").innerHTML = xmlHttpReq.responseText;
        }
        // Error
        else
        {
           document.getElementById("Results").innerHTML = "<b>There is an error in the service</b>";
        }
    }
}
</script>
 
<form name="form">
  <input name="keyword" onKeyUp="sendQuery(this.value)" style="WIDTH:500px" autocomplete="off">
  <div align="left" id="Results" style="width:100%"></div>
</form>
Friday, April 28, 2006 7:44:30 PM (Hora de verano romance, UTC+02:00)   #    Comments [8]   csegSearch | SharePoint  | 

Miguel Jimenez (MVP C#) ha estado estos días en Pamplona asi que aprovechamos para tomar unas cervezas y hablar sobre lo humano y lo divino ....


Wednesday, April 26, 2006 8:13:37 PM (Hora de verano romance, UTC+02:00)   #    Comments [0]   Misc  | 

I continue working in my csegSharePoint library. Meanwhile I'm doing some test with this, as this webpart that is a small calendar that show a date field from a list, and  it allows select the dates witth entries, and provide a cell value with the date. You can select the List and the Field and the styles to draw the calendar.

Also you can use this with csegRollUp to filter by dates, using [CellProvider] in queries.

The source code will be available along with more examples as csegNavigator and others with csegSharePoint.

 csegSmallCalendar.zip (13,68 KB)
Wednesday, April 26, 2006 12:16:14 AM (Hora de verano romance, UTC+02:00)   #    Comments [6]   csegSmallCalendar | SharePoint  | 

Estos días continuo terminando cosas, la biblioteca csegSharePoint, y el csegRollUp 3.5 (que me esta dando algún que otro problemilla). La cosa es que eh empezado a recodificar algunos de los webparts que tenía para que usen la nueva biblioteca csegSharePoint en la que estoy trabajando. Por el momento he pasado este par de webparts que me son bastante útiles.

csegSubWebs (WSS) y csegSubAreas (SPS), son dos webparts que muestran un árbol con las subwebs y con las subareas.


 csegNavigator.zip (13,38 KB)
Monday, April 24, 2006 9:24:44 AM (Hora de verano romance, UTC+02:00)   #    Comments [0]   SharePoint-es  | 

This is a small xml stylesheet to render a generic table with the data collected from csegRollUp, and it's ideal for debug purposes.

<?xml version="1.0" encoding="utf-8"?>
 
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 
  <xsl:template match="Rows">
    <xsl:call-template name="Tabla"/>
  </xsl:template>
 
  <!-- Tabla -->
  <xsl:template name="Tabla">
    <table width="100%" cellpading="1">
      <tbody>
      <xsl:call-template name="Cabeceras" />
      <xsl:for-each select='Row'>
        <tr>
          <xsl:for-each select=".//*">
            <td class="ms-vb2">
              <xsl:value-of select="."/>
            </td>
          </xsl:for-each>
        </tr>
      </xsl:for-each>
      </tbody>
    </table>
  </xsl:template>
  
  <!-- Cabeceras de la tabla -->
  <xsl:template name="Cabeceras">
    <tr>
      <xsl:for-each select="Row[1]/*">
        <th nowrap=""  class="ms-vh2">
          <xsl:value-of select="name()"/>
        </th>
      </xsl:for-each >
    </tr>
  </xsl:template>
  
</xsl:stylesheet> 

Now I'm finishing the new version 3.5. There is a beta in the forums.

 

Wednesday, April 19, 2006 11:39:19 PM (Hora de verano romance, UTC+02:00)   #    Comments [0]   csegRollUp  | 

Hoy ha sido otro de esos días divertidos con SharePoint, tras configurar una máquina con SharePoint (WSS) le hemos cambiado el nombre  (es un servidor aislado) pero ... nos hemos encontrado con el conocido error ....

No se puede conectar con la base de datos. Compruebe la información de conexión con la base de datos y asegúrese de que el servidor de la base de datos está funcionando. Para obtener sugerencias sobre cómo solucionar este error, busque el artículo 823287 de Microsoft Knowledge Base en http://support.microsoft.com.

Sobre el cual la KB no aporta nada. Mi solución consiste en básicamente tratar de acceder vía administración central del SharePoint para cambiar el servidor de la base de datos de configuración en primer lugar. Si no se puede, cosa bastante normal ya que el servidor SQL con la base de datos de configuración queda referenciado por el nombre anterior, podemos editar el registro del servidor y localizar :

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\Secure\ConfigDb]
"dsn"="Provider=SQLOLEDB;Server=SRV2\\SharePoint;Database=STS_Config;User Id=;Password="

Cambiar el nombre del servidor por el nuevo nombre de nuestra máquina y acceder a la administración central de SharePoint, ahora desde la administración central podremos cambiar tambien la base de datos de contenido dentro de la configuración del servidor virtual. Para dejarlo todo bonito, he hecho una copia de las bases de datos, con el servicio (MSSQL$SHAREPOINT) parado y les he cambiado el nombre de modo que en vez de STS_SERVEROLD_1.mdf y STS_SERVEROLD_1_LOG.mdf les he llamado STS_SRV2 ....

Problemilla resuelto....

Monday, April 10, 2006 11:31:07 PM (Hora de verano romance, UTC+02:00)   #    Comments [0]   SharePoint-es  | 

Finally I have a first version (0.99) of my InfoPath viewer, first I want give thanks to my friend Gustavo, for testing the preliminary version and to make as always good suggestions.

Installation

stsadm -o addwppack -filename csegInfopathWebPart.cab -globalinstall  (use -force if you have installed the preliminary version)

Use

a) Create a view in your Form Library webpart containing the identifier of the list (the ID field).

b) Create a new webpart page, and insert the FormLibrary webpart and csegInfoPath webpart.

c) In the FormLibrary webpart select the view that contains the ID field, you need this view to connect with csegRollUp.

d) In the FormLibrary webpart menu select, "Conections" -> "Send row to" -> "csegInfoPathViewer" when prompt for field use the ID field.

e) Now fill the csegInfoPathViewer properties, you need specify the form library list name in the "List Name" field and put the XSL in the field XSL. (You can extract it from the infopath solution file, rename it as a .cab file and extract the xsl, then copy the content into the xsl property)

f) Now select an item and you can view the form in the csegInfoPathViewer.

 csegInfoPathViewer.zip (8,44 KB)
Friday, April 07, 2006 5:20:56 PM (Hora de verano romance, UTC+02:00)   #    Comments [12]   csegInfoPathViewer | SharePoint  | 

El otro día comentaba el problema que había tenido con los interfaces de conexión de los webparts. Tenía un webpart consumidor conectado con dos proveedores, la primera vez que uno de los webparts proveía un valor este era aceptado por el consumidor, pero desde el momento en que el consumidor aceptaba un valor desde el segundo webpart, ya nunca más volvía a aceptar valores del primero. Evidentemente el comportamiento cambiaba si se invertía el orden de conexión. Tras dedicarle un buen rato y reproducir el problema en su esencia usando tres webparts, caí en la cuenta de que un valor null o vació también es transmitido .... de modo que ese era el problema. Así que a revisar los PartComunicationMain()

/// <summary>
/// In this method, a part can fire any events that it requires to.
/// </summary>
public override void PartCommunicationMain()
{
    if (CellReady != null && sProviderValue != defaultText)
    {
       // send value 
    }
}
 

Thursday, April 06, 2006 12:09:33 AM (Hora de verano romance, UTC+02:00)   #    Comments [0]   SharePoint-es  | 


Copyright © 2008 Carlos Segura. All rights reserved.