Showing posts with label Taxonomy Field. Show all posts
Showing posts with label Taxonomy Field. Show all posts

Thursday, 12 July 2012

Create managed meta data in sharepoint 2010

Added the namespace:

using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Publishing;


Feature1EventReceiver.cs code:
namespace Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("1ecb928c-632f-4ecf-9e91-bb8e54ce12a6")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            try
            {

                ConnectTaxonomyField(site, new Guid("{ABE8D451-BD55-4ea7-B617-63B897F13B67}"), "Global Intranet", "Classification",0);
                ConnectTaxonomyField(site, new Guid("{F8097950-9483-44dd-B9BE-51FDE94A0C5B}"), "Global Intranet", "Classification",1);
                ConnectTaxonomyField(site, new Guid("{9BC363E1-9749-443e-8821-C9157D3598DC}"), "Global Intranet", "Organisation",1);
            }

            catch (Exception ex)
            {

            }
        }

        public static void ConnectTaxonomyField(SPSite site, Guid fieldId, string termGroup, string termSetName, int termindex)
        {
            if (site.RootWeb.Fields.Contains(fieldId))
            {
                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);
                    TermCollection termcol = termSet.Terms;

                    var term = termSet.Terms[termindex];
                    TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;
                    // connect the field to the specified term
                    field.SspId = termSet.TermStore.Id;
                    // field.TermSetId = termSet.Terms[term.Id].Id;
                    field.TermSetId = termSet.Id;

                    field.TargetTemplate = string.Empty;
                    field.AnchorId = term.Id;
                    field.Update();
                }
                else
                {
                    throw new TermStoreNotFoundException(string.Format("DefaultKeywordsTermStore not found in site {0}", site.Url));
                }
            }
            else
            {
                throw new ArgumentException(string.Format("Field {0} not found in site {1}", fieldId, site.Url), "fieldId");
            }
        }

    }
    [Serializable]
    public class TermStoreNotFoundException : Exception
    {
        public TermStoreNotFoundException() { }
        public TermStoreNotFoundException(string message) : base(message) { }
        public TermStoreNotFoundException(string message, Exception inner) : base(message, inner) { }
        protected TermStoreNotFoundException(
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }
    }

    public static class TaxonomyExtensions
    {
        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("groupName", 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");
        }
    }
}