Tuesday, April 17, 2012

SharePoint 2010 Code Tips – Determining if a Content Type is Published and other Tips

Technorati Tags: ,,

In this post I will showing you different code snippets that may be useful when developing SharePoint applications. The code accomplished various things and I will give you an idea how you may want to use them in your applications. The code is posted “AS IS” with no warranties and confers no rights.

Determining if a content type is published

The Content Type Publishing feature in SharePoint 2010 is very useful for the management and reuse of content types. It enables you to define a content type on one site collection and publish the content types to other site collections. More information: Content Type Publishing in SharePoint 2010.

Typically, the published content types are read only and can only be inherited from. So you may need some code to determine if a content type is published. The following code does this by examining the SPContentType.XmlDocuments collection. If the collection contains an XML document with a key of “Microsoft.SharePoint.Taxonomy.ContentTypeSync”, then it is either a published content type or derived from one. In order to decipher which is which, then you must compare the content type ID that is listed as an attribute in the XML document with the content type you are interrogating. If the two match then the content type has been published from the publishing hub.

public static bool IsContentTypePublished(SPContentType contentType)
{
    bool flag = false;
    string str = contentType.XmlDocuments["Microsoft.SharePoint.Taxonomy.ContentTypeSync"];
    if (!string.IsNullOrEmpty(str))
    {
        XmlDocument document = new XmlDocument();
        document.LoadXml(str);
        XmlAttribute attribute = document.DocumentElement.Attributes["ContentTypeId"];
        if (attribute != null)
        {
            try
            {
                flag = new SPContentTypeId(attribute.Value).Equals(contentType.Id);
            }
            catch (ArgumentException)
            {
                flag = false;
            }
        }
    }

    return flag;
}

 

Retrieving schema information for SharePoint built-In fields

Many developers use Visual Studio to develop and deploy SharePoint solutions that create document libraries and  content types. More information: Creating custom content types. The definitions for these can contain FieldRef elements to existing built-in SharePoint fields and developers need a way to obtain information from the schema xml definition for the field. There are tools you can buy or download for free to obtain this information. However, you can use the simple code to run in a console application to obtain this information given a site URL and the internal name of the field. The code uses reflection to obtain the GUID of the built-in field using the internal name and then uses the GUID to obtain the schema.

public static string GetSchemaXmlForBuiltInField(string siteURL, string fieldName)
{
    string schema = string.Empty;
    Guid fieldID = Guid.Empty;

    var result = from f in typeof(SPBuiltInFieldId).GetFields()
                    where string.Equals(f.Name,fieldName,StringComparison.OrdinalIgnoreCase)
                    select f;

    if (result != null && result.Count() == 1)
    {
        FieldInfo fi = result.FirstOrDefault();
        fieldID = (Guid)fi.GetValue(fi);
    }

    using (SPSite site = new SPSite(siteURL))
    {
        using (SPWeb web = site.OpenWeb())
        {                   
            SPField builtInField = web.AvailableFields[fieldID];
            schema = builtInField.SchemaXml;                  
        }           
    }

    return schema;  
}

 

Setting default values for metadata fields and locations

A nice feature in SharePoint 2010 is being able to set default values for fields per location or folder. This is accessible from the list settings page under “column default value settings”.

 

A scenario may arise where you might want to have different default values for a metadata field per folder. Setting a default value for a managed metadata field is much different than other types of SharePoint fields. The following code shows how to do this using the Microsoft.Office.DocumentManagement.MetadataDefaults class. The method takes the URL to the site, list name, metadata field name and the relative URL to the folder. The code can be modified to accept the term group name, term set name and the default term you want to use. This example shows hard coded values these.

public static void AddDefaultMetaDataForLocation(string siteUrl,
    string listName, string folderLocation, string metadataFieldName)
{

    using (SPSite site = new SPSite(siteUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {

            SPList list = web.Lists[listName];
            string folder = web.GetFolder(folderLocation).ServerRelativeUrl;

            TaxonomySession sessions = new TaxonomySession(web.Site);
            TermStore store = sessions.TermStores["Managed Metadata Service"];
            Group group = store.Groups["Cars"];
            TermSet productenTermSet = group.TermSets["Cadillac"];
            TermCollection terms = productenTermSet.GetTerms("STS", true);
            Term defaultValue = terms[0];

            string defaultValueText = "-1;#" + defaultValue.Labels[0].Value +
                TaxonomyField.TaxonomyGuidLabelDelimiter + defaultValue.Id.ToString();

            MetadataDefaults defaults = new MetadataDefaults(list);

            defaults.SetFieldDefault(folder, metadataFieldName, defaultValueText);

            defaults.Update();
        }

    }

}

 

More Code Tips Soon

SharePoint has many features and figuring out how to use these features in your application can take time. Hopefully these code tips can help speed up that process for you. I will try to post more of these in the future.

Thursday, March 29, 2012

SharePoint 2010 Search Centers Explained

Technorati Tags: ,,

SharePoint 2010 offers an Enterprise Search Center site template. Many users question the usefulness of this site template given the fact that SharePoint offers a plethora of search web parts. These web parts give a search administrator substantial flexibility in designing custom search functionality anywhere within the the SharePoint farm. However, with all this flexibility there comes a cost, and this cost is inconsistency on how users conduct their searches in SharePoint. One of the best books on searching is  "Search User Interfaces" by Marti Hearst. One of the design guidelines for search interfaces is striving for consistency. The Enterprise Search Center site template provides a consistent location and process of searching but also provides the flexibility to create different types of search experiences for different search audiences. The Enterprise Search Center site template also gives the administrator control on what types of search experiences are designed through SharePoint’s content publishing management infrastructure. In this post I will explain how the Enterprise Search Center site template provides searching consistency and enables a more powerful search experience for your users.

Creating a Enterprise Search Center Site

When creating a Search Center site SharePoint 2010 offers three search center templates.

  • Enterprise Search Center: This template requires the Publishing Infrastructure feature to be activated since it is a publishing site. A publishing site contains a system library called pages which contains different types of publishing pages.  The Enterprise Search Center utilizes template publishing pages.The default page layout contains a tab control where a search administrator can add additional tabs. Each tab can represent a different type of search for different audiences. Since this a publishing site the creation of new pages can leverage scheduling, caching, workflow and other publishing features.
  • Basic Search Center: Offers only three basic search pages and does not contain multiple tabs for different searches. Also it is not a publishing site and cannot leverage publishing features. The Basic Search Center does enable the addition of custom search pages.
  • Fast Search Center: This template is available even without FAST Search for SharePoint installed. It will only function if FAST Search server is installed. A Fast Search Center has all the same functionality as the Enterprise Search Center but works exclusively with Fast Search for SharePoint.

To create a new Enterprise Search Center, make sure the “SharePoint Server Publishing Infrastructure” site collection feature is activated. Next, go to the Site Actions tab and click New Site. Finally, choose the Enterprise Search Center template and enter a title and a URL. Remember, if you want to customize your Search Center by adding new search pages you must choose the Enterprise Search Center template.

 

Search Center UI Components

The Search Center UI consists of three types of Web Part pages.

  • Basic Search Page. The page where users will conduct standard searches. It includes the Search Box Web Part and a tab control to allow navigation among different types of searches.
  • Advanced Search Page. The page where users conduct more complicated searches. It is accessed from the Basic Search page.
  • Search Results Page. The page where search results are displayed and where most customization occurs. This can be a standard results or people results page.

 

The Basic Search Page/Box

The Basic Search page is the search starting point for users.In addition to the Search Box Web Part, the Basic Search Page includes tabs that enable users to navigate to other search pages that focus on other search scopes. It also has links to the Advanced Search page and to a Preferences page where users can set search preferences, such as enabling or disabling search suggestions and language choice. The language setting is activated for keywords and the ranking of results. Tabs, preferences, and the Advanced Search feature are all configurable using the Search Box Web Part.

 

 

Configuring the Basic Search Page/Box

You can edit the default.aspx  page for the Enterprise Search Center and change the settings for the search box web part. The search box web part can be configured to add more options based on your user’s needs. For example, if your user needs to create more sophisticated searches you can enable the “Advanced” link which will take them to a standard Advanced Search page. You can enable the display of scopes to help users limit the content they are searching on. Finally you can create your own custom advanced search or search results pages and configure this web part to navigate to these. The screen shot below shows you all the different options you can enable for this web part.

 

Advanced Search Page

The Advanced Search page contains the Advanced Search Web Part. This page enables users to submit searches using multiple terms, phrases, and result types. Users can also exclude terms, indicate language specifications, and include property restrictions using Boolean logic.

The Result Type drop-down box enables users to specify what kind of documents to include in the results. Result types include such file types as Word, Excel, or PowerPoint.

The Property Restrictions drop-down box enables selection of managed properties to restrict the results based on comparison operators such as Contains, Equals, or Does Not Equal. Multiple property restrictions can be combined using the OR and AND Boolean operators.

You might discover during the needs assessment phase that your users might not require an Advanced Search page or they might just need certain parts of the Advanced Search Web Part. The challenge with this Web Part is that it might provide too many options and confuse the user. For example, different types of keyword options, such as All of these Keywords or Any of these Keywords might not produce results. The use of this Web Part requires education so the user knows how to use it effectively. In the screen shot below you can see most of these options can be hidden. By making only certain functions available, you can tailor the Advanced Search UI to the user’s knowledge of how search works.

 

  • The Search Box section enables and disables different types of term searches and then provides each with a custom label.
  • The Scopes section enables and disables different types of drop-down boxes, such as scopes, languages, or the result types. The result types are used to narrow your search to a particular category of document, such as Office documents.
  • The Properties section enables and disables the capability to conduct property (managed property) searches. It enables the customization of the sections label and also defines properties that a user can choose from using an XML definition file. Finally, it permits setting the location of a Custom Search Results page if you choose to create one.

 

The Search Results Page

The Search Results page is where you can add, remove or re-locate the many search Web Parts to different Web Part zones. There are many web parts on this page by default. At a minimum your results page should contain the document results and search statistics. It is also recommended to provide mechanisms for exploring results further using features such as paging, sorting, refining  and generating federated results from other sources. In a future post I will explain the function and purpose of all the various search web parts available in SharePoint 2010.

 

Customizing your Search Center

One the most powerful features of a search center is the ability to create your own search pages and associate these with a custom tab. Creating new types of search experiences and adding tabs to the search center gives a user a central and consistent place to search. The first step in creating a custom search is to to create some new search pages. From your Enterprise Search Center select “Site Actions” then “More Options”. This will display a dialog. Select “Pages” and then “Publishing Page”. Click the “Create” button. Here you can select the “Search Box” page. Once you have created this page you can customize the settings, for example enabling the display of scopes. Save the customizations.

 

Adding a new tab to your Search Center

Your next step is to add a new tab to your search center. Click on the “Site Actions” menu and select the “Edit Page” menu item. Here you will see a “Add New Tab” link. Click on this link to add a new tab.

Now enter the name of the tab and the new publishing page you created previously and possibly a tool tip.

So now you will have a new tab and a customized search box. This tab could be for different types of search audiences. For example in this case it was for Discovery managers. You could possibly create one that just searched for documents and did not return list items. The search results can be limited to certain scopes. A great blog post about customizing your search center can be read on this blog here "Advanced Search for SharePoint 2010 Hold and eDiscovery".

One Search Center to Unite them All

This post has shown you how to leverage the Enterprise Search Center to give users a consistent search experience and a central location to conduct searches. This lowers search training costs and the amount of time it takes to find content. The publishing feature and the many search web parts give an administrator a very powerful tool to develop custom searching solutions with a consistent UI. Additional information about SharePoint search concepts is provided in this blog and can be useful when making decisions on what capabilities you want to expose in your search center. I recommend you become familiar with the concepts and the many search web parts so you can take full advantage of the tools SharePoint 2010 gives you to effectively search for content.

SharePoint 2010 Search Scopes Explained

SharePoint 2010 Search Query Suggestions Explained

Tuning SharePoint Search Relevance with Ranking Models