SharePoint and other geeky stuff

Menu

Skip to content
  • Home
  • About Me

Tag Archives: Managed Metadata Service

Search CAML query with Managed Metadata

Posted on April 10, 2013 by cann0nf0dder

  • Part 1 – Setting up Managed Metadata Service
  • Part 2 – Explaining how to use the Term Store
  • Part 3 – Creating a Site Column with managed Metadata (gotchas with List Definitions)
  • Part 4 – Search Refiners with Managed Metadata
  • Part 5 – Search CAML query with Managed Metadata
  • Update – Creating a Site Column with Managed Metadata using Javascript.

In this final blog of this series, I will show you how to perform a CAML Query against a list for Managed Metadata Column. Now I’ve realized over the past week while I’ve been writing these blogs, that you might assume that I’d be using the Search Engine to obtain my results. Actually I’m performing a SPQuery on a SPList. (Perhaps I will create an additional post later how to actually “Search” via code.

The trick with performing a CAML query again a list for Managed Metadata is using <In> and listing every wssIds for the main term, and all its children. Normally when you perform a CAML query you would enter something similar to the following

<Where><Eq><FieldRef Name="Title"/><Value>File</Value></Eq></Where>

If you performed the above on a Managed Metadata column it would only bring back the one value, not the children.

If you remember from my last blog, the Managed Metadata column was called Location. It was Term Set based on Continents and the Countries within them. So to perform a query of Europe and all its child terms, you would first need to get the ID of the Term “Europe” then get all the children ID terms (e.g, Albania, Andorra, Anguilla etc).

Once we have the ID’s you then perform a CAML query similar to below.

<Where><In><FieldRef Name="Location" LookupId="TRUE"><Values><Value Type="Integer">13</Value><Value Type="Integer">3</Value><Value Type="Integer">9</Value></Values></In></Where>

Basic WebPart with Taxonomy Picker performing a CAML Query.

I’m going to walk through the steps that will allow you to obtain the Metadata Term, and then obtain all the children, before performing a query on a list. My list is called managed Metadata Demo, and I have a Managed Metadata Column on the list called Location.

  • Create an Empty SharePoint project. Make it a Farm Solution, and point to your SharePoint site with your document library containing your Managed Metadata column.
  • Add the following References Microsoft.SharePoint.Taxonomy.
  • Right click the project and select Add >New Item
  • From the Add New Item dialog, select Web Part. (Not Visual Web Part)
    I called my Web Part WPFilter.
  • Add the Using statement using Microsoft.SharePoint.Taxonomy; to the top of the c# class WPFilter.
  • Add the following private variables.
    //Control for user to pick a Location
     private TaxonomyWebTaggingControl termPicker;
     //Button to search.
     private Button findButton;
     //Label Control for results
     private System.Web.UI.WebControls.Label result;
     //Taxonomy Field for Location
     private TaxonomyField location;
     //Data Grid to display Data
     private DataGrid dataGrid;
    
    • Add your CreateChildControls() method.
      
      protected override void CreateChildControls()
       {
       try
       {
       //Obtain location Field as it is list.
       location = SPContext.Current.Web.Lists.TryGetList("Managed Metadata Demo").Fields["Location"] as TaxonomyField;
       //If was site Column.
       //location = SPContext.Current.Site.RootWeb.Fields["Location"] as TaxonomyField;
       //If location found.
       if (location != null)
       {
       //Create Picker.
       termPicker = new TaxonomyWebTaggingControl();
       //Grab SspID
       termPicker.SspId.Add(location.SspId);
       //Grab TermSetId
       termPicker.TermSetId.Add(location.TermSetId);
       termPicker.AllowFillIn = false;
       termPicker.IsMulti = false;
       //Set Width.
       termPicker.Width = 200;
       //Add Control
       this.Controls.Add(termPicker);
       this.Controls.Add(new LiteralControl("<br/>"));
       //Add Button.
       findButton = new Button();
       findButton.Text = "Search";
       findButton.Click += new EventHandler(findButton_Click);
       this.Controls.Add(findButton);
       //Add results label
       this.Controls.Add(new LiteralControl("<br/>"));
       result = new System.Web.UI.WebControls.Label();
       this.Controls.Add(result);
       this.Controls.Add(new LiteralControl("<br/>"));
       //Add DataGrid.
       dataGrid = new DataGrid();
       this.Controls.Add(dataGrid);
       }
       else
       {
       //Throw Error message
       Controls.Add(new LiteralControl("Unable to find field Location."));
       }
       }
       catch (Exception ex)
       {
       //Throw Error message
       Controls.Add(new LiteralControl("There was an error. " + ex.ToString()));
       }
       }
      
      • Now the method for findButton_Click
      void findButton_Click(object sender, EventArgs e)
              {
                  result.Text = "";
                  //This returns as Name|GUID;
                  string selectedTermValue = termPicker.Text;
                  int seperatorIndex = selectedTermValue.IndexOf("|");
                  if (selectedTermValue != string.Empty && seperatorIndex != -1)
                  {
                      //Get the TermID.
                      Guid termId = new Guid(selectedTermValue.Substring(seperatorIndex + 1));
                      //Get a TaxonomySession.
                      TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
                      if (session.DefaultKeywordsTermStore != null)
                      {
                          //get the default metadata service application
                          /*Function GetWssIdsOfTerm
                           * Site - The SPSite object that cotains the taxonomy hidden list.
                           * termStoreId - A Guid object that uniquely identifies the TermStore object
                           * termSetId - A Guid object that uniquely identifies the TermSet Object
                           * termId - A Guid object that uniquely identifies the Term
                           * includeDecendants - A boolean value that must be set to true if you would like the list of
                           *                     item Ids of descendant Term Obejct to also be included in the results.
                           * limit - The maximum number of list items IDs to return.
                           *
                           */
                          int[] wssIds = TaxonomyField.GetWssIdsOfTerm(SPContext.Current.Site, session.DefaultKeywordsTermStore.Id, location.TermSetId, termId, true, 100);
                          if (wssIds.Length > 0)
                          {
                              //Pass to SPQuery and display results.
                              FillDataGrid(wssIds);
                          }
                          else
                          {
                              //No results
                              result.Text += "\n Sorry. No results could be found.";
                          }
                      }
                      else
                      {
                          //Unable to find default keyword.
                          throw new Exception(string.Format("DefaultKeyWordTermStore not found in this site {0]", SPContext.Current.Site.Url));
                      }
                  }
              }
      
      <ul>
      	<li>
      <div>Finally add the code to grab the CAML query, perform it, and add the results to the data grid.</div>
      
      
      private void FillDataGrid(int[] wssIds)
       {
       //using System.Text;
       StringBuilder values = new StringBuilder();
       //Loop through ID's and create CAML QUERY loop.
       for (int i = 0; i < wssIds.Length; i++)
       {
       values.Append("<Value Type=\"Integer\">");
       values.Append(wssIds[i].ToString());
       values.Append("</Value>");
       }
       //Complete the CAML Query String.
       string strQuery = String.Format("<Where><In><FieldRef Name=\"Location\" LookupId=\"TRUE\"/><Values>{0}</Values></In></Where>", values.ToString());
       //Get List
       SPList list = SPContext.Current.Web.Lists.TryGetList("Managed Metadata Demo");
       if (list != null)
       {
       SPQuery query = new SPQuery();
       query.Query = strQuery;
       //View Fields
       query.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Title'/><FieldRef Name='Location'/>";
       SPListItemCollection items = list.GetItems(query);
       //Results of Query to show User Query made.
       result.Text = System.Web.HttpUtility.HtmlEncode(strQuery);
       if (items.Count < 1)
       result.Text += "\n Sorry. No results could be found.";
       //Add to grid and bind.
       dataGrid.DataSource = items.GetDataTable();
       dataGrid.DataBind();
       }
       else
       {
       result.Text = "Sorry. Unable to find the list Managed Metadata Demo";
       }
       }
      [/soucecode]
      </li>
      	<li>
      <div>Now run your code. Add your web part to a page. It should look similar to below.</div>
      <img alt="" src="https://cann0nf0dder.files.wordpress.com/2013/04/041013_2046_searchcamlq3.png" /></li>
      	<li>
      <div>If I enter Europe, or use the label picker to find Europe and click Search, I will get a result set of all documents tagged with Europe or within the Term children. Also note the query actually being called in the result label.</div>
      
      <Where><In><FieldRef Name="Location" LookupId="TRUE"/>
       <Values>
       <Value Type="Integer">13</Value>
       <Value Type="Integer">1</Value>
       <Value Type="Integer">2</Value>
       <Value Type="Integer">3</Value>
       <Value Type="Integer">8</Value>
       </Values>
       </In>
      </Where>
       

      • As you can see from the results above, it has returned United Kingdom, Switzerland, Turkey and Europe documents. Hopefully you would you a ListViewByQuery webpart or display your data a little better than this.

      This concludes my Managed Metadata Series. Hope you have learnt something new. I’m hoping to write a bonus post on this series that will actually perform a Search query on Managed Metadata.

Advertisement

Share this:

  • Tweet
  • Email
  • WhatsApp
  • More
  • Pocket
  • Print
  • Share on Tumblr

Like this:

Like Loading...
Posted in Development, SharePoint | Tagged Managed Metadata Service, Search, SharePoint 2010 | 1 Comment

Search Refiners with Managed Metadata

Posted on April 7, 2013 by cann0nf0dder

  • Part 1 – Setting up Managed Metadata Service
  • Part 2 – Explaining how to use the Term Store
  • Part 3 – Creating a Site Column with managed Metadata (gotchas with List Definitions)
  • Part 4 – Search Refiners with Managed Metadata
  • Part 5 – Search CAML query with Managed Metadata.
  • Update – Creating a Site Column with Managed Metadata using Javascript.

If we open up our Search Centre and query on some data, down the left hand side of the search results is a search refinement panel. This panel gives a breakdown of some metadata found within the search results which allows you to filter it further. If you look at the image below, the default search refiners are Result Type, Site, Author, Modified Date,
and Location. Now location is actually our managed metadata column. However this isn’t a custom one I’ve made, this is created by default by SharePoint. If I had something else in search that was more popular in the results that would have been there instead. So there is no guarantee that will be there for each search.

To get the search to work, you first need to ensure you have put data in a list with the columns you wish to search on, and perform a crawl in Central Administration for any results to show up in search. There are two different types of Search Refiners you can create ManagedPropertyFilterGenerator, or a TaxonomyFilterGenerator.

A ManagedPropertyFilterGenerator can be used with a Managed Metadata Column, however it displays the results as exact matches. What do I mean by that? Well if you remember in my previous blog I had a Term Set called Countries. Inside countries I had a list of Continents, and then countries underneath the Continents.

With a ManagedPropertyFilterGenerator if I selected Europe as my filter, it will only display items that have been tagged with Europe. However, what we are really asking for it any item that is in Europe. Using a TaxonomyFilterGenerator by filtering on Europe we will receive all items tagged with Europe, but also other item that are tagged with countries within Europe, such as United Kingdom, Andorra etc.

Setup for ManagedPropertyFilterGenerator refiner

This wasn’t going to be part of the blog, but as there is a different setup to get your ManagedPropertyFilterGenerator working to the TaxonomyFilterGenerator, I thought I would show you.

  • Create your site column, it can be any type of column, but for simplicity use a Choice column. Add some choice values.
  • Create a List, and add your choice column to it.
  • Then add items to your list. My example is below.

  • Now open up Central Administration > Application Management > Manage Service Applications > Search Service Application then click on Content Sources

  • On the Manage Content Sources page, click on the right of Local SharePoint Site and select Start Full Crawl

  • Once the crawl has completed in the Left Navigation Menu, under Queries and Results click Metadata Properties.
  • On the Metadata Property Mappings page click New Managed Property
  • Fill in the Property Name: DemoChoice
  • Under the Mappings to crawled properties click the button Add Mapping
  • In the dialog box, under Crawled property name type DemoSearchChoice. Click Find. Select the crawled property ows_DemoSearchChoice(Text) and click OK.

  • Save the Metadata Property Page.
  • Now that you have set up the Metadata Property, you need to perform a full crawl again. Follow the steps from earlier to do this.
  • Once the full crawl had completed, the way to check if it will work in a search it to navigate to your search center.
  • Type in <Name Of Property>:<Value> so for instance my example would be DemoChoice:Red and only the items tagged with Red will appear in my result set.

Set up for TaxonomyFilterGenerator refiner

For the TaxonomyFilterGenerator you don’t actually need to do anything apart from add some data to the list with the column and perform a full search. All managed Metadata columns are added to search Managed properties automatically. Unfortunately I can’t show you in a test, as it’s not quite the same as the Managed Property Generator.

Creating the refiner

  • Navigate to your search center results page. Easiest way is to perform a search. Once there edit the page.
  • Find the Refinement Panel on the left of the page, and edit the webpart.
  • Under the Refinement section there is the Filter Category Defintion, and the Use Default Configuration. The Filter Category Definition is what you will be adding your custom refiner to. However if you do not untick Use Default Configuration it doesn’t matter what you change the Filter Category Definition to, it won’t pick up the change.

If you take a copy of the Filter Category Definition you will be able to see what we are dealing with. It does look quite scary, but all it is, is a collection of <Category> and we just have to create one for our Taxonomy. Details can be found on the Microsoft Site on what can be included in a Category section.
http://msdn.microsoft.com/en-gb/library/ee819920(v=office.14).aspx
http://msdn.microsoft.com/en-gb/library/ff625183(v=office.14).aspx

Creating a ManagedPropertyFilterGenerator refiner

First before we get round to doing one for our managed metadata property, we are going to create one for our Choice field we created at the start of this blog. Called DemoChoice.

With notepad or Visual studio copy the following.

<Category Title="CF Demo Choices"
Description="Managed Metadata for Blog Demo"
Type="Microsoft.Office.Server.Search.WebControls.ManagedPropertyFilterGenerator"
MetadataThreshold="1"
NumberOfFiltersToDisplay="4"
MaxNumberOfFilters="20"
SortBy="Frequency"
SortByForMoreFilters="Name"
SortDirection="Descending"
SortDirectionForMoreFilters="Ascending"
ShowMoreLink="True"
MappedProperty="DemoChoice"
MoreLinkText="show more"
ShowCounts="Count"
LessLinkText="show fewer" />

Let me explain a few things. The Title can be anything you like. MetadataThreshold specifies the number of results that must contain a value to display in the filter generator. I have set this to 1 to ensure that if there is a result, then the refiner will show something. You might want to set this higher in a production environment. The MappedProperty is the value you created during the steps of “Setup for ManagedPropertyFilterGenerator refiner”.

  • Assuming you still have the Results page in edit mode, and are editing the Refinement Panel Web Part, take a copy of the above, and insert it after <FilterCategories> and before <Category Title=”Result Type” of the Filter Category Definition.
<?xml version="1.0" encoding="utf-8"?>
<FilterCategories>
<!--Insert Here-->
<Category Title="Result Type"
  • Click OK to the WebPart Editor, Save and Close the page from the ribbon.
  • In the search, (if you have been following my demo) type item in the search box. In the Search refinement section you will see your ManagedPropertyFilterGenerator at work.

  • If you click on any of the links, say Orange the results will re-filter to show you just Items that are tagged with Orange. You might have noticed the number of items next to the value, this is there because I added the XML ShowCounts=”Count”, I could have added Percentage instead.

Creating a TaxonomyFilterGenerator refiner

With notepad or Visual studio copy the following

<Category Title="Location"
Description="Taxonomy Managed Metadata for Blog Demo"
Type="Microsoft.Office.Server.Search.WebControls.TaxonomyFilterGenerator"
MetadataThreshold="1"
NumberOfFiltersToDisplay="4"
MaxNumberOfFilters="20"
SortBy="Frequency"
SortByForMoreFilters="Name"
SortDirection="Descending"
SortDirectionForMoreFilters="Ascending"
ShowMoreLink="True"
MappedProperty="ows_MetadataFacetInfo"
MoreLinkText="show more"
LessLinkText="show fewer" />

The difference here is that the Type always points to TaxonomyFilterGenerator.
The MappedProperty always points to ows_MetadataFacetInfo, and the Title points to the name of the Column or Field that the Managed Metadata is mapped to. So in our case Location, (If the field has a space that’s OK but remember it’s the column name.) If you used “Managed Metadata Columns” for your title then it would display all managed metadata columns, not one particular refiner.

  • Assuming you still have the Results page in edit mode, and are editing the Refinement Panel Web Part, take a copy of the above, and insert it after <FilterCategories> and before <Category Title=”CF Demo Choices” of the Filter Category Definition.
  • Click OK to the WebPart Editor, Save and Close the page from the ribbon.
  • In the search, (if you have been following my demo) type item in the search box. In the Search refinement section you will see your TaxonomyFilterGenerator at work.

Above is the picture of my library with the Location data. Below is a Search on “File” which happens to be the title of each document. All 15 items.

Now if I select show more, and then click on Europe. It will show me 5 documents. The one I’ve actually tagged as Europe, and the 4 others that have been tagged to countries that are children of Europe in our Term Set.

In my last blog of this series, I will show you how to perform a CAML query against a Managed Metadata column so that the results will return all child terms as well. Just like we have with the Search Refiner.

Share this:

  • Tweet
  • Email
  • WhatsApp
  • More
  • Pocket
  • Print
  • Share on Tumblr

Like this:

Like Loading...
Posted in SharePoint | Tagged Managed Metadata Service, Search, SharePoint 2010 | 8 Comments

Creating a Site Column with managed Metadata

Posted on April 1, 2013 by cann0nf0dder

  • Part 1 – Setting up Managed Metadata Service
  • Part 2 – Explaining how to use the Term Store
  • Part 3 – Creating a Site Column with managed Metadata (gotchas with List Definitions)
  • Part 4 – Search Refiners with Managed Metadata
  • Part 5 – Search CAML query with Managed Metadata
  • Update – Creating a Site Column with Managed Metadata using Javascript.

In the last blog I explained to you how to use the Term Store Management Tool. Once you have created a Term Set and terms, you will want to use them within your SharePoint Sites. This blog will explain how to do this via point and click in the UI, and then afterwards I will show you how programmatically you can create a Managed Metadata Column in a SharePoint Feature.

Creating a Managed Metadata Column for a library (Point and Click).

  • Go to your site, and create a new document library.
  • Once created on the ribbon, select Library from the Library Tools and then click Library Settings.
  • Under the columns section click Create Column
  • Name your column, in my instance I’ve called my Location.
  • Select Managed Metadata as the column type.
    • Now if under Term Set Settings you get the message “The required feature is not enabled for this column type”, then you are probably using a blank site and will need to enable a SP Feature in powershell. Type the following in powershell
      Enable-SPFeature –id "73EF14B1-13A9-416B-A9B5-ECECA2B0604C" –Url <SiteURL>
    • Go back to your Create Column page, select a different column type, then select Managed Metadata column again. Under Term Set Settings you will see your Managed Metadata Data Service instead of the above message.
  • Under Term Set Settings, expand the service and group to navigate down to your term set. Mine is called Countries.
  • Under Default Value you can enter a value that is always displayed when creating a new item. For my demo, I’m putting United Kingdom.
  • Back on your list, upload a document. As you can see, in Location by default United Kingdom is entered.
  • If you wish to change this, you can either
    • Delete United Kingdom and type the name of a different term
    • Click the label icon on the right which brings up the term dialog to allow you to select a different Term.
  • I’ve uploaded a few documents in preparation for my part 4 of my Managed Metadata Series. As you can see I’ve set all the locations.

Programmatically create a Managed Metadata Column.

Here we are going to walk through creating a Managed Metadata column via a feature, then we are going to build upon it to create a list Definition and list instance.

  • Open Visual Studio, and create a new Empty SharePoint Project. Name the project ManagedMetadata.
  • Use your SharePoint Site for debugging, I’m using a team site, and Deploy as a Farm Solution.
  • In Solution Explorer right click your project and select Add -> New Item.
  • On the Add New Item dialog, select Empty Element and name it Fields. This will create a feature for you too.
  • Open the Elements.xml file and add the following to create 2 fields. The first field of type TaxonomyFieldType is the actual field we are trying to create (TaxonomyFieldTypeMulti for multiple selection, don’t forget to add Multi = True to the element field too). The Show Field will always point to Term1033 for any Managed Metadata Column. You will need to also include the Customization section. This will be identical for every Managed Metadata Column you create, except the Guid which is the same Guid ID of the second field created here, the Note Hidden field. The Note field, is a hidden field that contains a reference to the actual term in the term set that was selected, this is required for each Managed Metadata Column and the name of it is always [ManagedMetadataColumName]TaxHTField0
    <Field ID="{B654D984-187A-471B-8738-F08F3356CFDA}"
             Type="TaxonomyFieldType"
             DisplayName="Countries"
             ShowField="Term1033"
             EnforceUniqueValues="FALSE"
             Group="Demo"
             StaticName="Countries"
             Name="Countries">
        <Customization>
          <ArrayOfProperty>
            <Property>
              <Name>TextField</Name>;
              <Value xmlns:q6="http://www.w3.org/2001/XMLSchema" p4:type="q6:string" xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">{67308AC2-9556-456B-BF9E-43E8F23EBEE6}</Value>
            </Property>
          </ArrayOfProperty>
        </Customization>
      </Field>
      <Field Type="Note"
             DisplayName="Countries_0"
             StaticName="CountriesTaxHTField0"
             Name="CountriesTaxHTField0"
             ID="{67308AC2-9556-456B-BF9E-43E8F23EBEE6}"
             ShowInViewForms="FALSE"
             Required="FALSE"
             Hidden="TRUE"
             CanToggleHidden="TRUE"
             Group="Demo"
             RowOrdinal="0"
             />
    </Elements>
    
  • Now we have created the field if this was deployed it wouldn’t work. This is because you have to hook up the column to the TermSet, and this isn’t something we can do declaratively. It has to be done via a Feature Receiver event. Right click your feature, and select Add Event Receiver.
  • Before we start, we need to add a dll reference to Microsoft.SharePoint.Taxonomy. Right click References > Add References… and find Microsoft.SharePoint.Taxonomy. Add using Microsoft.SharePoint.Taxnonomy to the top of your Event Receiver class.
  • In the FeatureActivated event add the code
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
 SPSite site = properties.Feature.Parent as SPSite;
 ConnectTaxonomyField(site, new Guid("{B654D984-187A-471B-8738-F08F3356CFDA}", "Continents", "Countries");
}

We are about to create the ConnectTaxonomyField method in a moment. It will pass in the Guid of the Managed Metadata Field ID, and the Group name, and Term Set Name of the Term Set we wish to add. From the below image you can see where I got the string names from.

public static void ConnectTaxonomyField(SPSite site, Guid fieldId, String termGroup, string termSetName)
{
 //Check if field exists in the site.
 if(site.RootWeb.Fields.Contains(fieldId))
 {
   //Create a Taxonomy Session
   TaxonomySession session = new TaxonomySession(site);
   if(session.DefaultkeywordsTermStore != null)
   {
     //get the default metadata service application
     var termStore = session.DefaultKeywordsTermStore;
     var group = termStore.Groups.GetByName(termGroup);
     var termSet = group.TermSets.GetByName(termSetName);
     TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;
     field.SspId = termSet.TermStore.Id;
     field.TermSetId = termSet.Id;
     field.TargetTemplate = string.Empty;
     field.AnchorId = Guid.Empty;
     field.Update();
    }
    else
    {
       throw new Exception(string.Format("DefaultKeyWordTermStore not found in this site {0}", site.Url));
    }
  }
  else
  {
    throw new ArgumentException(string.Format("Field {0} not found in site {1}", fieldId, site.Url));
  }
 }
  • The termStore.Groups.GetByName() and group.TermSets.GetByName() you will find that they don’t exist in your code. That is because these are custom extensions I have created. Add a new class to your project called Extensions, and ensure it is a public static, also add using Microsoft.SharePoint.Taxnonomy to the top of your class. Add the following code.
public static Group GetByName(this GroupCollection groupCollection, string groupName)
{
            if (String.IsNullOrEmpty(groupName))
            {
                throw new ArgumentException("Taxonomy group name cannot be empty", "name");
            }
            foreach (var group in groupCollection)
            {
                if (group.Name == groupName)
                {
                    return group;
                }
            }
            throw new ArgumentOutOfRangeException("Group Name", groupName, " Could not find the taxonomy group");
        }

        public static TermSet GetByName(this TermSetCollection termSets, string termSetName)
        {
            if (String.IsNullOrEmpty(termSetName))
            {
                throw new ArgumentException("Term set name cannot be empty", "name");
            }
            foreach (var termSet in termSets)
            {
                if (termSet.Name == termSetName)
                {
                    return termSet;
                }
            }
            throw new ArgumentOutOfRangeException("TermSetName", termSetName, " Could not find the term set");
       }
  • Now we can deploy our solution. First go into the feature, and change the scope from Web to Site. Now click the play button in Visual Studio and deploy the solution.
  • Once your site has loaded up, click Site actions -> Site Settings. Under Galleries, click on Site Columns. As my field was put in the group Demo when I scroll down to that group, I see Countries.
  • Click on Countries. Now if my feature receiver has worked correctly, under Term Set Settings this has been configured correctly.

Create Content Type and List Definition with Managed Metadata

In this step, we are going to create a Content Type, add our new Managed metadata field and required fields to get it all working. Then we are going to create a list definition.

  • Right click on your project and select Add > New Item. Select Content Type and give it the name of Document Location. Click Add.
  • In the SharePoint Customization Wizard select Document as the base type. Click finish.
  • The Elements.xml file should already be displayed for you, for your new content type. We need to update a few items first
    • Name – Document Location,
    • Group – Demo Content Type
    • Description – Demonstration of a content type with a managed metadata field.
  • Now we need to add our field refs. The Managed Metadata Field, the Note field that comes with our Managed Metadata field, SharePoint’s TaxCatchAll column and SharePoint’s TaxCatchAllLabel. The TaxCatchAll and TaxCatchAllLabel columns are lookup fields pointing to the special hidden list in the site collection (TaxonomyHiddenList). They point to the CatachAllData and CatachAllDataLabel fields in the hidden list and are used within each list that has a column of type Managed Metadata. Our final Content Type Elements file should look like below.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Parent ContentType: Document (0x0101) -->;
  <ContentType ID="0x010100571ebc0f478a49d5a775039347ee1535"
               Name="Document Location"
               Group="Demo"
               Description="A content type containing Managed Metadata Column."
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{B654D984-187A-471B-8738-F08F3356CFDA}" Name="Countries"/>
      <FieldRef ID="{67308AC2-9556-456B-BF9E-43E8F23EBEE6}" Name="CountriesTaxHTField0"/>
      <FieldRef ID="{f3b0adf9-c1a2-4b02-920d-943fba4b3611}" Name="TaxCatchAll"/>
      <FieldRef ID="{8f6b6dd8-9357-4019-8172-966fcd502ed2}" Name="TaxCatchAllLabel"/>
    </FieldRefs>
  </ContentType>
</Elements>
  • Now we are going to create our List Definition. Right Click on your project and select Add > New Item. Select List Definition From Content Type and give it the name of DocLocationCT. Click Add.
  • In the SharePoint Customization Wizard put the Display Name as Reference Documents and select your Document Location as the content type to use for your list definition. Ensure the Add a list instance for this list definition is ticked. Click Finish.

  • Open the Schema.xml file from within your DocLocationCT. At the very top of the document you will see <List xmlns:ows=”Microsoft SharePoint”… add the following attribute to enable Content Types on the Document Library.
    EnableContentTypes="TRUE"
    
  • Underneath <List><Metadata><ContentType><FieldRefs> you will see that all your fields have already been added to the Content Type FieldRefs section at the top of the file.
  • Under the <ContentTypes> section there is the <Fields> section. Near the bottom of the <Fields> section you will find the TaxonomyField Type and Note field for Countries and CountriesTaxHTField0. Here is your first Gotcha, you need to add the following to the end of the Countries field.
    webId="~sitecollection" List="TaxonomyHiddenList"
    
  • To ensure our field shows up in the default view, scroll down Schema.xml file until you reach <View BaseViewID=”1″ Type=”HTML”… Then add the following as an addition FieldRef. The order you add it to in the list, will be the order it will appear on the document library view. I’ (Please note, if you add it to BaseViewID=”0″ it will not show up.
    <FieldRef Name="Countries"></FieldRef>
    

List instance.

When we created the List Definition, we said to add a list instance for this list definition.

  • Within the List Definition in Solution Explorer, you can see a List Instance has been added with an elements.xml file. Open up this elements file. Change the file to the following. (We will add the featureId value shortly, also note that the TemplateType will match the List Template Type in the Elements.xml file from the List Defintion.
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <ListInstance Title="Document Location References"
                    OnQuickLaunch="TRUE"
                    TemplateType="10000"
                    Url="Lists/References"
                    FeatureId="[The Feature ID of the List Definition Feature]"
                    Description="A document library of reference, categorised by Country/Region.">
      </ListInstance>
    </Elements>
    
  • The last thing that has to be done is add an event receiver for our list instance. This event receiver is fired on item adding or item updating. The events are SharePoint Taxonomy events, and they ensure the hidden columns are updated whenever the values within the Managed Metadata column changes. Right Click the project and select Add > New Item. Select Event Receiver and name it MangedMetadataER, click Add.
  • On the SharePoint Customization Wizard, the event receiver type is List Item Events (Default). The item that should be the event source is Reference Documents(ManagedMetadata\DocLocationCT) (Default). Then tick An item is being added and An item is being updated. Click Finished.
  • You will be taken to the .cs file. This file can be deleted. Then open the Elements.xml file of the ManagedMetadataER.
  • The current Receivers shown will need to be deleted and replaced. To be honest we could have just created an empty element, however I like the icons in Visual studio to be correct, so this is the reason I created an Event Receiver.
  • Replace the Receivers to so the file looks like the following.
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers ListTemplateId="10000">
        <Receiver>
          <Name>TaxonomyItemSynchronousAddedEventReceiver</Name>
          <Type>ItemAdding</Type>
          <Assembly>Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
          <Class>Microsoft.SharePoint.Taxonomy.TaxonomyItemEventReceiver</Class>
          <SequenceNumber>10000</SequenceNumber>;
        </Receiver>
        <Receiver>
          <Name>TaxonomyItemUpdatingEventReceiver</Name>
          <Type>ItemUpdating</Type>
          <Assembly>Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
          <Class>Microsoft.SharePoint.Taxonomy.TaxonomyItemEventReceiver</Class>
          <SequenceNumber>10000</SequenceNumber>
        </Receiver>
      </Receivers>
    </Elements>
    
  • Time to put it all together. Create 2 features. One called ManagedMetadataListDefinition and one called ManagedMetadataListInstance. Both of these features are web scope instances. (Gotcha 2! I found that if List Definition and List Instance in the same feature didn’t allow the Managed Metadata field to work when I viewed the list it created on activation, although, any following lists created via the list definition did.)The original feature 1 can be renamed to ManagedMetadataFieldAndCT.
  • In the MangedMetadataFieldAndCT feature, (Site scope) ensure the following items are in the Feature.
    • Fields
    • Document Location (This is the Content Type)
  • In the ManagedMetadataListDefinition feature, (Web scope) ensure the following items are in the Feature.
    • DocLoactionCT (This is the List Definition)
    • ManagedMetadataER (This is the Event Receiver)
  • In the ManagedMetadataListInstance feature, (Web scope) ensure the following items are in the Feature.
    • ListInstance1 (This is the List Instance)
  • Lastly, double click the ManagedMetadataListDefinition and view the properties (F4). Take a copy of the Feature Id. Now open the Elements.xml file from the ListInstance1 and add this Guid to the FeatureId property that we left blank earlier.
  • Now deploy your solution. When your site loads up, in the Quick Launch list you will see “Document Location References” this is your List Instance. You should find uploading an item, and being able to pick from the term store something for Countries.
  • If you click Site Actions -> More Options, the Create dialog box will appear. If you filter by Library, in the list you will see Reference Documents. This is your List Definition.
  • If you click Site Actions -> Site Settings. Under Galleries, click on Site Content Types. If we scroll down to the group Demo you will see our Content Type Document Location.

This concludes this blog Creating a Site Column with managed Metadata (gotchas with List Definitions) in the Managed Metadata Series. It highlighted some of the Gotchas when creating the Managed Metadata field declaratively. Our next part in the series will explain about Search Refiners, and how to create one based on a Managed Metadata column.

Share this:

  • Tweet
  • Email
  • WhatsApp
  • More
  • Pocket
  • Print
  • Share on Tumblr

Like this:

Like Loading...
Posted in SharePoint | Tagged Managed Metadata Service, SharePoint 2010, Term Store | 2 Comments

Explaining how to use the Term Store

Posted on March 31, 2013 by cann0nf0dder

  • Part 1 – Setting up Managed Metadata Service
  • Part 2 – Explaining how to use the Term Store
  • Part 3 – Creating a Site Column with managed Metadata (gotchas with List Definitions)
  • Part 4 – Search Refiners with Managed Metadata
  • Part 5 – Search CAML query with Managed Metadata
  • Update – Creating a Site Column with Managed Metadata using Javascript.

In my previous blog I showed you how to create a Managed Metadata Service. As you saw it wasn’t that difficult. This blog in the series will explain how to use the Term Store Management Tool.

How to find the link to the Term Store

If you are in Central Administration, the link is easy to find, you simply navigate to Application Management, under Service Applications click Manage service applications. Down the list you should see Managed Metadata Service click this link. However if you are not a Farm Administrator you won’t be able to navigate to Central Administration site.

On the Site Collection root site, click Site Actions -> All Site Settings. Under Site Administration there should be a link to Term store management.


However there can be times when this link isn’t showing.

Normally because you have created a Blank site. So what feature activates this link? The feature you are looking for is hidden, and can only be activated via powershell, or via the stsadm command. (stsadm command is really for SharePoint 2007, so below I’ll show you the PowerShell command.


Enable-SPFeature –id &quot;73EF14B1-13A9-416B-A9B5-ECECA2B0604C&quot; –Url &lt;SiteURL&gt;

Explaining the Term Store Structure.

In the above picture it illustrates how the Term Store is structured.

Managed Metadata Service – This is the name of the Term Store. This is when you created your Managed Metadata Service in my previous blog. Each Term Store has 1 SQL database. The properties you can set on a Term Store are adding/removing Term Store Administrators (See Permissions for Term Store Management Tool), you can assign the default language, and specify which other languages to be used within the Term Store. Please note these languages will depend on the Language packs you have installed within the farm.

Group – Under the Term Store you can create multiple groups. Each group are a security boundary, so assigning users to one group doesn’t mean they will have access to another. The properties on the group, allows you to add or remove Group managers or Contributors. (See Permissions for Term Store Management Tool).

Term Set – A term set is a collection of terms. You can have many term sets per Group. When you create a managed metadata column you normally assign the column to a term set. (E.g, Country, Office, Department etc). The properties on the Term Set allows you to set the owner and email address for term suggestions and feedback, any stakeholders for the term set can be added here too. The Submission Policy is by default set to Closed. When closed only metadata managers can add terms to this term set. When it is open, users can add terms from a tagging application. (Similar to the keywords)

Term – Think of the term as the item within the term set. So for country a Term might be United Kingdom, France, Spain. Properties for Term allows you to create a default label for each language, you can also add other labels such as synonyms. This might be United Kingdom synonym would be GBR. If a user searched for GBR or United Kingdom both would resolve to the same Term.

Sub Term – A Term can have one or multiple terms beneath it, so for country a Sub Term for United Kingdom, might be England, Scotland, Wales, Ireland.

Permissions for Term Store Management Tool

Term Store Administrators

When you set up your Managed Metadata Service you would automatically be the Term Store Administrator. You can add additional people to be a Term Store Administrator. By doing so, you will give this users access to create new Term set groups and assign users to the group manager role. As an Administrator, access the Term Store Management Tool, on the landing page, the properties page has a section called Term Store Administrators. It is here where you can additional Administrators.

Group Managers

The group managers are assigned at the Group level and are contributors on this group but can also assign other users to the contributor role. This setting can be found on the Group Properties.

Contributors

The contributors are assigned at the Group level too, they will have full permission to edit term sets and terms within this group.

Adding to the Term Store.

There are two ways in which you can add to the Term Store.

  1. Manually
  2. Via a CSV import.

To do it manually is simply click on the right of the Group, Term Set or Term which brings up a context menu for that item type.

When you have numerous Terms to enter, you probably find it tedious. Therefore you can do it via a CSV. On the Term Store properties page there is a link to a CSV Sample import. By downloading this and viewing it you can see how to create your Term Set via a CSV

The above is a picture of the sample CSV. To import, once you have created your group by clicking the context menu, you can select Import Term Set. Point it to your CSV file and then after clicking OK, your term set is imported. The picture below shows you the sample term set that Microsoft provides you.

In Part 3 of the blog, I’m going to show you how to use the Term Store for a general site user. Then I’m going to show you how to create a Site Column with List definition using C# code.

Share this:

  • Tweet
  • Email
  • WhatsApp
  • More
  • Pocket
  • Print
  • Share on Tumblr

Like this:

Like Loading...
Posted in SharePoint | Tagged Managed Metadata Service, SharePoint 2010, Term Store

Setting up Managed Metadata Service

Posted on March 31, 2013 by cann0nf0dder

  • Part 1 – Setting up Managed Metadata Service
  • Part 2 – Explaining how to use the Term Store
  • Part 3 – Creating a Site Column with managed Metadata (gotchas with List Definitions)
  • Part 4 – Search Refiners with Managed Metadata
  • Part 5 – Search CAML query with Managed Metadata
  • Update – Creating a Site Column with Managed Metadata using Javascript.

In this 5 part blog I’m going to explain about Managed Metadata Service. The managed metadata service application has two purposes, 1. To make it possible to use managed metadata and 2. Share content types. I will not be going into detail about the Content Hub or shared content types across site collections in this series of blogs, but basically if you create a site collection and turn on the feature Content Type Syndication Hub before creating the Managed Metadata Service you will have a working Content Hub for the Farm. The Managed metadata service can be used to define metadata centrally for all web applications. You can even use the service across farms. Cross farms will also be outside of the scope of this blog.

If you have already created your managed metadata service using the SharePoint wizard then you can completely skip this step. However in a live environment you probably won’t want to use the wizard and create the Managed Metadata service manually so that it has the correct service account.

Setting up Managed Metadata Service.

  • Open central administration and click on Application Management. Under the Service Applications section, click on Manage Service Applications.
  • On the ribbon bar click New and select Managed Metadata Service.
  • Put the following information in:
    • Name: Managed Metadata Service
    • Database Server:
      (This should be your SharePoint SQL server. Normally entered by default)
    • Database Name: SP_Dev_MMS
    • Under Application Pool, Create a new application Pool Application Pool Name: MMS_AP
    • Configurable:
      (In my case I have an account already set up called SP_Services, use whatever account you wish that is not your Farm Account or your personal account. Register a new managed account called SP_MMS if you like)
    • Content Type Hub: (This is the URL to your Content Hub, please note you will not be able to change this again here in the UI. If you wish to add it later, or change it, you will need to use PowerShell.)
    • Report syndication import errors: Ticked
    • Add this service application to the farm’s default list: Ticked.
  • Click OK

If you have followed the instructions above correctly, you should now see Managed Metadata Service in the Service Application list.

By clicking on this you will now have access to the Term Store Management Tool.

In my next blog I will explain how to use the Term Store Management Tool in more detail. How to create Term Sets, and how to assign permissions.

Share this:

  • Tweet
  • Email
  • WhatsApp
  • More
  • Pocket
  • Print
  • Share on Tumblr

Like this:

Like Loading...
Posted in SharePoint | Tagged Managed Metadata Service, SharePoint 2010, Term Store

Top Posts & Pages

  • Connecting to Azure Devops with a Service Principal
  • Viewing, Restoring and Removing Items from the SharePoint Recycle Bin - The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.
  • Getting all MS Teams User Policies using PowerShell
  • SPFX obtaining the URL Query Parameters
  • Unable to see public Teams within ‘Join or create a team’ section of MS Teams
  • Finding the related Site from Teams Private Channel Site
  • Using HTML template and JQuery.clone()
  • Externally Sharing – GetSharingInformation REST API

Archives

Categories

  • Development (158)
  • General (7)
  • Hyper V (19)
  • MS Teams (7)
  • Office (6)
  • PowerShell (55)
  • SharePoint (134)
  • SQL (12)
  • Virtual Machines (3)
  • VM Workstation (2)
  • Windows (13)

Meta

  • Register
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com

Follow me on Twitter

Tags

Azure Blogging Business Conectivity Services Certificates Content Types CrossDomain Development Dev Machine DevOps Display Templates Extensions Externally Sharing Hyper V JavaScript JQuery Kerberos Managed Metadata Managed Metadata Service Manage Services MS Teams Nintex O365 Groups Office Office 365 PnP PowerShell PowerShell Script REST Ribbon Search SharePoint SharePoint 2010 SharePoint 2013 SharePoint 2016 SharePoint Apps SharePoint Designer SharePoint Online SQL SQL 2012 SQL 2016 Term Store Upgrade Upgrading Visual Studio VMWare Windows 8 Windows 10 Windows Server 2012 Windows Server 2012 R2 Workflows

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 433 other subscribers

SharePoint and other Geeky Stuff

  • RSS - Posts
  • RSS - Comments

Blog Stats

  • 1,305,235 hits
Blog at WordPress.com.
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • SharePoint and other geeky stuff
    • Join 96 other followers
    • Already have a WordPress.com account? Log in now.
    • SharePoint and other geeky stuff
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d bloggers like this: