Thursday, July 15, 2010

Error message when you try to start User Profile Synchronization in SharePoint 2010: An update conflict has occurred, and you must re-try this action. The object UserProfileApplication Name=User Profile Service Application was updated by [User]

Symptoms:

When you try to start User Profile Synchronization (Full/Incremental) or start the "User Profile Synchronization Service" found under "Services on server" in SharePoint 2010, you receive an error
"An update conflict has occurred, and you must re-try this action. The object UserProfileApplication Name=User Profile Service Application was updated by [User]"

Full details about this error as it is logged in various places has been detailed below:

ULS:

ConcurrencyException: Old Version : 241817 New Version : 241817 99a7a04b-0297-4ecc-9621-a38b05c8ccce Microsoft.SharePoint.Administration.SPUpdatedConcurrencyException: An update conflict has occurred, and you must re-try this action. The object UserProfileApplication Name=User Profile Service Application was updated by [User], in the OWSTIMER (3456) process, on machine [Server Name]

ULS:

SharePoint Foundation Runtime Unexpected Microsoft.SharePoint.Administration.SPUpdatedConcurrencyException: An update conflict has occurred, and you must re-try this action. The object UserProfileApplication Name=User Profile Service Application was updated by [User], in the OWSTIMER (3456) process, on machine [Server Name]

Event Viewer:

The Event 6482 is logged once every minute and has the following data:
An update conflict has occurred, and you must re-try this action. The object SearchDataAccessServiceInstance was updated by [User], in the OWSTIMER (1756) process, on machine [Server Name].

Troubleshooting:

Our initial thoughts went in the direction of Active Directory. We have started investigating whether any changes have been made to the AD that may be causing the issue. After confirming that no AD changes have been made, we tried to see why it is failing using the "Microsoft Forefront Identity Manager 2010" as it provides step by step detail about what happens. The "Microsoft Forefront Identity Manager 2010" failed to start because the "User Profile Synchronization Service" and the forefront windows services (Forefront Identity Manager Service and Forefront Identity Manager Synchronization Service) were in stopped state. When we tried to start the "User Profile Synchronization Service", we got the same error detailed above.
We took the whole farm backup and investigated further.

Cause:

This issue occurs if the contents of the file system cache on the front-end servers are newer than the contents of the configuration database. After you perform a system recovery, you may have to manually clear the file system cache on the local server.

Resolution:
To resolve this issue, clear the file system cache on all servers in the server farm on which the Windows SharePoint Services Timer service is running.

Microsoft has provided a step by step procedure on clearing file system cache from the SharePoint front-end servers in this kb article.


  1. Stop the Windows SharePoint Services Timer service (Found in Windows Services)
  2. Navigate to the cache folder
    In Windows Server 2008, the configuration cache is in the following location:
    Drive:\ProgramData\Microsoft\SharePoint\Config
    In Windows Server 2003, the configuration cache is in the following location:
    Drive:\Documents and Settings\All Users\Application Data\Microsoft\SharePoint\Config
    Locate the folder that has the file "Cache.ini"
    (Note: The Application Data folder may be hidden. To view the hidden folder, change the folder options as required)
  3.  Back up the Cache.ini file.
  4. Delete all the XML configuration files in the GUID folder. Do this so that you can verify that the GUID folder is replaced by new XML configuration files when the cache is rebuilt.
  5. Note When you empty the configuration cache in the GUID folder, make sure that you do not delete the GUID folder and the Cache.ini file that is located in the GUID folder.
  6. Double-click the Cache.ini file.
  7. On the Edit menu, click Select All. On the Edit menu, click Delete. Type 1, and then click Save on the File menu. On the File menu, click Exit.
  8. Start the Windows SharePoint Services Timer service
  9. Note The file system cache is re-created after you perform this procedure. Make sure that you perform this procedure on all servers in the server farm.
  10. Make sure that the Cache.ini file in the GUID folder now contains its previous value. For example, make sure that the value of the Cache.ini file is not 1.

Wednesday, July 7, 2010

How to create an External Content Type in SharePoint Designer 2010 using Business Connectivity Services(BCS) and fix issues that arise on the way

Scenario:
How to create an External Content Type in SharePoint Designer 2010 using Business Connectivity Services(BCS) and fix issues that arise on the way

Explanation:
In this walkthrough I will explain how to use Sharepoint Server 2010 Business Connectivity Services(BCS) feature to access external business data (SQL Server 2008 in this example). This simple step-by-step will also help you fix the issues that you might encounter on the way

Create Model using SharePoint Designer

SPD includes functionality to design the application definition model visually. Based on the options selected on UI, it generates the xml metadata in the background. Using ECT Designer in SPD you can discover database, point to the table, view, or stored procedure that will perform the operations, and then return the required data and use it to create external content type without writing any code or XML. Follow the steps below to create the ECT:

Open up SharePoint Designer 2010 and click on "External Content Types"

External Content Types

To create a new external content type, click on "New External Content Type" in the ribbon



Click on the link "Click here to discover external data sources and define operations". This will open up the windows to define the connection to AW database and operations for the ECT.

Click "Add Connection" under External Data Source section and choose Data Source Type as SQL Server. This brings up the SQL connection properties dialog. In this we are connecting using SQL Server provider to get data.

Define Operations on External System

SPD provides option to create the view for all common operations available in BCS or it can create operations for specific operation.

Following two minimum operations are required to fetch data from backend using BCS:

  • Query Item List method which gets the list of records and work as finder method
  • Read Item method which gets data for specific record and work as SpecificFinder method

Choose the appropriate external data connection and then the database table. Right click on the selected table and create operations as required. In this example, I have created all the operations that are possible through SPD 2010.

External Data Connection

After adding all the operations, we should be able to see something like in the image below:



Create External List based on External Content Type

You can create an external content type by using Microsoft SharePoint Designer 2010 or the browser. Follow the steps given below to create list using browser.

  1. Open the SharePoint site in which you would like to create the external list in browser.
  2. Go to Site Actions, View All Site Content.
  3. Click the Create button. In the Custom Lists section, click External List.
  4. On the New page, type the list name and description for the new external list.
  5. The Data source configuration section displays a text box and an external content type picker. Use the picker to choose the external content type. Select the newly created external content type and then click OK.
  6. Click Create.
This creates the external list. You can now navigate to the new list in the SharePoint site and view/edit items.





All good so far. But you can expect to see the below error when we try to access the external list that has been just created.

Access Denied Error

This is because the BDC service that we just created has not been given permissions yet.

Open Central Admin > Application Management > Manage Service Applications > Business Data Connectivity Service and select the check box next to the service that we just created and then click "Set Object Permissions". Add the user(s) that need to be given access as in the image below:



Go back to the external list and refresh the page if required.
Now we see a new error "Login failed for user 'NT Authority\ANONYMOUS LOGON" as in the image below:

Login failed error

The above error occured because by default, when we create the BDC definition in SPD 2010, the authentication mode is set to "User's Identity".

The "Connect with User’s Identity" is the "PassThrough" authentication mode we had in MOSS 2007 BDC. The other 2 relates to SSO. Now that we have Secure Store Service Application, we can use "Connect with Impersonated Windows Identity" OR if we are using claims token we can use "Connect with Impersonated Custom Identity"

Inorder to access the data from the external data connection, one way of fixing the above issue is to change the Authentication Mode from "User's Identity" to "BDC Identity".

So open up the external content type in SPD 2010 and change the authentication mode.



Now we end up with a new error:

Change Authentication Mode Error

Below are steps we need to follow to get this corrected!

We have to first enable BCS model to accept "RevertToSelf" as one of the authentication modes. Yes, it’s disabled by default. We can do this using SharePoint 2010 Management Console.

The "ReverToSelfAllowed" property is set to false by default. We can now change it to true using the below script:

$bdc = Get-SPServiceApplication | where {$_ -match "Business Data Connectivity Service"};
$bdc.RevertToSelfAllowed = $true;
$bdc.Update();

So finally when we hit the list again, we should be able to see the rows from the SQL Server table as items in the external list that we have created. Also notice the highlighted top left corner in the image below.
We are able to see the options "New Item", "View Item", "Edit Item" and "Delete Item" because I have created all the operations from SPD 2010 when I created the BDC definition above. If you skip any of the operations for example "Delete Operation", the "Delete Item" option will be diabled in the ribbon.


Friday, July 2, 2010

Effect of moving PerformancePoint Service from one server in a SharePoint 2010 farm to another..

Scenario:
We have 2 WFE servers in a SharePoint 2010 farm.
We had PerformancePoint Service residing on WFE1 and for enhancing performance, we needed to move it to WFE2.
Before moving the service we had one dashboard page that was using PerformancePoint Service.



After movied the services from WFE1 to WFE2, all the web parts on the page disappeared and we ended up with the below:



Explanation:
Plan your farm well in advance and be cautious and take the necessary backups before attempting to move the services from one server to the other in a farm.

Saturday, June 26, 2010

SharePoint 2010 - Application Page runtime error "Server Error in "/" Application"

Scenario:

I have developed an application page in SharePoint 2010. After deploying it as a solution, I got the below error:

Server Error in '/' Application. 
--------------------------------

Runtime Error

<!-- Web.Config Configuration File -->

<configuration>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration> 

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.

<!-- Web.Config Configuration File -->

<configuration>
  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
  </system.web>
</configuration> 

So, I went in and turn customError and StackTrace option, in web.config on; and then, I got a more detailed error :). Runtime Error with the description telling me that I need to set customError and StackTrace on to see the message. This sound very recursive and very strange. Since, I could not see this error that is why I try to turn on by changing customError and StackTrace on and now they are both on, I am suddenly getting the message telling me to do so in place of the SharePoint custom error.

Explanation:

In SharePoint 2010, depending on what we do, we may need to also edit the web.config in the layouts folder of the SharePoint root:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\web.config

Tuesday, June 22, 2010

"Internet Explorer cannot display the webpage" error in SharePoint 2010 web application

While working on a SharePoint 2010 site, I suddenly encountered the infamous error "Internet Explorer cannot display the web page".

It was just me who was working on that farm at that time.

When I attempted to access the same site collection from within the server, I have been thrown the login prompt repeatedly despite providing the right credentials. All the other site collections in other web applications were behaving normally.

So at this point, it looks like it has to do some thing with that particular web application. I started to check all the web application properties, performed IISRESET but nothing worked. So I rebooted all the servers in the farm starting with the WFEs, then the SQL Server and the AD server.

Finally after handling the Loopback check issue which is covered in this KB article: http://support.microsoft.com/kb/896861, the authentication issues have been resolved.

Friday, June 4, 2010

Displaying real time SharePoint search results alphabetically using search.asmx and jQuery/JS

Scenario:
Ho to display real time SharePoint people search results alphabetically using search.asmx and js

Explanation:
If there is a requirement to display all AD users in people search in SharePoint, the list can grow long and hence it is a good idea to categorize users alphabetically.

People Search Results

Solution:
The below combination of Javascript and XSL can be used to accomplish the above. You can either use your own custom search web part or the OOB search results web part to get the results xml and apply the below XSL to the xml result

The below XSL builds a list of alphabets as links. Upon clicking each link a javascript function is called and names of people that start with the corresponding alphabet are displayed.

<xsl:attribute name="onclick">
GetContacts('<xsl:value-of select="child::node()[position()]"/>');
</xsl:attribute>

Lets get started..

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
  <xsl:output method="html" encoding="UTF-8"/>
  <xsl:template name="Alphabets">
    <Alpha>A</Alpha>
    <Alpha>B</Alpha>
    <Alpha>C</Alpha>
    <Alpha>D</Alpha>
    <Alpha>E</Alpha>
    <Alpha>F</Alpha>
    <Alpha>G</Alpha>
    <Alpha>H</Alpha>
    <Alpha>I</Alpha>
    <Alpha>J</Alpha>
    <Alpha>K</Alpha>
    <Alpha>L</Alpha>
    <Alpha>M</Alpha>
    <Alpha>N</Alpha>
    <Alpha>O</Alpha>
    <Alpha>P</Alpha>
    <Alpha>Q</Alpha>
    <Alpha>R</Alpha>
    <Alpha>S</Alpha>
    <Alpha>T</Alpha>
    <Alpha>U</Alpha>
    <Alpha>V</Alpha>
    <Alpha>W</Alpha>
    <Alpha>X</Alpha>
    <Alpha>Y</Alpha>
    <Alpha>Z</Alpha>
  </xsl:template>
  <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'"/>
  <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
  <xsl:key name="keyTitle" match="Result" use="translate(substring(lastname,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/>
  <xsl:template match="/">
    <xsl:variable name="Rows" select="/Search_Results/All_Results/Result"/>
    <div id="assocDirResultBox" sizset="115" sizcache="16">
      <xsl:variable name="AlphabetNodes">
        <xsl:call-template name="Alphabets"/>
      </xsl:variable>
      <xsl:variable name="AlphabetName">
        <xsl:apply-templates select="msxsl:node-set($AlphabetNodes)/Alpha">
          <xsl:sort select="." order="ascending"/>
        </xsl:apply-templates>
      </xsl:variable>
      <xsl:variable name="TitleNames">
        <xsl:for-each select="$Rows[generate-id(.) = generate-id(key('keyTitle', translate(substring(lastname,1,1),$smallcase,$uppercase))[1])]">
          <xsl:value-of select="translate(substring(lastname,1,1),$smallcase,$uppercase)"/>
        </xsl:for-each>
      </xsl:variable>
      <a name="top_AssosiatesAToZ"></a>
      <div class="alphaBrowseNavBox" sizcache="16" sizset="111">
        <div class="alphaBrowseNav" sizcache="16" sizset="111">
          <xsl:for-each select="msxsl:node-set($AlphabetNodes)/Alpha">
            <xsl:if test="position() &lt;= count(msxsl:node-set($AlphabetNodes)/Alpha)">
              <xsl:variable name="char" select="child::node()[position()]"/>
              <xsl:choose>
                <xsl:when test="contains($TitleNames,$char)">
                  <a>
                    <xsl:attribute name="href">
                      #<xsl:value-of select="child::node()[position()]"/>
                    </xsl:attribute>
                    <xsl:attribute name="onclick">
                      GetContacts('<xsl:value-of select="child::node()[position()]"/>');
                    </xsl:attribute>
                    <xsl:value-of select="child::node()[position()]"/>
                  </a>
                </xsl:when>
                <xsl:otherwise>
                  <span>
                    <xsl:value-of select="child::node()[position()]"/>
                  </span>
                </xsl:otherwise>
              </xsl:choose>
            </xsl:if>
          </xsl:for-each>
        </div>
      </div>
      <div id="searchResults">
      </div>
    </div>
  </xsl:template>
  <!-- A generic function that can be used to replace strings in a given text. Similar to String.Replace of C# -->
  <xsl:template name="ReplaceAllCharsInString">
    <xsl:param name="text"/>
    <xsl:param name="replace"/>
    <xsl:param name="by"/>
    <xsl:choose>
      <xsl:when test="contains($text, $replace)">
        <xsl:value-of select="substring-before($text,$replace)"/>
        <xsl:value-of select="$by"/>
        <xsl:call-template name="ReplaceAllCharsInString">
          <xsl:with-param name="text" select="substring-after($text,$replace)"/>
          <xsl:with-param name="replace" select="$replace"/>
          <xsl:with-param name="by" select="$by"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

The javascript/jQuery functions:
function GetContacts(alpha) 
  {
   var qry = "SELECT Department,WorkPhone,OfficeNumber,AboutMe,PictureURL,WorkEmail,WebSite,BaseOfficeLocation,LastName,FirstName,Company,MobilePhone,PreferredName,AccountName,UserProfile_GUID, JobTitle,Size, Rank, Path, Title, Description, Write  FROM SCOPE() WHERE (\"scope\"='Associates') AND (\"DAV:contentclass\"='urn:content-class:SPSPeople') AND (\"LastName\" LIKE '" + alpha + "%') ORDER BY LastName";

   var queryXML = 
    <![CDATA["<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'> \
    <Query domain='QDomain'> \
     <SupportedFormats><Format>urn:Microsoft.Search.Response.Document.Document</Format></SupportedFormats> \
     <Context> \
      <QueryText type='MSSQLFT' language='en-us'>#qry#</QueryText> \
     </Context> \
    <SortByProperties><SortByProperty name='Rank' direction='Descending' order='1'/></SortByProperties> \
     <Range><StartAt>1</StartAt><Count>2000</Count></Range> \
     <EnableStemming>false</EnableStemming> \
     <TrimDuplicates>true</TrimDuplicates> \
     <IgnoreAllNoiseQuery>true</IgnoreAllNoiseQuery> \
     <ImplicitAndBehavior>true</ImplicitAndBehavior> \
     <IncludeRelevanceResults>true</IncludeRelevanceResults> \
     <IncludeSpecialTermResults>true</IncludeSpecialTermResults> \
     <IncludeHighConfidenceResults>true</IncludeHighConfidenceResults> \
    </Query></QueryPacket>"]]>;
   
   queryXML = queryXML.replace('#qry#', qry);
   
   var soapEnv =
    <![CDATA["<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
      <soap:Body> \
     <Query xmlns='urn:Microsoft.Search'> \
       <queryXml>" + escapeHTML(queryXML) + "</queryXml> \
     </Query> \
      </soap:Body> \
    </soap:Envelope>"]]>;   

   $.blockUI({ message: '<p>Please wait while the contacts are being loaded...</p>' });
    
   $.ajax({
    url: window.location.protocol + "//" + window.location.host + "/_vti_bin/search.asmx",
    type: "POST",
    dataType: "xml",
    data: soapEnv,
    complete: processResult,
    contentType: "text/xml; charset=\"utf-8\""
   });
   
   function processResult(xData, status) {
    var html = "";
    html += "&lt;div class='alphaBrowseNavHeader'&gt;" + alpha + "&lt;/div&gt;";
    html += "&lt;div class='rightActionsWrapper'&gt;";
    $(xData.responseXML).find("QueryResult").each(function() {
     var x = $("<xml>" + $(this).text() + "</xml>");

     /* Find value of each property */ 
     x.find("Document").each(function() {
      var department = '', workPhone = '', pictureUrl = '', workEmail = '', location = '', lastName = '', firstName = '', company = '', mobilePhone = '', preferredname = '', accountName = '', accountNameEncoded = '', jobTitle = '', responsibility = '';
      $(this).find("Property").each(function() {
       switch($(this).find("Name").text())
       {
        case 'DEPARTMENT':
         department = $(this).find("Value").text();
         break;
        case 'WORKPHONE':
         workPhone = $(this).find("Value").text();
         break;          
        case 'PICTUREURL':
         pictureUrl = $(this).find("Value").text();
         break;          
        case 'WORKEMAIL':
         workEmail = $(this).find("Value").text();
         break;          
        case 'BASEOFFICELOCATION':
         location = $(this).find("Value").text();
         break;          
        case 'LASTNAME':
         lastName = $(this).find("Value").text();
         break;          
        case 'FIRSTNAME':
         firstName = $(this).find("Value").text();
         break;          
        case 'COMPANY':
         company = $(this).find("Value").text();
         break;          
        case 'MOBILEPHONE':
         mobilePhone = $(this).find("Value").text();
         break;          
        case 'PREFERREDNAME':
         preferredname = $(this).find("Value").text();
         break;          
        case 'ACCOUNTNAME':
         accountName = $(this).find("Value").text();
         accountNameEncoded = accountName.replace('\\','%5C');
         break;          
        case 'JOBTITLE':
         jobTitle = $(this).find("Value").text();
         break;  
        case 'RESPONSIBILITY':
         responsibility = $(this).find("Value").text();
         break;  
        default:
         break;
       }
      })
      
      /* If no picture is available, display the temp place holder image */
      if(pictureUrl == '')
      {
       pictureUrl = '/Style%20Library/Images/temp_placeholder.gif';
      }          
      
      var title = $("Title", $(this)).text();
      var url = $("Action>LinkUrl", $(this)).text();
      var description = $("Description", $(this)).text()
       
      html += 
      <![CDATA["<div class='rightActionsBox'> \
       <a href='"+ url +"'><img alt='Photo of " + preferredname + "' border='0' width='158' class='rightActionsBoxImage' src='"+pictureUrl+"' /></a> \
       <div class='rightActionsCopy' sizset='122' sizcache='16'> \
        <a href='"+ url +"'><span class='name'>" + preferredname + "</span></a> \
        <table class='assocDirResultTable'> \
         <tbody> \
          <tr> \
           <td> \
            <span class='property title'>&#160;#jobTitle#</span> \
            <span class='property'><label>Work:</label>&#160;#workPhone#</span> \
            <span class='property'><label>Mobile:</label>&#160;#mobilePhone#</span> \
            <span class='property' sizset='122' sizcache='16'>#accountLink#</span> \
           </td> \
           <td> \
            <span class='property'><label>Business:</label>&#160;#company#</span> \
            <span class='property'><label>Department:</label>&#160;#department#</span> \
            <span class='property'><label>Location:</label>&#160;#location#</span> \
           </td> \
           <td class='last'><label>Ask me about</label> \
            <span class='property'>#responsibility#</span> \
           </td> \
          </tr> \
         </tbody> \
        </table> \
       </div> \
       <ul class='rightActions' sizset='123' sizcache='16'> \
        <li class='iconCal' sizset='123' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#AddToColleageCall#, null, AddToColleaguesDialogCallback);return false;'>Add As Colleague</a> \
        </li> \
        <li class='iconPeople' sizset='124' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#ShowOrganizationHierarchyCall#, null, ShowOrganizationHierarchyDialogCallback);return false;'>Browse In Organization Chart</a> \
        </li> \
        <li class='iconFlagGreen' sizset='125' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#ViewRecentContentCall#, null, ViewRecentContentDialogCallback);return false;'>View Recent Content</a> \
        </li> \
       </ul> \
      </div>"]]>
      html = html.replace('#jobTitle#', jobTitle).replace('#workPhone#', workPhone).replace('#mobilePhone#', mobilePhone).replace('#company#', company).replace('#department#', department).replace('#location#', location).replace('#responsibility#', responsibility).replace('#AddToColleageCall#','"' + 'http://[Site URL]/my/_layouts/QuickLinksDialogForm.aspx?Mode=Person&amp;NTName=' + accountNameEncoded + '&amp;IsDlg=1' + '"').replace('#ShowOrganizationHierarchyCall#','"' + 'http://[site url]/my/OrganizationView.aspx?ProfileType=User&amp;accountname=' + accountNameEncoded + '"').replace('#ViewRecentContentCall#','"' + 'http://[site URL]/my/personcontent.aspx?accountname=' + accountNameEncoded + '"').replace('#workEmail#',workEmail);
      if(workEmail != '')
      {
       html = html.replace('#accountLink#','&lt;a href=\'mailto:#workEmail#\'&gt;#accountName#&lt;/a&gt;');
       html = html.replace('#workEmail#', workEmail);
       html = html.replace('#accountName#', accountName);
      }
      else 
       html = html.replace('#accountLink#',accountName);
     });
    });
    html += "&lt;/div&gt;"; 
    $("#searchResults").empty().append(html);
   }
  } 

Complete Code:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
 <xsl:output method="html" encoding="UTF-8"/>
 <xsl:template name="Alphabets">
  <Alpha>A</Alpha>
  <Alpha>B</Alpha>
  <Alpha>C</Alpha>
  <Alpha>D</Alpha>
  <Alpha>E</Alpha>
  <Alpha>F</Alpha>
  <Alpha>G</Alpha>
  <Alpha>H</Alpha>
  <Alpha>I</Alpha>
  <Alpha>J</Alpha>
  <Alpha>K</Alpha>
  <Alpha>L</Alpha>
  <Alpha>M</Alpha>
  <Alpha>N</Alpha>
  <Alpha>O</Alpha>
  <Alpha>P</Alpha>
  <Alpha>Q</Alpha>
  <Alpha>R</Alpha>
  <Alpha>S</Alpha>
  <Alpha>T</Alpha>
  <Alpha>U</Alpha>
  <Alpha>V</Alpha>
  <Alpha>W</Alpha>
  <Alpha>X</Alpha>
  <Alpha>Y</Alpha>
  <Alpha>Z</Alpha>
 </xsl:template>
 <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'"/>
 <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
 <xsl:key name="keyTitle" match="Result" use="translate(substring(lastname,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/>
 <xsl:template match="/">
  <script type="text/javascript">
  function AddToColleaguesDialogCallback(dialogResult, returnValue)
  {
   if (dialogResult == 1)
   {
    alert('Contact has been added as your colleague.');
   }
  }

  function ShowOrganizationHierarchyDialogCallback(dialogResult, returnValue)
  {
  }
  
  function ViewRecentContentDialogCallback(dialogResult, returnValue)
  {
  }
  
  function ULSX84(){var o=new Object;o.ULSTeamName="SharePoint Portal Server";o.ULSFileName="portal.js";return o;}
  
  function ShowDialog(e,b,c)
  {
   ULSX84:;
   var a=[];
   if(b!=null)
    a[0]=b;
   else 
    a=null;
   var d={width:750,height:500};
   SP.UI.ModalDialog.commonModalDialogOpen(e,d,c,a)
  }
 
  $(document).ajaxStop($.unblockUI); 
 
  $(document).ready(function(){
   GetContacts('A');
  });
 
  function GetContacts(alpha) 
  {
   var qry = "SELECT Department,WorkPhone,OfficeNumber,AboutMe,PictureURL,WorkEmail,WebSite,BaseOfficeLocation,LastName,FirstName,Company,MobilePhone,PreferredName,AccountName,UserProfile_GUID, JobTitle,Size, Rank, Path, Title, Description, Write  FROM SCOPE() WHERE (\"scope\"='Associates') AND (\"DAV:contentclass\"='urn:content-class:SPSPeople') AND (\"LastName\" LIKE '" + alpha + "%') ORDER BY LastName";

   var queryXML = 
    <![CDATA["<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'> \
    <Query domain='QDomain'> \
     <SupportedFormats><Format>urn:Microsoft.Search.Response.Document.Document</Format></SupportedFormats> \
     <Context> \
      <QueryText type='MSSQLFT' language='en-us'>#qry#</QueryText> \
     </Context> \
    <SortByProperties><SortByProperty name='Rank' direction='Descending' order='1'/></SortByProperties> \
     <Range><StartAt>1</StartAt><Count>2000</Count></Range> \
     <EnableStemming>false</EnableStemming> \
     <TrimDuplicates>true</TrimDuplicates> \
     <IgnoreAllNoiseQuery>true</IgnoreAllNoiseQuery> \
     <ImplicitAndBehavior>true</ImplicitAndBehavior> \
     <IncludeRelevanceResults>true</IncludeRelevanceResults> \
     <IncludeSpecialTermResults>true</IncludeSpecialTermResults> \
     <IncludeHighConfidenceResults>true</IncludeHighConfidenceResults> \
    </Query></QueryPacket>"]]>;
   
   queryXML = queryXML.replace('#qry#', qry);
   
   var soapEnv =
    <![CDATA["<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
      <soap:Body> \
     <Query xmlns='urn:Microsoft.Search'> \
       <queryXml>" + escapeHTML(queryXML) + "</queryXml> \
     </Query> \
      </soap:Body> \
    </soap:Envelope>"]]>;   

   $.blockUI({ message: '<p>Please wait while the contacts are being loaded...</p>' });
    
   $.ajax({
    url: window.location.protocol + "//" + window.location.host + "/_vti_bin/search.asmx",
    type: "POST",
    dataType: "xml",
    data: soapEnv,
    complete: processResult,
    contentType: "text/xml; charset=\"utf-8\""
   });
   
   function processResult(xData, status) {
    var html = "";
    html += "&lt;div class='alphaBrowseNavHeader'&gt;" + alpha + "&lt;/div&gt;";
    html += "&lt;div class='rightActionsWrapper'&gt;";
    $(xData.responseXML).find("QueryResult").each(function() {
     var x = $("<xml>" + $(this).text() + "</xml>");

     /* Find value of each property */ 
     x.find("Document").each(function() {
      var department = '', workPhone = '', pictureUrl = '', workEmail = '', location = '', lastName = '', firstName = '', company = '', mobilePhone = '', preferredname = '', accountName = '', accountNameEncoded = '', jobTitle = '', responsibility = '';
      $(this).find("Property").each(function() {
       switch($(this).find("Name").text())
       {
        case 'DEPARTMENT':
         department = $(this).find("Value").text();
         break;
        case 'WORKPHONE':
         workPhone = $(this).find("Value").text();
         break;          
        case 'PICTUREURL':
         pictureUrl = $(this).find("Value").text();
         break;          
        case 'WORKEMAIL':
         workEmail = $(this).find("Value").text();
         break;          
        case 'BASEOFFICELOCATION':
         location = $(this).find("Value").text();
         break;          
        case 'LASTNAME':
         lastName = $(this).find("Value").text();
         break;          
        case 'FIRSTNAME':
         firstName = $(this).find("Value").text();
         break;          
        case 'COMPANY':
         company = $(this).find("Value").text();
         break;          
        case 'MOBILEPHONE':
         mobilePhone = $(this).find("Value").text();
         break;          
        case 'PREFERREDNAME':
         preferredname = $(this).find("Value").text();
         break;          
        case 'ACCOUNTNAME':
         accountName = $(this).find("Value").text();
         accountNameEncoded = accountName.replace('\\','%5C');
         break;          
        case 'JOBTITLE':
         jobTitle = $(this).find("Value").text();
         break;  
        case 'RESPONSIBILITY':
         responsibility = $(this).find("Value").text();
         break;  
        default:
         break;
       }
      })
      
      /* If no picture is available, display the temp place holder image */
      if(pictureUrl == '')
      {
       pictureUrl = '/Style%20Library/Images/temp_placeholder.gif';
      }          
      
      var title = $("Title", $(this)).text();
      var url = $("Action>LinkUrl", $(this)).text();
      var description = $("Description", $(this)).text()
       
      html += 
      <![CDATA["<div class='rightActionsBox'> \
       <a href='"+ url +"'><img alt='Photo of " + preferredname + "' border='0' width='158' class='rightActionsBoxImage' src='"+pictureUrl+"' /></a> \
       <div class='rightActionsCopy' sizset='122' sizcache='16'> \
        <a href='"+ url +"'><span class='name'>" + preferredname + "</span></a> \
        <table class='assocDirResultTable'> \
         <tbody> \
          <tr> \
           <td> \
            <span class='property title'>&#160;#jobTitle#</span> \
            <span class='property'><label>Work:</label>&#160;#workPhone#</span> \
            <span class='property'><label>Mobile:</label>&#160;#mobilePhone#</span> \
            <span class='property' sizset='122' sizcache='16'>#accountLink#</span> \
           </td> \
           <td> \
            <span class='property'><label>Business:</label>&#160;#company#</span> \
            <span class='property'><label>Department:</label>&#160;#department#</span> \
            <span class='property'><label>Location:</label>&#160;#location#</span> \
           </td> \
           <td class='last'><label>Ask me about</label> \
            <span class='property'>#responsibility#</span> \
           </td> \
          </tr> \
         </tbody> \
        </table> \
       </div> \
       <ul class='rightActions' sizset='123' sizcache='16'> \
        <li class='iconCal' sizset='123' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#AddToColleageCall#, null, AddToColleaguesDialogCallback);return false;'>Add As Colleague</a> \
        </li> \
        <li class='iconPeople' sizset='124' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#ShowOrganizationHierarchyCall#, null, ShowOrganizationHierarchyDialogCallback);return false;'>Browse In Organization Chart</a> \
        </li> \
        <li class='iconFlagGreen' sizset='125' sizcache='16'> \
         <a href='#' onclick='ShowDialog(#ViewRecentContentCall#, null, ViewRecentContentDialogCallback);return false;'>View Recent Content</a> \
        </li> \
       </ul> \
      </div>"]]>
      html = html.replace('#jobTitle#', jobTitle).replace('#workPhone#', workPhone).replace('#mobilePhone#', mobilePhone).replace('#company#', company).replace('#department#', department).replace('#location#', location).replace('#responsibility#', responsibility).replace('#AddToColleageCall#','"' + 'http://[Site URL]/my/_layouts/QuickLinksDialogForm.aspx?Mode=Person&amp;NTName=' + accountNameEncoded + '&amp;IsDlg=1' + '"').replace('#ShowOrganizationHierarchyCall#','"' + 'http://[site url]/my/OrganizationView.aspx?ProfileType=User&amp;accountname=' + accountNameEncoded + '"').replace('#ViewRecentContentCall#','"' + 'http://[site URL]/my/personcontent.aspx?accountname=' + accountNameEncoded + '"').replace('#workEmail#',workEmail);
      if(workEmail != '')
      {
       html = html.replace('#accountLink#','&lt;a href=\'mailto:#workEmail#\'&gt;#accountName#&lt;/a&gt;');
       html = html.replace('#workEmail#', workEmail);
       html = html.replace('#accountName#', accountName);
      }
      else 
       html = html.replace('#accountLink#',accountName);
     });
    });
    html += "&lt;/div&gt;"; 
    $("#searchResults").empty().append(html);
   }
  } 
  
  <![CDATA[
  function escapeHTML (str) {
   return str.replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }
  ]]>
  </script>
  <xsl:variable name="Rows" select="/Search_Results/All_Results/Result"/>
  <div id="assocDirResultBox" sizset="115" sizcache="16">
   <xsl:variable name="AlphabetNodes">
    <xsl:call-template name="Alphabets"/>
   </xsl:variable>
   <xsl:variable name="AlphabetName">
    <xsl:apply-templates select="msxsl:node-set($AlphabetNodes)/Alpha">
     <xsl:sort select="." order="ascending"/>
    </xsl:apply-templates>
   </xsl:variable>
   <xsl:variable name="TitleNames">
    <xsl:for-each select="$Rows[generate-id(.) = generate-id(key('keyTitle', translate(substring(lastname,1,1),$smallcase,$uppercase))[1])]">
     <xsl:value-of select="translate(substring(lastname,1,1),$smallcase,$uppercase)"/>
    </xsl:for-each>
   </xsl:variable>
   <a name="top_AssosiatesAToZ"></a>
   <div class="alphaBrowseNavBox" sizcache="16" sizset="111">
    <div class="alphaBrowseNav" sizcache="16" sizset="111">
     <xsl:for-each select="msxsl:node-set($AlphabetNodes)/Alpha">
      <xsl:if test="position() &lt;= count(msxsl:node-set($AlphabetNodes)/Alpha)">
       <xsl:variable name="char" select="child::node()[position()]"/>
       <xsl:choose>
        <xsl:when test="contains($TitleNames,$char)">
         <a>
          <xsl:attribute name="href">
           #<xsl:value-of select="child::node()[position()]"/>
          </xsl:attribute>
          <xsl:attribute name="onclick">
           GetContacts('<xsl:value-of select="child::node()[position()]"/>');
          </xsl:attribute>          
          <xsl:value-of select="child::node()[position()]"/>
         </a>
        </xsl:when>
        <xsl:otherwise>
         <span>
          <xsl:value-of select="child::node()[position()]"/>
         </span>
        </xsl:otherwise>
       </xsl:choose>
      </xsl:if>
     </xsl:for-each>
    </div>
   </div>
   <div id="searchResults">
   </div>
  </div>
 </xsl:template>
 <!-- A generic function that can be used to replace strings in a given text. Similar to String.Replace of C# -->
 <xsl:template name="ReplaceAllCharsInString">
  <xsl:param name="text"/>
  <xsl:param name="replace"/>
  <xsl:param name="by"/>
  <xsl:choose>
   <xsl:when test="contains($text, $replace)">
    <xsl:value-of select="substring-before($text,$replace)"/>
    <xsl:value-of select="$by"/>
    <xsl:call-template name="ReplaceAllCharsInString">
     <xsl:with-param name="text" select="substring-after($text,$replace)"/>
     <xsl:with-param name="replace" select="$replace"/>
     <xsl:with-param name="by" select="$by"/>
    </xsl:call-template>
   </xsl:when>
   <xsl:otherwise>
    <xsl:value-of select="$text"/>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

Lessons learned from first SharePoint 2010 implementation

Just wanted to list down the lessons learnt from our first SharePoint 2010 implementation. While some of them are quite simple ones, some were disasterous.

  1. Attempted to save a blog site as a template. SharePoint has succesfully created a sandbox wsp solution in the solutions gallery of the site collection. But it could not be activated. ULS Logs told that there were some errors in the xml. So we cleaned up the xml and rebuild the wsp (Visual Studio 2010 has a option to open wsp files and reverse engineer them). Uploaded the solution into solutions gallery. Activated the solution. At first it looked as if every thing went smooth. All fine. But later we have noticed that it corrupted the whole site collection taxanomy. We have noticed that the Site Columns and Content Types galleries were emptied during the activation. So to fix this, we had to restore from an old backup
  2. SharePoint 2010 has closed the back door ability to save publishing site as a template.
  3. SharePoint Designer 2010 often poses problems while working with page layouts. This is especially true with connected web parts and few OOB web parts such as the Note Board Web Part (comments web part). In case of connected web parts, SPD interferes and alters the connection IDs to 0000-0000-0000-000. In the case of NoteBoard Web Part, SPD does not let us to shange the title. Resolution for the Note Board Web Part is to change the properties in design mode.
  4. It is not an easy and straight process to set certain properties like Picture URL in User Profile Properties. I have written a blog explaining how to map them to AD correctly Setting up the PictureURL User Profile Property using Forefront Synchronization Service Manager in SharePoint 2010
  5. Forefront Server may cause lot of troubles in case of a single server farm
  6. Content Query Web Part's styles do not work correctly untill they are fixed. Fellow colleague Sandeep Nahta wrote a blog about fixing the issue here
  7. Microsoft has not yet provided options to automatically take backups. We still have to write scripts and use them with a automater like Task Scheduler
  8. The infamous COLD, SLOW requests that baffles users still remains. We have used SPWakeUp with Task Scheduler to overcome this.
  9. If you take a backup of a particular list using the SharePoint 2010 UI's new granular backup interface and restore it to the same location where it has been backed up from, do not expect the list to have the same list ID. It generates a new ID for the list. This can pose a problem especially if this list is being used by a lookup column and if the list gets corrupted for any reason.

--- More to come ---