Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Sitecore;
- using Sitecore.Buckets.Extensions;
- using Sitecore.ContentSearch;
- using Sitecore.ContentSearch.Linq;
- using Sitecore.ContentSearch.SearchTypes;
- using Sitecore.ContentSearch.Security;
- using Sitecore.ContentSearch.Utilities;
- using Sitecore.Data.Items;
- using Sitecore.Data.Query;
- using Sitecore.Diagnostics;
- using Sitecore.Globalization;
- using Sitecore.Resources;
- using Sitecore.Shell.Applications.ContentEditor;
- using Sitecore.Text;
- using Sitecore.Web.UI.Sheer;
- using System;
- using System.Linq;
- using System.Collections;
- using System.Web.UI;
- using System.Collections.Specialized;
- using System.Text;
- using System.Web;
- using System.Collections.Generic;
- using Sitecore.Web.UI.HtmlControls;
- using Sitecore.Data;
- using BlueRubicon.Common;
- using Glass.Mapper.Sc;
- using BlueRubicon.Models.Templates.Data;
- using Sitecore.ContentSearch.Linq.Utilities;
- using BlueRubicon.Common.Utils;
- using Sitecore.Search;
- namespace BlueRubicon.Models.CustomFields.People {
- public class ClientProfileSelector : Sitecore.Web.UI.HtmlControls.Control, IContentField {
- private string _source;
- private bool enableSetNewStartLocation;
- private string _itemid;
- private int pageNumber = 1;
- protected readonly string Of = Translate.Text("{0} of {1}");
- private readonly string typeHereToSearch = Translate.Text("Type here to search");
- private string filter = string.Empty;
- private string _calculatedValue;
- private bool loadedClientProfiles;
- protected string FieldID { get; set; }
- public ClientProfileSelector() {
- this.Class = "scContentControlMultilist scClientProfileSelector";
- this.Activation = true;
- this._source = string.Empty;
- this.loadedClientProfiles = false;
- }
- public override string Value {
- get {
- Log.Info("Getting value...", this);
- return this.GetViewStateString("Value");
- }
- set {
- Log.Info("Setting value...", this);
- if (!(value != this.Value))
- return;
- this.SetViewStateString("Value", value);
- }
- }
- /// <summary>
- /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event.
- /// </summary>
- /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
- protected override void OnLoad(EventArgs e) {
- Assert.ArgumentNotNull((object)e, "e");
- base.OnLoad(e);
- string str = Sitecore.Context.ClientPage.ClientRequest.Form[this.ID + "_value"];
- if (str == null)
- return;
- if (this.GetViewStateString("Value", string.Empty) != str)
- this.SetModified();
- this.SetViewStateString("Value", str);
- }
- /// <summary>Sets the modified flag.</summary>
- protected void SetModified() {
- Sitecore.Context.ClientPage.Modified = true;
- }
- /// <summary>
- /// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
- /// </summary>
- /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
- protected override void OnPreRender(EventArgs e) {
- Assert.ArgumentNotNull((object)e, "e");
- base.OnPreRender(e);
- this.ServerProperties["Value"] = this.ServerProperties["Value"];
- }
- public virtual string OutputString(Item item4) {
- Item bucketItemOrParent = item4.GetParentBucketItemOrParent();
- string str = bucketItemOrParent != null ? "- " + bucketItemOrParent.Name : string.Empty;
- return string.Format("{0} ({1} {2} - {3} - {4})", (object)item4.DisplayName, (object)item4.TemplateName, (object)str, (object)item4.Version.Number, (object)item4.Language.Name);
- }
- protected override void DoRender(HtmlTextWriter output) {
- if (!ContentSearchManager.Locator.GetInstance<IContentSearchConfigurationSettings>().ItemBucketsEnabled()) {
- output.Write(Translate.Text("The field cannot be displayed because the Item Buckets feature is disabled."));
- } else {
- ArrayList selected;
- OrderedDictionary unselected;
- this.GetSelectedItems(this.GetItems(Sitecore.Context.ContentDatabase.GetItem(this.ItemID)), out selected, out unselected);
- StringBuilder stringBuilder = new StringBuilder();
- foreach (DictionaryEntry dictionaryEntry in unselected) {
- Item obj = dictionaryEntry.Value as Item;
- if (obj != null) {
- stringBuilder.Append(obj.DisplayName + ",");
- stringBuilder.Append(this.GetItemValue(obj) + ",");
- }
- }
- this.RenderStartLocationInput(output);
- output.Write("<input type='hidden' width='100%' id='multilistValues" + this.ClientID + "' value='" + (object)stringBuilder + "' style='width: 200px;margin-left:3px;'>");
- this.ServerProperties["ID"] = (object)this.ID;
- string str1 = string.Empty;
- output.Write("<input id='" + this.ID + "_Value' type='hidden' value='" + StringUtil.EscapeQuote(Value) + "' />");
- output.Write("<div class='scContentControlSearchListContainer scClientProfileSelectorTable'>");
- output.Write("<table" + this.GetControlAttributes() + ">");
- output.Write("<tr>");
- output.Write("<td class='scContentControlMultilistCaption' width='50%'>" + Translate.Text("All") + "</td>");
- output.Write("<td width='20'>" + Images.GetSpacer(20, 1) + "</td>");
- output.Write("<td class='scContentControlMultilistCaption' width='50%'>" + Translate.Text("Selected") + "</td>");
- output.Write("<td width='20'>" + Images.GetSpacer(20, 1) + "</td>");
- output.Write("</tr>");
- output.Write("<tr>");
- output.Write("<td valign='top' height='100%'>");
- output.Write("<div class='scMultilistNav'><input type='text' class='scIgnoreModified bucketSearch inactive' value='" + this.TypeHereToSearch + "' id='filterBox" + this.ClientID + "' " + (Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Access.CanWrite() ? string.Empty : "disabled") + ">");
- output.Write("<a id='prev" + this.ClientID + "' class='hovertext'>" + Images.GetImage("Office/16x16/arrow_left.png", 16, 16, "absmiddle") + Translate.Text("Prev") + "</a>");
- output.Write("<a id='next" + this.ClientID + "' class='hovertext'> " + Translate.Text("Next") + Images.GetImage("Office/16x16/arrow_right.png", 16, 16, "absmiddle") + "</a>");
- output.Write("<a id='refresh" + this.ClientID + "' class='hovertext'> " + Images.GetImage("Office/16x16/refresh.png", 16, 16, "absmiddle") + Translate.Text("Refresh") + "</a>");
- output.Write("<a id='goto" + this.ClientID + "' class='hovertext'> " + Images.GetImage("Office/16x16/magnifying_glass.png", 16, 16, "absmiddle") + Translate.Text("Go to item") + "</a>");
- output.Write("<span><span><strong>" + Translate.Text("Page number") + ": </strong></span><span id='pageNumber" + this.ClientID + "'></span></span></div>");
- string str2 = !UIUtil.IsIE() || UIUtil.GetBrowserMajorVersion() != 9 ? "10" : "11";
- output.Write("<select id=\"" + this.ID + "_unselected\" class='scBucketListBox' multiple=\"multiple\" size=\"" + str2 + "\"" + str1 + " >");
- foreach (DictionaryEntry dictionaryEntry in unselected) {
- Item obj = dictionaryEntry.Value as Item;
- if (obj != null) {
- string str3 = this.OutputString(obj);
- output.Write("<option value='" + this.GetItemValue(obj) + "'>" + str3 + "</option>");
- }
- }
- output.Write("</select>");
- output.Write("</td>");
- output.Write("<td valign='top'>");
- output.Write("<img class='' height='16' width='16' border='0' alt='' style='margin: 15px;' src='/sitecore/shell/themes/standard/Images/blank.png'/>");
- output.Write("<br />");
- this.RenderButton(output, "Office/16x16/navigate_right.png", string.Empty, "btnRight" + this.ClientID);
- output.Write("<br />");
- this.RenderButton(output, "Office/16x16/navigate_left.png", string.Empty, "btnLeft" + this.ClientID);
- output.Write("</td>");
- output.Write("<td valign='top' height='100%'>");
- output.Write("<select id='" + this.ID + "_selected' class='scBucketListSelectedBox' multiple='multiple' size='10'" + str1 + ">");
- for (int index = 0; index < selected.Count; ++index) {
- Item obj1 = selected[index] as Item;
- if (obj1 != null) {
- string str3 = this.OutputString(obj1);
- output.Write("<option value='" + this.GetItemValue(obj1) + "'>" + str3 + "</option>");
- } else {
- string path = selected[index] as string;
- if (path != null) {
- Item obj2 = Sitecore.Context.ContentDatabase.GetItem(path);
- string str3 = obj2 == null ? path + (object)' ' + Translate.Text("[Item not found]") : this.OutputString(obj2);
- output.Write("<option value='" + path + "'>" + str3 + "</option>");
- }
- }
- }
- output.Write("</select>");
- output.Write("</td>");
- output.Write("<td valign='top'>");
- output.Write("<img class='' height='16' width='16' border='0' alt='' style='margin: 15px 0;' src='/sitecore/shell/themes/standard/Images/blank.png'/>");
- output.Write("<br />");
- this.RenderButton(output, "Office/16x16/navigate_up.png", "javascript:scContent.multilistMoveUp('" + this.ID + "')", "btnUp" + this.ClientID);
- output.Write("<br />");
- this.RenderButton(output, "Office/16x16/navigate_down.png", "javascript:scContent.multilistMoveDown('" + this.ID + "')", "btnDown" + this.ClientID);
- output.Write("</td>");
- output.Write("</tr>");
- output.Write("<div style='border:1px solid #999999;font:8pt tahoma;display:none;padding:2px;margin:4px 0px 4px 0px;height:14px' id='" + this.ID + "_all_help'></div>");
- output.Write("<div style='border:1px solid #999999;font:8pt tahoma;display:none;padding:2px;margin:4px 0px 4px 0px;height:14px' id='" + this.ID + "_selected_help'></div>");
- output.Write("</table>");
- output.Write("</div>");
- this.RenderScript(output);
- }
- }
- public override void HandleMessage(Message message) {
- Assert.ArgumentNotNull((object)message, "message");
- base.HandleMessage(message);
- if (!(message["id"] == this.ID))
- return;
- switch (message.Name) {
- case "bucketsearchlist:selectall":
- SheerResponse.Eval("scContent.multilistMoveRight('" + this.ID + "', true)");
- break;
- case "bucketsearchlist:unselectall":
- SheerResponse.Eval("scContent.multilistMoveLeft('" + this.ID + "', true)");
- break;
- }
- }
- protected virtual void RenderScript(HtmlTextWriter output) {
- string str = "<script type='text/javascript'>\r\n (function() {\r\n if (!document.getElementById('BucketListJs')) {\r\n var head = document.getElementsByTagName('head')[0];\r\n head.appendChild(new Element('script', { type: 'text/javascript', src: '/sitecore/shell/Controls/BucketList/BucketList.js', id: 'BucketListJs' }));\r\n head.appendChild(new Element('link', { rel: 'stylesheet', href: '/sitecore/shell/Controls/BucketList/BucketList.css' }));\r\n }\r\n var stopAt = Date.now() + 5000;\r\n var timeoutId = setTimeout(function() {\r\n if (Sitecore.InitBucketList) {\r\n Sitecore.InitBucketList(" + this.ScriptParameters + ");\r\n clearTimeout(timeoutId);\r\n } else if (Date.now() > stopAt) {\r\n clearTimeout(timeoutId);\r\n }\r\n }, 100);\r\n }());\r\n </script>";
- output.Write(str);
- }
- public virtual string JavaScriptOutputString(string clientId) {
- return "responseParsed" + clientId + ".items[i].Name + ' (' + responseParsed" + clientId + ".items[i].TemplateName + ' - ' + responseParsed" + clientId + ".items[i].Bucket + ')'";
- }
- /// <summary>Gets or sets the item language.</summary>
- /// <value>The item language.</value>
- public string ItemLanguage {
- get {
- return StringUtil.GetString(this.ViewState["ItemLanguage"]);
- }
- set {
- Assert.ArgumentNotNull((object)value, "value");
- this.ViewState["ItemLanguage"] = (object)value;
- }
- }
- /// <summary>Gets or sets the item ID.</summary>
- /// <value>The item ID.</value>
- /// <contract>
- /// <requires name="value" condition="not null" />
- /// <ensures condition="nullable" />
- /// </contract>
- public string ItemID {
- get {
- return this._itemid;
- }
- set {
- Assert.ArgumentNotNull((object)value, "value");
- // If the value to be set is different, we need to initialize the Calculated Value as well as the Client Profiles
- if (this._itemid != value) {
- this.CheckOrUpdateCalculatedValue(value);
- }
- this._itemid = value;
- }
- }
- private void CheckOrUpdateCalculatedValue(string itemId = null) {
- if (itemId == null) {
- itemId = ItemID;
- }
- if (string.IsNullOrEmpty(itemId))
- return;
- var person = Sitecore.Context.ContentDatabase.GetItem(itemId);
- if (person == null || (person.TemplateID.Guid != GlobalDefinitions.Templates.PersonTemplate.Id && person.TemplateID.Guid != GlobalDefinitions.Templates.TeneoPersonTemplate.Id)) {
- return;
- }
- var glassContext = new SitecoreContext(Sitecore.Context.ContentDatabase);
- var glassPerson = glassContext.GetItem<BlueRubicon.Models.Templates.Data.BasePerson>(person.ID.Guid);
- if (this.loadedClientProfiles == false) {
- glassPerson.CurrentClients = CalculateClientProfile(glassContext, glassPerson);
- this.loadedClientProfiles = true;
- }
- if (glassPerson == null)
- return;
- if (glassPerson.CurrentClients == null) {
- CalculatedValue = string.Empty;
- } else {
- var currentClients = string.Join("|", glassPerson.CurrentClients.ToArray<ClientProfile>().Select(i => i.Id));
- if (!string.IsNullOrEmpty(currentClients)) {
- CalculatedValue = currentClients;
- }
- }
- }
- public string CalculatedValue {
- get {
- return this._calculatedValue;
- }
- set {
- this._calculatedValue = value;
- }
- }
- private List<ClientProfile> CalculateClientProfile(SitecoreContext context, BasePerson person) {
- var baseFilter = PredicateBuilder.True<ClientProfile>();
- List<ClientProfile> List = new List<ClientProfile>();
- baseFilter = baseFilter
- .And(i => i.ItemAncestors.Contains(GlobalDefinitions.Data.ContentRoot))
- .And(i => i.Enabled)
- .And(i => i.TemplateName == GlobalDefinitions.Templates.ClientProfileTemplate.Name);
- var filter = baseFilter
- .And(i => i.CurrentTeamIds.Contains(person.Id));
- OrderBy<ClientProfile>[] orderBy = {
- new OrderBy<ClientProfile>
- {
- Clause = i => i.Created,
- Descending = true
- }
- };
- var SearchIndex = ContentSearchManager.GetIndex("sitecore_master_index");
- IProviderSearchContext SearchContext = SearchIndex.CreateSearchContext();
- var query = SearchContext.GetQueryable<ClientProfile>();
- query = query.Where(filter);
- var results = query.GetResults();
- foreach (var hit in results.Hits) {
- ClientProfile profile = context.GetItem<ClientProfile>(hit.Document.Uri.ItemID.ToGuid());
- if (profile != null) {
- List.Add(profile);
- }
- }
- return List;
- }
- /// <summary>Gets or sets the source.</summary>
- /// <value>The source.</value>
- /// <contract>
- /// <requires name="value" condition="not null" />
- /// <ensures condition="nullable" />
- /// </contract>
- public string Source {
- get {
- return this._source;
- }
- set {
- Assert.ArgumentNotNull((object)value, "value");
- this._source = value;
- }
- }
- protected int PageNumber {
- get {
- return this.pageNumber;
- }
- set {
- this.pageNumber = value;
- }
- }
- protected bool EnableSetNewStartLocation {
- get {
- return this.enableSetNewStartLocation;
- }
- set {
- this.enableSetNewStartLocation = value;
- }
- }
- protected string Filter {
- get {
- return this.filter;
- }
- set {
- this.filter = value;
- }
- }
- protected string TypeHereToSearch
- {
- get
- {
- return this.typeHereToSearch;
- }
- }
- protected virtual void GetSelectedItems(Item[] sources, out ArrayList selected, out OrderedDictionary unselected) {
- Assert.ArgumentNotNull((object)sources, "sources");
- ListString listString;
- if (this.CalculatedValue != null) {
- listString = new ListString(this.CalculatedValue);
- } else {
- listString = new ListString(Value);
- }
- unselected = new OrderedDictionary();
- selected = new ArrayList(listString.Count);
- for (int index = 0; index < listString.Count; ++index)
- selected.Add((object)listString[index]);
- foreach (Item source in sources) {
- string str = source.ID.ToString();
- int index = listString.IndexOf(str);
- if (index >= 0)
- selected[index] = (object)source;
- else
- unselected.Add((object)MainUtil.GetSortKey(source.Name), (object)source);
- }
- }
- protected string ScriptParameters {
- get {
- return string.Format("'{0}'", (object)string.Join("', '", (object)this.ID, (object)this.ClientID, (object)this.PageNumber, (object)"/sitecore/shell/Applications/Buckets/Services/Search.ashx", (object)this.Filter, (object)SearchHelper.GetDatabaseUrlParameter("&"), (object)this.TypeHereToSearch, (object)this.Of, (object)this.EnableSetNewStartLocation));
- }
- }
- protected string MakeFilterQueryable(string locationFilter) {
- if (locationFilter != null && locationFilter.StartsWith("query:")) {
- locationFilter = StringUtil.GetNameValues(this.Source, '=', '&')["StartSearchLocation"];
- locationFilter = locationFilter.Replace("->", "=");
- string query = locationFilter.Substring(6);
- bool flag = query.StartsWith("fast:");
- if (!flag)
- QueryParser.Parse(query);
- locationFilter = (flag ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Database.SelectSingleItem(query) : Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Axes.SelectSingleItem(query)).ID.ToString();
- }
- return locationFilter;
- }
- protected void RenderStartLocationInput(HtmlTextWriter output) {
- if (!this.EnableSetNewStartLocation)
- return;
- output.Write("<span id='startlocation" + this.ClientID + "' class='startLocationText' style='cursor:pointer;' onMouseOver=\"this.style.color='#666'\" onMouseOut=\"this.style.color='#000'\">" + Translate.Text("Set New Start Location (by ID)") + ": </span>");
- output.Write("<input type='text' width='300px' class='scIgnoreModified' style='width:300px;' value='' id='locationOverride" + this.ClientID + "' style='width:300px'>");
- }
- protected virtual void RenderButton(HtmlTextWriter output, string icon, string click, string id) {
- Assert.ArgumentNotNull((object)output, "output");
- Assert.ArgumentNotNull((object)icon, "icon");
- Assert.ArgumentNotNull((object)click, "click");
- ImageBuilder imageBuilder = new ImageBuilder() { Src = icon, Width = 16, Height = 16, Margin = "2px", ID = id };
- imageBuilder.OnClick = click;
- output.Write(imageBuilder.ToString());
- }
- /// <summary>Gets the item value.</summary>
- /// <param name="item">The item.</param>
- /// <returns>The item value.</returns>
- /// <contract>
- /// <requires name="item" condition="not null" />
- /// <ensures condition="none" />
- /// </contract>
- protected virtual string GetItemValue(Item item) {
- Assert.ArgumentNotNull((object)item, "item");
- return item.ID.ToString();
- }
- /// <summary>Gets the value.</summary>
- /// <returns></returns>
- /// <contract>
- /// <ensures condition="not null" />
- /// </contract>
- public string GetValue() {
- return string.IsNullOrEmpty(CalculatedValue) ? CalculatedValue : Value;
- }
- /// <summary>Sets the value.</summary>
- /// <param name="value">The value.</param>
- public void SetValue(string value) {
- Assert.ArgumentNotNull((object)value, "value");
- if (value != CalculatedValue) {
- if (ItemID == null)
- return;
- var person = Sitecore.Context.ContentDatabase.GetItem(ItemID);
- if (person == null || (person.TemplateID.Guid != GlobalDefinitions.Templates.PersonTemplate.Id && person.TemplateID.Guid != GlobalDefinitions.Templates.TeneoPersonTemplate.Id)) {
- return;
- }
- var glassContext = new SitecoreContext(Sitecore.Context.ContentDatabase);
- var glassPerson = glassContext.GetItem<BlueRubicon.Models.Templates.Data.Person>(person.ID.Guid);
- if (glassPerson == null)
- return;
- var valueIdArray = value.Split(',');
- var calculatedIdArray = CalculatedValue != null ? CalculatedValue.Split(',') : new String[0];
- var clientProfilesRemoved = valueIdArray.Except(calculatedIdArray).ToArray();
- var counter = 0;
- ClientProfile clientProfile = null;
- // Add the person to the Client Profiles that have been added
- for (counter = 0; counter < valueIdArray.Length; counter++) {
- clientProfile = glassContext.GetItem<ClientProfile>(valueIdArray[counter]);
- if (clientProfile != null) {
- if (!clientProfile.CurrentTeam.Contains(glassPerson)) {
- var ct = clientProfile.CurrentTeam.ToList();
- ct.Add(glassPerson);
- clientProfile.CurrentTeam = ct;
- glassContext.Save(clientProfile);
- }
- }
- }
- // Remove the person from the Client Profiles that have been discarded
- for (counter = 0; counter < clientProfilesRemoved.Length; counter++) {
- clientProfile = glassContext.GetItem<ClientProfile>(clientProfilesRemoved[counter]);
- if (clientProfile != null) {
- if (clientProfile.CurrentTeam.Contains(glassPerson)) {
- var ct = clientProfile.CurrentTeam.ToList();
- ct.Remove(glassPerson);
- clientProfile.CurrentTeam = ct;
- glassContext.Save(clientProfile);
- }
- }
- }
- value = CalculatedValue;
- }
- Value = value;
- }
- protected override void OnItemSaved(DataContext context, ID id) {
- base.OnItemSaved(context, id);
- }
- /// <summary>Gets the items.</summary>
- /// <param name="current">The current.</param>
- /// <returns>The items.</returns>
- protected virtual Item[] GetItems(Item current) {
- Assert.ArgumentNotNull((object)current, "current");
- NameValueCollection nameValues1 = StringUtil.GetNameValues(this.Source, '=', '&');
- foreach (string allKey in nameValues1.AllKeys)
- nameValues1[allKey] = HttpUtility.JavaScriptStringEncode(nameValues1[allKey]);
- bool.TryParse(nameValues1["EnableSetNewStartLocation"], out this.enableSetNewStartLocation);
- string str1 = nameValues1["StartSearchLocation"];
- if (str1.IsNullOrEmpty())
- str1 = ItemIDs.RootID.ToString();
- string str2 = this.MakeFilterQueryable(str1);
- if (!Sitecore.Buckets.Extensions.StringExtensions.IsGuid(str2)) {
- string paramValue = str2;
- str2 = ItemIDs.RootID.ToString();
- this.LogSourceQueryError(current, "StartSearchLocation", paramValue, str2);
- }
- string str3 = nameValues1["Filter"];
- if (str3 != null) {
- NameValueCollection nameValues2 = StringUtil.GetNameValues(str3, ':', '|');
- if (nameValues2.Count == 0 && str3 != string.Empty)
- this.filter = this.filter + "&_content=" + str3;
- foreach (string key in nameValues2.Keys)
- this.filter = this.filter + "&" + key + "=" + nameValues2[key];
- }
- List<SearchStringModel> searchStringModel = str3.IsNullOrEmpty() ? new List<SearchStringModel>() : SearchStringModel.ParseQueryString(str3).ToList<SearchStringModel>();
- searchStringModel.Add(new SearchStringModel("_path", Sitecore.Buckets.Util.IdHelper.NormalizeGuid(str2).ToLowerInvariant(), "must"));
- this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "FullTextQuery", "_content", "_content", false);
- this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "Language", "language", "parsedlanguage", false);
- this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "SortField", "sort", "sort", false);
- this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "TemplateFilter", "template", "template", true);
- string sourceString = nameValues1["PageSize"];
- string str4 = sourceString.IsNullOrEmpty() ? "10" : sourceString;
- int result;
- if (!int.TryParse(str4, out result)) {
- result = 10;
- this.LogSourceQueryError(current, "PageSize", str4, result.ToString());
- }
- int pageSize = str4.IsNullOrEmpty() ? 10 : result;
- this.filter = this.filter + "&location=" + Sitecore.Buckets.Util.IdHelper.NormalizeGuid(str2.IsNullOrEmpty() ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).GetParentBucketItemOrRootOrSelf().ID.ToString() : str2, true) + "&pageSize=" + (object)pageSize;
- using (IProviderSearchContext searchContext = ContentSearchManager.GetIndex((IIndexable)(SitecoreIndexableItem)Sitecore.Context.ContentDatabase.GetItem(str2)).CreateSearchContext(SearchSecurityOptions.Default)) {
- System.Linq.IQueryable<SitecoreUISearchResultItem> query = LinqHelper.CreateQuery<SitecoreUISearchResultItem>(searchContext, (IEnumerable<SearchStringModel>)searchStringModel);
- int num = query.Count<SitecoreUISearchResultItem>();
- this.pageNumber = num % pageSize == 0 ? num / pageSize : num / pageSize + 1;
- return query.Page<SitecoreUISearchResultItem>(0, pageSize).ToList<SitecoreUISearchResultItem>().Select<SitecoreUISearchResultItem, Item>((Func<SitecoreUISearchResultItem, Item>)(sitecoreItem => sitecoreItem.GetItem())).Where<Item>((Func<Item, bool>)(i => i != null)).ToArray<Item>();
- }
- }
- protected virtual void LogSourceQueryError(Item current, string paramName, string paramValue, string value) {
- Assert.ArgumentNotNull((object)current, "current");
- Log.SingleWarn(string.Format("The '{0}' parameter in the Source field of the '{1}' field in the '{2}' template contains an invalid value: '{3}'. The following value will be used instead: '{4}'.", (object)paramName, (object)current.Fields[this.FieldID].Name, (object)current.Template.Name, (object)paramValue, (object)value), (object)this);
- }
- protected virtual void ExtractQueryStringAndPopulateModel(NameValueCollection values, List<SearchStringModel> searchStringModel, string parameterName, string filterName, string indexFieldName, bool checkForQuery) {
- string str1 = values[parameterName] ?? string.Empty;
- if (!(str1 != string.Empty))
- return;
- string operation = "must";
- string[] strArray = str1.Split('|');
- if (((IEnumerable<string>)strArray).Count<string>() > 1)
- operation = "should";
- foreach (string templateFilter in strArray) {
- string str2 = templateFilter;
- if (checkForQuery)
- str2 = this.MakeTemplateFilterQueryable(templateFilter);
- if (parameterName == "SortField") {
- if (templateFilter.Contains("[") && templateFilter.Contains("]")) {
- operation = templateFilter.Substring(templateFilter.IndexOf('[') + 1, templateFilter.IndexOf(']') - templateFilter.IndexOf('[') - 1).ToLowerInvariant();
- str2 = str2.Remove(str2.IndexOf('['), str2.IndexOf(']') - str2.IndexOf('[') + 1);
- } else
- operation = "asc";
- }
- this.filter += string.Format("&{0}={1}", (object)filterName, (object)str2);
- searchStringModel.Add(new SearchStringModel(indexFieldName, str2, operation) {
- Operation = operation
- });
- }
- }
- protected virtual string MakeTemplateFilterQueryable(string templateFilter) {
- if (templateFilter != null && templateFilter.StartsWith("query:")) {
- templateFilter = templateFilter.Replace("->", "=");
- string query = templateFilter.Substring(6);
- bool flag = query.StartsWith("fast:");
- if (!flag)
- QueryParser.Parse(query);
- Item[] objArray = !flag ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Axes.SelectItems(query) : Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Database.SelectItems(query);
- templateFilter = string.Empty;
- templateFilter = ((IEnumerable<Item>)objArray).Aggregate<Item, string>(templateFilter, (Func<string, Item, string>)((current1, item) => current1 + item.ID.ToString()));
- }
- return templateFilter;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement