Tuesday, October 20, 2009

Customizing SharePoint search results web part

In some cases the client does not want to display/see out-of-the-box search results. For example the client wants to have a search functionality only on a specific document library or wants to see all the related links by a particular author. In this case it makes sense to display the search results grouped by author. Below we will try to display the search results web part grouped by author.

Step 1. In search centre page(where you have placed search box and search results web part), click on ‘Site Actions’ and ‘Edit Page’.

Figure 1. Click on ‘Edit Page’. (Since I have already modified the ‘Search Core Results’ web part, you are able to see group by result.)


Step 2. For ‘Search Core Results’ web part, click on ‘modify shared web part’


Figure 2. Click on ‘Modify Shared Web Part’ for ‘Search Core esults’.


Step 3. Click on ‘XSL Editor…’ button. Copy all the text available. Now open notepad and paste all the content in it. Save the file as ‘SearchAll.xml’.

Figure 3. Click on ‘XSL Editor…’ button and copy the text available.


Step 4. Open SharePoint designer, Open any test site. On the test site, right click and create a new .ASPX page.

Figure 4. Click on ‘New’ -> ‘ASPX’ from the context menu.


Step 5. Open the newly created aspx page and from the menu, click on Data View -> Manage Data Sources.

Figure 5. Click on ‘Data View’ -> ‘Manage Data Sources…’ from the menu.


Step 6. From the ‘Data source Library’ click on ‘Add an XML file’. Browse and select the ‘SelectAll.xml’ file you have saved in step 3.

Step 7. Click on ‘Show Data’ from the xml file you have just now added.

Figure 6. Click on ‘Show Data’ from the context menu.


Step 8. Now drag and drop the columns that you think are necessary for grouping information. For this example, I have selected title, author, size and write.

Figure 7. Drag and drop required columns on to the page.


Step 9. From ‘Common data view tasks’, select ‘Sort and Group’. Now select ‘Author’ from the available fields. And also check ‘Show group header’ property. Click on OK.

Figure 8. Click on ‘Sort and Group’ from the context menu and select ‘author’ from the available fields.


Step 10. For column title, select ‘Hyperlink’ for ‘Format as :’. Say yes to the confirm box. In the ‘Edit Hyperlink’ dialog, change the address as ‘{url}’ and text to display as ‘{title}’.

Figure 9. Select ‘Hyperlink’ from the content menu for ‘Format as:’.



Figure 10. Edit Hyperlink dialog.


Step 11. Go to code of the .aspx page and copy all the content between tags.

Figure 11. Select xsl stylesheet from code.


Step 12. Paste the xsl copied in to the XSL editor dialog box. Click on save and apply.

Figure 12. Paste the code onto the xsl editor.



Figure 13. The result can be seen as above.


-Vighnesh Bendre

Friday, October 16, 2009

A step-by-step guide to Configuring Forms Based Authentication (FBA) in SharePoint 2007

A STEP-BY-STEP GUIDE TO CONFIGURING FORMS AUTHENTICATION IN SHAREPOINT 2007
Following is a checklist for setting up Forms Authentication in SharePoint 2007

1. Setup the membership data store
2. Add a new user to the membership data store
3. Configure SharePoint Central Administration web.config
4. Configure the SharePoint site's web.config
5. Enable Forms authentication on the SharePoint site
6. Authorize the Forms-based user to access the site
7. Login

In this article, we will be using the SQL Server membership provider to authenticate users, but you can use any membership provider that you so choose. The steps involved will be about same, but the specifics of those steps may change depending on your provider. I'm also assuming that you've already installed SharePoint and created the SharePoint site on which you're trying to enable forms authentication.

STEP 1: SETUP THE MEMBERSHIP DATA STORE
Before you can use the SQL Server membership provider, you have to set up the database that the provider uses to store member and role information. Microsoft ships a handy tool named the ASP.NET SQL Server Setup Wizard along with the .NET Framework, which will guide you through the process of creating the table structure and stored procedures required for the provider. You can launch the wizard by running aspnet_regsql.exe from the .NET Framework folder, which is normally found in the following location:


\Microsoft.NET\Framework\\aspnet_regsql.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe


When you launch the wizard, the "Welcome" screen appears and tells you all sorts of useful things about what the wizard does and the command line parameters you can use to get more options. It makes for great reading. When you've satisfied your literary pallet, click the Next button to display the "Select a Setup Option" screen (Figure 1).

Figure 1 – ASP.NET SQL Server Setup Wizard – Select a Setup Option screen

From the "Select a Setup Option" screen, choose the "Configure SQL Server for application services" option button. This lets the wizard know you want to add new tables and stored procedures to a membership database. You can also use the wizard to remove the table structure and delete all data in the database, but we don't need to deal with that right now. If you accidentally add the structure to the wrong dataset, you may have to deal with it later. Click "Next" to move to the "Select the Server and Database" screen (Figure 2).

Figure 2 – ASP.NET SQL Server Setup Wizard – Select the Server and Database screen

Enter the name of your database server in the Server textbox to let the wizard know which SQL Server it needs to access. Then enter or select a database name in the Database combo box. The combo box displays a drop down containing a list of existing databases. If you want to add the tables and stored procedures for the provider to an existing database, select the database from the list. If you want to create a new database, then just type the name of the new database directly in the combo box and the wizard will create the database automatically. You may also need to enter SQL Server authentication credentials if you connect to the database using SQL Server authentication instead of Windows authentication. These credentials are not used outside of the wizard, so it won't affect your SharePoint configuration one way or the other. Click the Next button to continue to the "Confirm Your Settings" screen.

The "Confirm Your Settings" screen displays a summary of the epoch-defining choices you've made thus far in the wizard. In other words, the server and database name. If you're feeling hesitant about either, then this is your chance to back out. When you've got your courage built up, click the Next button.

In about a second, or about one and half seconds if you're using a Virtual PC image (like me), the wizard creates all of the tables and stored procedures required by the membership provider. If it takes longer than that, you've entered a setting incorrectly and the wizard is waiting to time out (or you have a really slow machine). The wizard then displays a final status screen indicating success or failure. If the wizard fails, it details the reasons why so you can fix the problem. There are only six settings in the entire wizard (if you count option buttons as "settings") so you should have a sporting chance at troubleshooting the problem. The success screen just tells you that everything worked and to click the Finish button.

At this point, the database you selected is populated with the proper table structure and stored procedures required by the provider, so now you can add a user to the membership database.


STEP 2: ADD A USER TO THE MEMBERSHIP DATA STORE
In IIS 7.0, there is a convenient "Add User" feature that uses the membership provider configured for the website to create a user. Unfortunately, IIS 7.0 isn't available for Windows Server 2003 so, in a production environment, you're probably stuck with IIS 6.0, which doesn't have a comparable add user feature. This makes adding users a bit tedious, but here's how you do it.

1. Create a new ASP.NET web application
2. Configure the new application for Forms authentication and point it at your newly-created membership database
3. Copy the machine key element from your SharePoint site's Web.config into to your new web application
4. Add users and roles using the ASP.NET Web Site Administration Tool (if you have Visual Studio 2005 handy) or create users via the CreateUserWizard ASP.NET control.

I'm assuming you know how to create a new web site, so I'm not delving into any of the specifics of step 1. Once you have the website created, add a new Web.config to the application root and add the following configuration setting to the file:

Listing 01 – Web.config for the User Creation Website








validationKey="8E074B186056F889587355255B167DA297AD837E43FD9850"
decryptionKey="991D4DEB57A2263855C31AA1D3FF4F1AD508A53D2A94658F"
validation="SHA1"
/>



name="DemoMembershipProvider"
type="System.Web.Security.SqlMembershipProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MembershipDatabaseCNX"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
/>




name="DemoRoleProvider"
connectionStringName="MembershipDatabaseCNX"
applicationName="/"
type="System.Web.Security.SqlRoleProvider, System.Web,
Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
/>







I've bolded a few areas of Listing 01 because you will need to modify them to work on your system:

1. Replace the machineKey element from the listing with the machine key element in the Web.config from your SharePoint site. The machine key from the listing is the machineKey from my SharePoint site (on a VPC local to my box, so calm down you crazy Hax0rs) so it won't do you much good. The machineKey element changes from site to site, so make sure you get it from the site you want to configure for Forms authentication and not another site, or the SharePoint Central Administration site. You need matching machineKeys in the web application and the SharePoint site because user passwords are hashed (one way encrypted) and the hash routine uses the machine key value as part of the hashing algorithm.

2. Make sure your connection string points at the appropriate server that houses the membership database you just created. Also make sure the appropriate credentials are supplied to the connection string.

3. You can name your connection string anything you want, just make sure you use the same name later on in the connectionStrngName parameter for the membership and roleManager provider configurations.

4. Make sure your applicationName parameters match in both the membership and roleManager provider configurations. The SqlMembershipProvider allows multiple applications to use the same membership database, so a mismatched name makes the provider think there are two applications instead of one and your members and roles won't associate correctly.

5. Feel free to configure the password settings of the membership provider as you see fit.

Once you have the configuration settings in place for your web application, you need a way to add users. If you are using Visual Studio 2005, you can use the built-in Web Site Administration Tool:

1. Click the Website menu and choose the ASP.NET Configuration menu item. This launches a new web browser window that displays the Web Site Administration Tool.
2. Click on the Security tab or link.
3. Click on the Create User link and create a new user. Remember the login information because you'll be needing it later.

If you do not have Visual Studio 2005, then you can use the CreateUserWizard control to add a new user to the membership database. It's not as nice as the Web Site Administration Tool interface, but it does get the job done. Create a new page named CreateUser.aspx and add the following markup to the file:

Listing 02 – CreateUser.aspx

<%@ Page Language="C#" %>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


Create User Wizard



runat="server">




Once you save the file, navigate to the CreateUser.aspx page using your browser and create a new user. One way or another, you should have a user in the membership database at this point.

STEP 3: CONFIGURE SHAREPOINT CENTRAL ADMINISTRATION WEB.CONFIG

Now that you have a user in the membership database, you've got to let SharePoint know that the user exists and grant the user access to your SharePoint site, which means configuring your site to use Forms authentication. You configure authentication through the SharePoint Central Administration web interface, but Central Administration needs to know about your membership and roleManager providers before that configuration can take place. That means you have to add the appropriate , , and configuration elements to the Central Administration Web.config. The configuration for Central Administration is almost identical to Listing 01, but this time around you do NOT set the defaultProvider attribute on the and elements, and do not set the enabled attribute on the element. Also, the Web.config for Central Administration already contains a great deal of configuration data, so make sure you do not accidentally remove or modify any existing settings.

Open the Central Administration's Web.config. If you do not know where this is located, use the IIS Manager to determine the home directory for Central Administration and open the Web.config from that directory.

Add the following configuration elements to the Central Administration's Web.config. Please note that some element, like , , and , may already exist in the Web.config. If they do, add the child elements to the existing item.

Listing 03 – Additions to the Central Administration Web.config



"http://schemas.microsoft.com/.NetConfiguration/v2.0">
...

connectionString="SERVER=localhost;
DATABASE=MembershipDatabase;
TRUSTED_CONNECTION=true;"/>

...

...


name="DemoMembershipProvider"
type="System.Web.Security.SqlMembershipProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MembershipDatabaseCNX"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
/>




name="DemoRoleProvider"
connectionStringName="MembershipDatabaseCNX"
applicationName="/"
type="System.Web.Security.SqlRoleProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
/>


...

...



Now the Central Administration knows about your provider configurations. You would think that having the information in the "SharePoint Central Administration" would be enough, but no. You've got to add it to the Web.config in your SharePoint site as well.
NOTE: Notice that Listing 03 never refers to the machineKey. Not even once. This is because you should not mess with the machineKey in SharePoint Central Administration. Leave it alone. Do not change it. Do not delete it. Your provider does not do any encrypting or hashing from the Central Administration, so you don't have to synchronize the machineKey between the two sites. If you change the machineKey in Central Administration, bad things could happen.


STEP 4: CONFIGURE SHAREPOINT SITE WEB.CONFIG

At this point, you should be tired of messing with configuration settings, but the end is near. Go ahead and open the Web.config in the root directory of your SharePoint site, and make the same changes that you made to the SharePoint Central Administration's Web.config. Use Listing 03 as your guide. When you are finished, you need to set the defaultProvider attributes in the and elements, and the enabled attribute in the element, as shown in Listing 04.

Listing 04 – Attributes that appear in the SharePoint site Web.config (but not in the Central Administration Web.config)



"http://schemas.microsoft.com/.NetConfiguration/v2.0">
...

...

...


...

...

...



Once you've entered the configuration settings, SharePoint Central Administration and your SharePoint site have the settings required to enable Forms authentication. Time to jump back to the SharePoint Central Administration site.


STEP 5: ENABLE FORMS AUTHENTICATION ON THE SHAREPOINT SITE

You enable Forms Authentication for SharePoint sites using SharePoint Central Administration. Navigate to the Central Admin site using your browser. You can normally find a shortcut to the site in the Start menu:

Programs > Office Server 2007 > SharePoint 3.0 Central Administration

Once the Central Administration Home page is loaded, click on the Application Management link on the left hand navigation bar. You are taken to the Application Management page, which displays a variety of administration links. Click on the Authentication Providers link under the Application Security section on the right hand column of the page. The Authentication Providers page loads.


Figure 3 – Authentication Providers screen

When working in SharePoint Central Administration website, make sure the correct Web Application is selected when you are about to change configuration settings; otherwise you'll be applying changes to the wrong site. There's a small light-blue bar in the content pane of the page that displays the current Web Application URL. Make sure it's the web application on which you want to enable Forms authentication. If it's not, click the little down-arrow next to the URL and choose "Change Web Application" from the drop down list. SharePoint then displays a popup window with a list of web application from which you may choose.

Once you have the right web application selected, the Authentication Providers page displays a list of the zones in that application. Click on the name of the zone in which you want to enable Forms authentication. The Edit Authentication page displays (Figure 4).


Figure 4 – Edit Authentication Page

In the Edit Authentication page, choose the "Forms" option for Authentication Type. The page refreshes and displays the Membership provider and Role manager sections. Enter DemoMembershipProvider in the Membership provider name textbox, and DemoRoleProvider in the Role manager name textbox, then click the Save button. You are taken back to the Authentication Providers screen, but your zone should now say DemoMembershipProvider under the Membership Provider Name column. Forms authentication is now enabled on the site.


STEP 6: AUTHORIZE THE FORMS-BASED USER TO ACCESS THE SITE

Now that Forms authentication is enabled on the site, you can hit the site and see the login form (Figure 6). Microsoft spared no expense making this the blandest form you'll ever see. You will probably want to customize it so it looks a lot nicer. Maybe include some text about how the user should enter their username and password. Nobody will read it, but it definitely makes a login form look like a login form. Anyway, if you enter your username and password, you will be successfully authenticated and then promptly denied access because you have no authorization to be in the site. So, how do you get authorization? You have to use the Site Collection Administrator account.

You may remember setting up a Site Collection Administrator when you first created the site a while back, and it was almost certainly a Windows user account. If you extended the site and have both a Windows zone and a Forms authentication zone, then you can login to the Windows zone and setup the Forms user in Site Settings as you would any other user.

If you have not extended the site, then you've only got one zone and its using Forms authentication. As such, the Windows account associated with the site collection administrator is effectively useless and you need to change the site collection administrator over to a Forms based account. To do this, open SharePoint Central Administration and click on the Application Management link in the left navigation menu. When the Application Management page displays, click the Site Collection Administrators link under the SharePoint Site Management section in the left-hand column of the page. The Site Collection Administrators page displays (Figure 5).


Figure 5 – Site Collection Administrators Page

On the Site Collection Administrators page, make sure that correct site collection is selected. Then, enter the username of the user you created back in Step 2 in the Primary Site Collection Administrator textbox. Click on the Check Names icon (the little red guy with a check mark) next to the textbox. It may take a few seconds, but the page should underline the text in the textbox indicating that the username is valid. If the username is not valid, the page puts a red squiggly line under the username and informs you that the user was not found. If the user is not found, make sure you typed the name correctly. If the issue persists, go back and check your configuration settings to ensure the connection string is valid and there are no typos.

Click on the OK button to save the changes. Your Forms authentication account is now a Site Collection Administrator who has authorization to visit the site. You can use that account to get into the site and setup additional Forms authentication users in Site Settings.

STEP 7: LOGIN
When you access the site, you are presented with the previously-mentioned default SharePoint login page (Figure 6). Enter your username and password, and then click the Sign In button. You should be authenticated and authorized, and the site should display as you would expect.


Figure 6 – SharePoint Forms Authentication Login Page


- Vighnesh Bendre

Thursday, October 15, 2009

Sharepoint search customization - Search-as-you-type (SayT), Find-As-You-Type(FAYT)

I was going through some case studies of search customizations in Sharepoint 2007. I stumbled upon something new!! JQuery for search in sharepoint. That is for implementing 'Search-as-you-type' (SayT) or Find-as-you-Type (FAYT) in sharepoint 2007. It looked so simple and prompted me to give it a try right away. This example uses JQuery and sharepoint web service to get the results for what you are typing. All at client side. No server side code needed. And some of the properties are configurable. Which makes it easier even after you deploy this on production. ;)

I implemented it right away, below are some of the screenshots.

As soon as you type 3 characters (can be configured), the JQuery will bring out all matching results.


You can also use the arrow button (or mouse pointer) and choose the right result and hit enter.



Steps to implement
Now coming back to the steps for implementing it. It is fairly simple, and can be done in a matter of few minutes.

1. Copy the below code,
















Go Search








2. Add a new Content Editor Web Part, which is available in SharePoint out-of-the-box, to a page.
3. Modify the newly added web part, use the Source Editor button in the properties task pane to add the downloaded code.
4. You can give the web part a nice title, Quickest Search.



So, with just these 4 steps you can implement SayT (Search-as-you-Type) functionality. There are some configurable properties which I am sure you will figure out by going through the script.

- Vighnesh Bendre

Tuesday, August 4, 2009

SharePoint (MOSS) AssetPicker (AssetURLSelector) customization

Couple of weeks back I was asked to customize the asset picker to suit client's requirements. The requirement was something like this : there is an ASP.net application running on application server, on click of a button, it should open up the assetpicker from MOSS (SharePoint environment). After the user selects a link and clicks on "OK" button in asset picker, the selected URL must be populated in a label.

The challenges faced are related to different server farms of hosted applications. asp.net application is on application server and assetpicker is on SharePoint server.

Below are the steps followed to achieve the desired result.

1. CALLINGPAGE.ASPX (this is an plain asp.net application page)

This page is part of asp.net application which will be hosted in application farm. This page consists of a “Browse” button on click of which the asset picker will be displayed. To achieve the desired result, we have put an iFrame in the HTML code. This iFrame will not be displayed to the user, but it will be used only to redirect the control to the AutoLaunchPickerDialog.aspx page.





Once the user clicks on the “Browse” button, OpenPicker() javascript function will be called. This javascript function will find the iFrame control and assign the source property with configurable value.


function OpenPicker()
{
document.getElementById("assetSelectorFrame").src = 'GetConfigValueforURL';
}


The configurable value for the source of iFrame is defined in web.config file as following.





The CallingPage.aspx page also has a label “lblAssetURL” which will be assigned with the selected URL by “AssetSelectorSelected.htm” page.

2 AUTOLAUNCHPICKERDIALOG.ASPX PAGE

AutoLaunchPickerDialog.aspx page will put under the Layouts folder in 12 hive folder of SharePoint server. In this page an instance of AssetURLSelector is created. On Pre render event of this page, a method is called which will register a client start up script. This start up script will get the script to launch the asset picker by executing “GetClientLaunchPickerReference” method of asset URL selector. A client call back script is also registered for the asset URL selector. The asset URL selector’s “GetClientLaunchPickerReference” method expects a parameter of the URL. This URL can be a already selected URL or it will point to the current location of the page.


private AssetUrlSelector assetSelector;
private string ScriptGetAssetUrlValue = "";

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
assetSelector = new AssetUrlSelector();
GenerateAssetUrlSelectorLaunchScript();
}

private void GenerateAssetUrlSelectorLaunchScript()
{
if (Request.QueryString["SelectedPath"] == "")
{
ScriptGetAssetUrlValue = "window.location.href";
}
else
{
ScriptGetAssetUrlValue = "'" + Request.QueryString["SelectedPath"] + "'";
}
this.assetSelector.Page = this.Page;
this.assetSelector.ID = "assetUrlSelector";

this.assetSelector.ClientCallback = "function(newAssetUrl, newAssetText, configObject, returnedValue) { window.location = '" + Request.QueryString["targetUrl"] + "' + newAssetUrl; }";

ClientScript.RegisterStartupScript(typeof(AutoLaunchPickerDialog), "Loading", "");
}



To the asset URL selector’s “ClientCallback” property, a javascript function is assigned. This function will assign newly selected URL to the location which is part of the query string. This query string will contain the location to redirect after the URL is selected. This will be the “AssetSelectorSelected.htm” page.

3 ASSETSELECTORSELECTED.HTM PAGE

The asset selector selected page is in application server. This html page will receive the selected URL as a query string from “AutoLaunchPickerDialog.aspx” page. On load of this page, a javascript function will be called. This function will read the query string and assign the value to the label in “CallingPage.aspx” page. Thus completing the entire process.


function Update()
{
window.parent.document.getElementById("lblAssetURL").innerHTML = getQueryStringValue("selectedAssetURL");
}

function getQueryStringValue(key)
{
searchString = window.location.search.substring(1);
searchStringSplit = searchString.split("&");
for (count=0;count