Monday, January 12, 2015

Result script webpart customize



ContentBySearchWebPartExt

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Search.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using System.Threading;
using Microsoft.IdentityModel.Claims;
using System.Text;
using Microsoft.SharePoint.Administration.Claims;
using System.Linq;

namespace SearchWebPartsExt.ContentBySearchWebPartExt {
    [ToolboxItemAttribute(false)]
    public class ContentBySearchWebPartExt : ContentBySearchWebPart {
        private string _manageProperty = "CustomerAge";
        private string _claimType = "http://schemas.xyz.org/customers/age";
        private string _allValue = "Everyone";

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("Claim Type")]
        public string ClaimType
        {
            get { return this._claimType; }
            set { this._claimType = value; }
        }

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("Managed Property")]
        public string ManagedProperty
        {
            get { return this._manageProperty; }
            set { this._manageProperty = value; }
        }

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("All Value")]
        public string AllValue
        {
            get { return this._allValue; }
            set { this._allValue = value; }
        }

        public ContentBySearchWebPartExt() { }

        //by default, only the contentbysearchtoolpart and webparttoolpart are returned.
        //include the customwebparttoolpart so that our custom properties will appear in the browser.
        public override ToolPart[] GetToolParts()
        {
            var toolParts = new List<ToolPart>();
            toolParts.AddRange(base.GetToolParts());
            toolParts.Add(new CustomPropertyToolPart());

            return toolParts.ToArray();
        }

        protected override void OnLoad(EventArgs e)
        {
            if (this.AppManager != null)
            {
                if (this.AppManager.QueryGroups.ContainsKey(this.QueryGroupName) &&
                    this.AppManager.QueryGroups[this.QueryGroupName].DataProvider != null)
                {
                    this.AppManager.QueryGroups[this.QueryGroupName].DataProvider.BeforeSerializeToClient +=
                        new BeforeSerializeToClientEventHandler(EnhanceQuery);
                }
            }

            base.OnLoad(e);
        }

        private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e)
        {
            DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
            SetFilteredResults(dataProvider, this.ClaimType, this.ManagedProperty, this.AllValue);
        }

        private void SetFilteredResults(DataProviderScriptWebPart dataProvider, string claimType, string managedProperty, string allValue) {
            //if there's no managed property or claim type given, do nothing
            if (string.IsNullOrEmpty(managedProperty) || string.IsNullOrEmpty(claimType))
                return;

            //if the current query already contains filters for the segment property, do nothing
            if (dataProvider.QueryTemplate.Contains(managedProperty))
                return;

            //if this is a windows user, don't continue
            if (IsWindowsUser(Thread.CurrentPrincipal.Identity.Name))
                return;

            //grab the current user's claimsidentity
            var currentIdentity = Thread.CurrentPrincipal.Identity as IClaimsIdentity;

            var claimValues = new List<string>();

            currentIdentity.Claims.Where(c => c.ClaimType == claimType).ToList().ForEach(
                c => {
                    //only get unique claim values
                    if (!claimValues.Contains(c.Value)) { claimValues.Add(c.Value); }
                }
            );

            var qry = new StringBuilder();
            qry.Append(dataProvider.QueryTemplate);

            //if there is a value that everyone can get, include it in list of claim values
            if (!string.IsNullOrEmpty(allValue))
                claimValues.Add(allValue);

            //if there are any items, start the query
            if (claimValues.Count > 0) {
                qry.Append("(");
                for (int i = 0; i < claimValues.Count; i++) {
                    var value = claimValues[i];
                    var filter = string.Format("{0}:\"{1}\"", managedProperty, value);

                    //add the segment filter
                    qry.Append(filter);

                    //if this isn't the last value, we need to append an or
                    if (i < claimValues.Count - 1)
                        qry.Append(" OR ");

                }

                qry.Append(")");
            }

            dataProvider.QueryTemplate = qry.ToString();
        }

        private bool IsWindowsUser(string userLoginName) {
            if (string.IsNullOrEmpty(userLoginName))
                return false;

            var enocoded = SPClaimProviderManager.Local.GetUserIdentifierEncodedClaim(userLoginName);

            SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(enocoded);
            return SPOriginalIssuers.GetIssuerType(claim.OriginalIssuer) == SPOriginalIssuerType.Windows;
        }
    }
}


ResultScriptWebPartExt

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Search.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.IdentityModel.Claims;
using System.Linq;

namespace SearchWebPartsExt.ResultScriptWebPartExt {
    [ToolboxItemAttribute(false)]
    public class ResultScriptWebPartExt : ResultScriptWebPart {
        private string _manageProperty = "CustomerAge";
        private string _claimType = "http://schemas.xyz.org/customers/age";
        private string _allValue = "Everyone";

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("Claim Type")]
        public string ClaimType {
            get { return this._claimType; }
            set { this._claimType = value; }
        }

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("Managed Property")]
        public string ManagedProperty {
            get { return this._manageProperty; }
            set { this._manageProperty = value; }
        }

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable(true),
        Category("Custom"),
        WebDisplayName("All Value")]
        public string AllValue {
            get { return this._allValue; }
            set { this._allValue = value; }
        }

        public override ToolPart[] GetToolParts() {
            var toolParts = new List<ToolPart>();
            toolParts.AddRange(base.GetToolParts());
            toolParts.Add(new CustomPropertyToolPart());

            return toolParts.ToArray();
        }

        public ResultScriptWebPartExt() { }

        protected override void OnLoad(EventArgs e) {
            if (this.AppManager != null) {
                if (this.AppManager.QueryGroups.ContainsKey(this.QueryGroupName) &&
                    this.AppManager.QueryGroups[this.QueryGroupName].DataProvider != null) {
                    this.AppManager.QueryGroups[this.QueryGroupName].DataProvider.BeforeSerializeToClient +=
                        new BeforeSerializeToClientEventHandler(EnhanceQuery);
                }
            }

            base.OnLoad(e);
        }

        private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e) {
            DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
            SetFilteredResults(dataProvider, this.ClaimType, this.ManagedProperty, this.AllValue);
        }

        private void SetFilteredResults(DataProviderScriptWebPart dataProvider, string claimType, string managedProperty, string allValue) {
            //if there's no managed property or claim type given, do nothing
            if (string.IsNullOrEmpty(managedProperty) || string.IsNullOrEmpty(claimType))
                return;

            //if the current query already contains filters for the segment property, do nothing
            if (dataProvider.QueryTemplate.Contains(managedProperty))
                return;

            //if this is a windows user, don't continue
            if (IsWindowsUser(Thread.CurrentPrincipal.Identity.Name))
                return;

            //grab the current user's claimsidentity
            var currentIdentity = Thread.CurrentPrincipal.Identity as IClaimsIdentity;

            var claimValues = new List<string>();

            currentIdentity.Claims.Where(c => c.ClaimType == claimType).ToList().ForEach(
                c => {
                    //only get unique claim values
                    if (!claimValues.Contains(c.Value)) { claimValues.Add(c.Value); }
                }
            );

            var qry = new StringBuilder();
            qry.Append(dataProvider.QueryTemplate);

            //if there is a value that everyone can get, include it in list of claim values
            if (!string.IsNullOrEmpty(allValue))
                claimValues.Add(allValue);

            //if there are any items, start the query
            if (claimValues.Count > 0) {
                qry.Append("(");
                for (int i = 0; i < claimValues.Count; i++) {
                    var value = claimValues[i];
                    var filter = string.Format("{0}:\"{1}\"", managedProperty, value);

                    //add the segment filter
                    qry.Append(filter);

                    //if this isn't the last value, we need to append an or
                    if (i < claimValues.Count - 1)
                        qry.Append(" OR ");

                }

                qry.Append(")");
            }

            dataProvider.QueryTemplate = qry.ToString();
        }

        private bool IsWindowsUser(string userLoginName) {
            if (string.IsNullOrEmpty(userLoginName))
                return false;

            var enocoded = SPClaimProviderManager.Local.GetUserIdentifierEncodedClaim(userLoginName);

            SPClaim claim = SPClaimProviderManager.Local.DecodeClaim(enocoded);
            return SPOriginalIssuers.GetIssuerType(claim.OriginalIssuer) == SPOriginalIssuerType.Windows;
        }
    }
}

No comments:

Post a Comment