Wednesday, 14 September 2011

How to create a managed property programmatically in Sharepoint 2010

Managed Properties have become a very powerful weapon in the Sharepoint 2010 search environment.

You can enhance the end-user search experience by mapping crawled properties to managed properties. Crawled properties are metadata (such as author, title, or subject) that are extracted from documents during crawls. Managed properties can appear in refined searches and help users perform more successful queries.

Refined searches can be performed only on managed properties, not crawled properties. To make a crawled property available for refined search queries, you must map the crawled property to a managed property. You can map multiple crawled properties to a single managed property or map a single crawled property to multiple managed properties. If a managed property has multiple crawled properties mapped to it, and a document contains values for more than one of the crawled properties, the order in which the properties are mapped and their priority determine the value of the managed property.

I think the best way to see how this work, it is by displaying an example.

1- Go to Visual Studio 2010->New Project->C#->Windows-> Console Application and call it netsourcecodeManagedPropertyCreation, click OK

2- Add the following dlls in your reference:

  • Microsoft.SharePoint

  • Microsoft.Office.Server

  • Microsoft.Office.Server.Search

To create a managed property with the argument passes replace the code in Program.cs for this code:

using System;
using System.Collections;
using System.Text;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;
namespace ManagedPropertiesSample
    class Program
        static void Main(string[] args)
                SearchContext context;
                using (SPSite site = new SPSite("http://YOUR_SHAREPOINT_SERVER"))
                    Context = SearchContext.GetContext(site);
                Schema sspSchema = new Schema(context);
                ManagedPropertyCollection properties = sspSchema.AllManagedProperties;
                ManagedProperty _mpNewProperty = properties.Create(args(1),ManagedDataType.Text);
            catch(Exception ex)