woensdag, juni 06, 2007

Creating Managed Properties for use in SharePoint Server Enterprise Custom Search through Code

Use the following Code to add Managed Properties in Code, the Managed Properties are created from crawled properties (like an infopath published form)

//Get search Schema
ServerContext serverContext = ServerContext.GetContext("SharedServices1");
SearchContext searchContext = SearchContext.GetContext(serverContext);
Schema schema = new Schema(searchContext);

//Get the list of properties (here from a published infoPath Form), you want to use in search
StringCollection infoPathFormProperties = GetData.GetAllInfoPathPublishedFields();
// Create new ManagedProperties
foreach (string infoPathFormProperty in infoPathFormProperties)
string managedPropertyName = infoPathFormProperty;
string infoPathFormPropertyPublished = string.Format("ows_{0}", infoPathFormProperty); //infopath published fields will be added as ows_[NAME]

// If you create a prop that already exists, you will get an SqlException (duplicate key),so you need this check
if (!schema.AllManagedProperties.Contains(managedPropertyName))
ManagedProperty newManagedProperty = schema.AllManagedProperties.Create(managedPropertyName, ManagedDataType.Text);

// Get the (crawled) property you want to map in the ManagedProperty
CrawledProperty cprop = null;
foreach (CrawledProperty prop in schema.QueryCrawledProperties(infoPathFormPropertyPublished, 1000, Guid.NewGuid(), string.Empty, true))
//schema.GetCrawledProperty(Guid.NewGuid(), infoPathFormPropertyPublished, 0); //can't use this, you need also need the Guid and variantType, and you only know the name
//QueryCrawledProperties will be filtered on CONTAINING infoPathFormPropertyPublished value, so extra check if the Name is equal!
if (prop.Name == infoPathFormPropertyPublished)
cprop = prop;

if (cprop != null)
// Map the crawled prop to the Managed Prop
MappingCollection mappings = new MappingCollection();
mappings.Add(new Mapping(cprop.Propset, cprop.Name, cprop.VariantType, newManagedProperty.PID));


// Set Some other properties
newManagedProperty.FullTextQueriable = true;
newManagedProperty.EnabledForScoping = true;
MessageBox.Show(string.Format("Published Infopath field {0} not found",infoPathFormPropertyPublished));

MessageBox.Show(infoPathFormProperty +" already exists");


1 opmerking:

Martin zei


it's possible and how retrieve values for ManagedProperty or CrawledProperty?

really thanks