Wednesday, 29 April 2015

Find all the Managed Metadata or Enterprise Keywords columns from a document library for Provider Hosted Apps




Suppose we have a dropdown control that shows the document libraries of a site collection and we have another dropdown that will load the columns of Managed Metadata type. For that we need to
do the following coding:


protected void ddlLibrary_SelectedIndexChanged(object sender, EventArgs e)
        {

            LoadColumns();

        }

        private void LoadColumns()
        {
            string token = GetAccessToken();
            string url = SitePicker.SelectedNode.Value;
            string library = ddlLibrary.SelectedValue;
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(library))
            {
                return;
            }

    using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(url, token))
            {
                List list = SharePointList.GetListFromRootfolder(context, library);

                DropDownColumns.Items.Clear();

                var fields = list.Fields;

                context.Load(fields);
                context.ExecuteQuery();

                foreach (var field in fields)
                {
                    var fieldType = field.TypeAsString;

                    if (fieldType == "TaxonomyFieldType" || fieldType == "TaxonomyFieldTypeMulti")
                    {
                        var fieldName = field.Title;
                        var fieldIternalName = field.InternalName;

                        var fieldtermSetId = ((TaxonomyField)field).TermSetId;
                        var item = new DropDownListItem
                        {
                            Value =string.Format("{0}:{1}",fieldtermSetId,fieldIternalName),
                            Text = fieldName
                        };
                        DropDownColumns.Items.Add(item);
                    }
                }
            }
        }


Here, token is the Access Token for provider hosted apps and url is the URL of the site collection.

No comments:

Post a Comment