Advertisement
EmanueleCiriachi

ClientProfileSelector

Jul 13th, 2017
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 33.17 KB | None | 0 0
  1. using Sitecore;
  2. using Sitecore.Buckets.Extensions;
  3. using Sitecore.ContentSearch;
  4. using Sitecore.ContentSearch.Linq;
  5. using Sitecore.ContentSearch.SearchTypes;
  6. using Sitecore.ContentSearch.Security;
  7. using Sitecore.ContentSearch.Utilities;
  8. using Sitecore.Data.Items;
  9. using Sitecore.Data.Query;
  10. using Sitecore.Diagnostics;
  11. using Sitecore.Globalization;
  12. using Sitecore.Resources;
  13. using Sitecore.Shell.Applications.ContentEditor;
  14. using Sitecore.Text;
  15. using Sitecore.Web.UI.Sheer;
  16.  
  17. using System;
  18. using System.Linq;
  19. using System.Collections;
  20. using System.Web.UI;
  21. using System.Collections.Specialized;
  22. using System.Text;
  23. using System.Web;
  24. using System.Collections.Generic;
  25. using Sitecore.Web.UI.HtmlControls;
  26. using Sitecore.Data;
  27. using BlueRubicon.Common;
  28. using Glass.Mapper.Sc;
  29. using BlueRubicon.Models.Templates.Data;
  30. using Sitecore.ContentSearch.Linq.Utilities;
  31. using BlueRubicon.Common.Utils;
  32. using Sitecore.Search;
  33.  
  34. namespace BlueRubicon.Models.CustomFields.People {
  35.     public class ClientProfileSelector : Sitecore.Web.UI.HtmlControls.Control, IContentField {
  36.         private string _source;
  37.         private bool enableSetNewStartLocation;
  38.         private string _itemid;
  39.         private int pageNumber = 1;
  40.         protected readonly string Of = Translate.Text("{0} of {1}");
  41.         private readonly string typeHereToSearch = Translate.Text("Type here to search");
  42.         private string filter = string.Empty;
  43.         private string _calculatedValue;
  44.         private bool loadedClientProfiles;
  45.  
  46.         protected string FieldID { get; set; }
  47.  
  48.         public ClientProfileSelector() {
  49.             this.Class = "scContentControlMultilist scClientProfileSelector";
  50.             this.Activation = true;
  51.             this._source = string.Empty;
  52.             this.loadedClientProfiles = false;
  53.         }
  54.  
  55.  
  56.         public override string Value {
  57.             get {
  58.                 Log.Info("Getting value...", this);
  59.                 return this.GetViewStateString("Value");
  60.             }
  61.             set {
  62.                 Log.Info("Setting value...", this);
  63.                 if (!(value != this.Value))
  64.                     return;
  65.                 this.SetViewStateString("Value", value);
  66.             }
  67.         }
  68.  
  69.         /// <summary>
  70.         /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event.
  71.         /// </summary>
  72.         /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
  73.         protected override void OnLoad(EventArgs e) {
  74.             Assert.ArgumentNotNull((object)e, "e");
  75.             base.OnLoad(e);
  76.             string str = Sitecore.Context.ClientPage.ClientRequest.Form[this.ID + "_value"];
  77.             if (str == null)
  78.                 return;
  79.             if (this.GetViewStateString("Value", string.Empty) != str)
  80.                 this.SetModified();
  81.             this.SetViewStateString("Value", str);
  82.         }
  83.  
  84.         /// <summary>Sets the modified flag.</summary>
  85.         protected void SetModified() {
  86.             Sitecore.Context.ClientPage.Modified = true;
  87.         }
  88.  
  89.         /// <summary>
  90.         /// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
  91.         /// </summary>
  92.         /// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
  93.         protected override void OnPreRender(EventArgs e) {
  94.             Assert.ArgumentNotNull((object)e, "e");
  95.             base.OnPreRender(e);
  96.             this.ServerProperties["Value"] = this.ServerProperties["Value"];
  97.         }
  98.  
  99.         public virtual string OutputString(Item item4) {
  100.             Item bucketItemOrParent = item4.GetParentBucketItemOrParent();
  101.             string str = bucketItemOrParent != null ? "- " + bucketItemOrParent.Name : string.Empty;
  102.             return string.Format("{0} ({1} {2} - {3} - {4})", (object)item4.DisplayName, (object)item4.TemplateName, (object)str, (object)item4.Version.Number, (object)item4.Language.Name);
  103.         }
  104.  
  105.         protected override void DoRender(HtmlTextWriter output) {
  106.             if (!ContentSearchManager.Locator.GetInstance<IContentSearchConfigurationSettings>().ItemBucketsEnabled()) {
  107.                 output.Write(Translate.Text("The field cannot be displayed because the Item Buckets feature is disabled."));
  108.             } else {
  109.                 ArrayList selected;
  110.                 OrderedDictionary unselected;
  111.                 this.GetSelectedItems(this.GetItems(Sitecore.Context.ContentDatabase.GetItem(this.ItemID)), out selected, out unselected);
  112.                 StringBuilder stringBuilder = new StringBuilder();
  113.                 foreach (DictionaryEntry dictionaryEntry in unselected) {
  114.                     Item obj = dictionaryEntry.Value as Item;
  115.                     if (obj != null) {
  116.                         stringBuilder.Append(obj.DisplayName + ",");
  117.                         stringBuilder.Append(this.GetItemValue(obj) + ",");
  118.                     }
  119.                 }
  120.                 this.RenderStartLocationInput(output);
  121.                 output.Write("<input type='hidden' width='100%' id='multilistValues" + this.ClientID + "' value='" + (object)stringBuilder + "' style='width: 200px;margin-left:3px;'>");
  122.                 this.ServerProperties["ID"] = (object)this.ID;
  123.                 string str1 = string.Empty;
  124.  
  125.                 output.Write("<input id='" + this.ID + "_Value' type='hidden' value='" + StringUtil.EscapeQuote(Value) + "' />");
  126.                 output.Write("<div class='scContentControlSearchListContainer scClientProfileSelectorTable'>");
  127.                 output.Write("<table" + this.GetControlAttributes() + ">");
  128.                 output.Write("<tr>");
  129.                 output.Write("<td class='scContentControlMultilistCaption' width='50%'>" + Translate.Text("All") + "</td>");
  130.                 output.Write("<td width='20'>" + Images.GetSpacer(20, 1) + "</td>");
  131.                 output.Write("<td class='scContentControlMultilistCaption' width='50%'>" + Translate.Text("Selected") + "</td>");
  132.                 output.Write("<td width='20'>" + Images.GetSpacer(20, 1) + "</td>");
  133.                 output.Write("</tr>");
  134.                 output.Write("<tr>");
  135.                 output.Write("<td valign='top' height='100%'>");
  136.                 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") + ">");
  137.                 output.Write("<a id='prev" + this.ClientID + "' class='hovertext'>" + Images.GetImage("Office/16x16/arrow_left.png", 16, 16, "absmiddle") + Translate.Text("Prev") + "</a>");
  138.                 output.Write("<a id='next" + this.ClientID + "' class='hovertext'> " + Translate.Text("Next") + Images.GetImage("Office/16x16/arrow_right.png", 16, 16, "absmiddle") + "</a>");
  139.                 output.Write("<a id='refresh" + this.ClientID + "' class='hovertext'> " + Images.GetImage("Office/16x16/refresh.png", 16, 16, "absmiddle") + Translate.Text("Refresh") + "</a>");
  140.                 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>");
  141.                 output.Write("<span><span><strong>" + Translate.Text("Page number") + ": </strong></span><span id='pageNumber" + this.ClientID + "'></span></span></div>");
  142.                 string str2 = !UIUtil.IsIE() || UIUtil.GetBrowserMajorVersion() != 9 ? "10" : "11";
  143.                 output.Write("<select id=\"" + this.ID + "_unselected\" class='scBucketListBox' multiple=\"multiple\" size=\"" + str2 + "\"" + str1 + " >");
  144.                 foreach (DictionaryEntry dictionaryEntry in unselected) {
  145.                     Item obj = dictionaryEntry.Value as Item;
  146.                     if (obj != null) {
  147.                         string str3 = this.OutputString(obj);
  148.                         output.Write("<option value='" + this.GetItemValue(obj) + "'>" + str3 + "</option>");
  149.                     }
  150.                 }
  151.                 output.Write("</select>");
  152.                 output.Write("</td>");
  153.                 output.Write("<td valign='top'>");
  154.                 output.Write("<img class='' height='16' width='16' border='0' alt='' style='margin: 15px;' src='/sitecore/shell/themes/standard/Images/blank.png'/>");
  155.                 output.Write("<br />");
  156.                 this.RenderButton(output, "Office/16x16/navigate_right.png", string.Empty, "btnRight" + this.ClientID);
  157.                 output.Write("<br />");
  158.                 this.RenderButton(output, "Office/16x16/navigate_left.png", string.Empty, "btnLeft" + this.ClientID);
  159.                 output.Write("</td>");
  160.                 output.Write("<td valign='top' height='100%'>");
  161.                 output.Write("<select id='" + this.ID + "_selected' class='scBucketListSelectedBox' multiple='multiple' size='10'" + str1 + ">");
  162.                 for (int index = 0; index < selected.Count; ++index) {
  163.                     Item obj1 = selected[index] as Item;
  164.                     if (obj1 != null) {
  165.                         string str3 = this.OutputString(obj1);
  166.                         output.Write("<option value='" + this.GetItemValue(obj1) + "'>" + str3 + "</option>");
  167.                     } else {
  168.                         string path = selected[index] as string;
  169.                         if (path != null) {
  170.                             Item obj2 = Sitecore.Context.ContentDatabase.GetItem(path);
  171.                             string str3 = obj2 == null ? path + (object)' ' + Translate.Text("[Item not found]") : this.OutputString(obj2);
  172.                             output.Write("<option value='" + path + "'>" + str3 + "</option>");
  173.                         }
  174.                     }
  175.                 }
  176.                 output.Write("</select>");
  177.                 output.Write("</td>");
  178.                 output.Write("<td valign='top'>");
  179.                 output.Write("<img class='' height='16' width='16' border='0' alt='' style='margin: 15px 0;' src='/sitecore/shell/themes/standard/Images/blank.png'/>");
  180.                 output.Write("<br />");
  181.                 this.RenderButton(output, "Office/16x16/navigate_up.png", "javascript:scContent.multilistMoveUp('" + this.ID + "')", "btnUp" + this.ClientID);
  182.                 output.Write("<br />");
  183.                 this.RenderButton(output, "Office/16x16/navigate_down.png", "javascript:scContent.multilistMoveDown('" + this.ID + "')", "btnDown" + this.ClientID);
  184.                 output.Write("</td>");
  185.                 output.Write("</tr>");
  186.                 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>");
  187.                 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>");
  188.                 output.Write("</table>");
  189.                 output.Write("</div>");
  190.  
  191.                 this.RenderScript(output);
  192.             }
  193.         }
  194.  
  195.         public override void HandleMessage(Message message) {
  196.             Assert.ArgumentNotNull((object)message, "message");
  197.             base.HandleMessage(message);
  198.             if (!(message["id"] == this.ID))
  199.                 return;
  200.             switch (message.Name) {
  201.                 case "bucketsearchlist:selectall":
  202.                     SheerResponse.Eval("scContent.multilistMoveRight('" + this.ID + "', true)");
  203.                     break;
  204.                 case "bucketsearchlist:unselectall":
  205.                     SheerResponse.Eval("scContent.multilistMoveLeft('" + this.ID + "', true)");
  206.                     break;
  207.             }
  208.         }
  209.  
  210.         protected virtual void RenderScript(HtmlTextWriter output) {
  211.             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>";
  212.             output.Write(str);
  213.         }
  214.  
  215.         public virtual string JavaScriptOutputString(string clientId) {
  216.             return "responseParsed" + clientId + ".items[i].Name + ' (' + responseParsed" + clientId + ".items[i].TemplateName + ' - ' + responseParsed" + clientId + ".items[i].Bucket + ')'";
  217.         }
  218.  
  219.         /// <summary>Gets or sets the item language.</summary>
  220.         /// <value>The item language.</value>
  221.         public string ItemLanguage {
  222.             get {
  223.                 return StringUtil.GetString(this.ViewState["ItemLanguage"]);
  224.             }
  225.             set {
  226.                 Assert.ArgumentNotNull((object)value, "value");
  227.                 this.ViewState["ItemLanguage"] = (object)value;
  228.             }
  229.         }
  230.  
  231.         /// <summary>Gets or sets the item ID.</summary>
  232.         /// <value>The item ID.</value>
  233.         /// <contract>
  234.         ///   <requires name="value" condition="not null" />
  235.         ///   <ensures condition="nullable" />
  236.         /// </contract>
  237.         public string ItemID {
  238.             get {
  239.                 return this._itemid;
  240.             }
  241.             set {
  242.                 Assert.ArgumentNotNull((object)value, "value");
  243.  
  244.                 // If the value to be set is different, we need to initialize the Calculated Value as well as the Client Profiles
  245.                 if (this._itemid != value) {
  246.                     this.CheckOrUpdateCalculatedValue(value);
  247.                 }
  248.  
  249.                 this._itemid = value;
  250.             }
  251.         }
  252.  
  253.         private void CheckOrUpdateCalculatedValue(string itemId = null) {
  254.             if (itemId == null) {
  255.                 itemId = ItemID;
  256.             }
  257.  
  258.             if (string.IsNullOrEmpty(itemId))
  259.                 return;
  260.  
  261.             var person = Sitecore.Context.ContentDatabase.GetItem(itemId);
  262.             if (person == null || (person.TemplateID.Guid != GlobalDefinitions.Templates.PersonTemplate.Id && person.TemplateID.Guid != GlobalDefinitions.Templates.TeneoPersonTemplate.Id)) {
  263.                 return;
  264.             }
  265.  
  266.             var glassContext = new SitecoreContext(Sitecore.Context.ContentDatabase);
  267.             var glassPerson = glassContext.GetItem<BlueRubicon.Models.Templates.Data.BasePerson>(person.ID.Guid);
  268.  
  269.             if (this.loadedClientProfiles == false) {
  270.                 glassPerson.CurrentClients = CalculateClientProfile(glassContext, glassPerson);
  271.                 this.loadedClientProfiles = true;
  272.             }
  273.  
  274.             if (glassPerson == null)
  275.                 return;
  276.  
  277.             if (glassPerson.CurrentClients == null) {
  278.                 CalculatedValue = string.Empty;
  279.             } else {
  280.                 var currentClients = string.Join("|", glassPerson.CurrentClients.ToArray<ClientProfile>().Select(i => i.Id));
  281.  
  282.                 if (!string.IsNullOrEmpty(currentClients)) {
  283.                     CalculatedValue = currentClients;
  284.                 }
  285.             }
  286.         }
  287.  
  288.         public string CalculatedValue {
  289.             get {
  290.                 return this._calculatedValue;
  291.             }
  292.             set {
  293.                 this._calculatedValue = value;
  294.             }
  295.         }
  296.  
  297.         private List<ClientProfile> CalculateClientProfile(SitecoreContext context, BasePerson person) {
  298.             var baseFilter = PredicateBuilder.True<ClientProfile>();
  299.             List<ClientProfile> List = new List<ClientProfile>();
  300.  
  301.             baseFilter = baseFilter
  302.                 .And(i => i.ItemAncestors.Contains(GlobalDefinitions.Data.ContentRoot))
  303.                 .And(i => i.Enabled)
  304.                 .And(i => i.TemplateName == GlobalDefinitions.Templates.ClientProfileTemplate.Name);
  305.  
  306.             var filter = baseFilter
  307.                 .And(i => i.CurrentTeamIds.Contains(person.Id));
  308.  
  309.             OrderBy<ClientProfile>[] orderBy = {
  310.                 new OrderBy<ClientProfile>
  311.                 {
  312.                     Clause = i => i.Created,
  313.                     Descending = true
  314.                 }
  315.             };
  316.  
  317.             var SearchIndex = ContentSearchManager.GetIndex("sitecore_master_index");
  318.             IProviderSearchContext SearchContext = SearchIndex.CreateSearchContext();
  319.             var query = SearchContext.GetQueryable<ClientProfile>();
  320.             query = query.Where(filter);
  321.             var results = query.GetResults();
  322.  
  323.             foreach (var hit in results.Hits) {
  324.                 ClientProfile profile = context.GetItem<ClientProfile>(hit.Document.Uri.ItemID.ToGuid());
  325.                 if (profile != null) {
  326.                     List.Add(profile);
  327.                 }
  328.             }
  329.  
  330.             return List;
  331.         }
  332.  
  333.         /// <summary>Gets or sets the source.</summary>
  334.         /// <value>The source.</value>
  335.         /// <contract>
  336.         ///   <requires name="value" condition="not null" />
  337.         ///   <ensures condition="nullable" />
  338.         /// </contract>
  339.         public string Source {
  340.             get {
  341.                 return this._source;
  342.             }
  343.             set {
  344.                 Assert.ArgumentNotNull((object)value, "value");
  345.                 this._source = value;
  346.             }
  347.         }
  348.  
  349.         protected int PageNumber {
  350.             get {
  351.                 return this.pageNumber;
  352.             }
  353.             set {
  354.                 this.pageNumber = value;
  355.             }
  356.         }
  357.  
  358.         protected bool EnableSetNewStartLocation {
  359.             get {
  360.                 return this.enableSetNewStartLocation;
  361.             }
  362.             set {
  363.                 this.enableSetNewStartLocation = value;
  364.             }
  365.         }
  366.  
  367.         protected string Filter {
  368.             get {
  369.                 return this.filter;
  370.             }
  371.             set {
  372.                 this.filter = value;
  373.             }
  374.         }
  375.  
  376.         protected string TypeHereToSearch
  377.         {
  378.           get
  379.           {
  380.             return this.typeHereToSearch;
  381.           }
  382.         }
  383.  
  384.         protected virtual void GetSelectedItems(Item[] sources, out ArrayList selected, out OrderedDictionary unselected) {
  385.             Assert.ArgumentNotNull((object)sources, "sources");
  386.             ListString listString;
  387.  
  388.             if (this.CalculatedValue != null) {
  389.                 listString = new ListString(this.CalculatedValue);
  390.             } else {
  391.                 listString = new ListString(Value);
  392.             }
  393.  
  394.             unselected = new OrderedDictionary();
  395.             selected = new ArrayList(listString.Count);
  396.             for (int index = 0; index < listString.Count; ++index)
  397.                 selected.Add((object)listString[index]);
  398.             foreach (Item source in sources) {
  399.                 string str = source.ID.ToString();
  400.                 int index = listString.IndexOf(str);
  401.                 if (index >= 0)
  402.                     selected[index] = (object)source;
  403.                 else
  404.                     unselected.Add((object)MainUtil.GetSortKey(source.Name), (object)source);
  405.             }
  406.         }
  407.  
  408.         protected string ScriptParameters {
  409.             get {
  410.                 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));
  411.             }
  412.         }
  413.  
  414.         protected string MakeFilterQueryable(string locationFilter) {
  415.             if (locationFilter != null && locationFilter.StartsWith("query:")) {
  416.                 locationFilter = StringUtil.GetNameValues(this.Source, '=', '&')["StartSearchLocation"];
  417.                 locationFilter = locationFilter.Replace("->", "=");
  418.                 string query = locationFilter.Substring(6);
  419.                 bool flag = query.StartsWith("fast:");
  420.                 if (!flag)
  421.                     QueryParser.Parse(query);
  422.                 locationFilter = (flag ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Database.SelectSingleItem(query) : Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Axes.SelectSingleItem(query)).ID.ToString();
  423.             }
  424.             return locationFilter;
  425.         }
  426.  
  427.         protected void RenderStartLocationInput(HtmlTextWriter output) {
  428.             if (!this.EnableSetNewStartLocation)
  429.                 return;
  430.  
  431.             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>");
  432.             output.Write("<input type='text' width='300px' class='scIgnoreModified' style='width:300px;' value='' id='locationOverride" + this.ClientID + "' style='width:300px'>");
  433.         }
  434.  
  435.         protected virtual void RenderButton(HtmlTextWriter output, string icon, string click, string id) {
  436.             Assert.ArgumentNotNull((object)output, "output");
  437.             Assert.ArgumentNotNull((object)icon, "icon");
  438.             Assert.ArgumentNotNull((object)click, "click");
  439.             ImageBuilder imageBuilder = new ImageBuilder() { Src = icon, Width = 16, Height = 16, Margin = "2px", ID = id };
  440.             imageBuilder.OnClick = click;
  441.            
  442.             output.Write(imageBuilder.ToString());
  443.         }
  444.  
  445.         /// <summary>Gets the item value.</summary>
  446.         /// <param name="item">The item.</param>
  447.         /// <returns>The item value.</returns>
  448.         /// <contract>
  449.         ///   <requires name="item" condition="not null" />
  450.         ///   <ensures condition="none" />
  451.         /// </contract>
  452.         protected virtual string GetItemValue(Item item) {
  453.             Assert.ArgumentNotNull((object)item, "item");
  454.             return item.ID.ToString();
  455.         }
  456.  
  457.         /// <summary>Gets the value.</summary>
  458.         /// <returns></returns>
  459.         /// <contract>
  460.         ///   <ensures condition="not null" />
  461.         /// </contract>
  462.         public string GetValue() {
  463.             return string.IsNullOrEmpty(CalculatedValue) ? CalculatedValue : Value;
  464.         }
  465.  
  466.         /// <summary>Sets the value.</summary>
  467.         /// <param name="value">The value.</param>
  468.         public void SetValue(string value) {
  469.             Assert.ArgumentNotNull((object)value, "value");
  470.  
  471.             if (value != CalculatedValue) {
  472.                 if (ItemID == null)
  473.                     return;
  474.  
  475.                 var person = Sitecore.Context.ContentDatabase.GetItem(ItemID);
  476.                 if (person == null || (person.TemplateID.Guid != GlobalDefinitions.Templates.PersonTemplate.Id && person.TemplateID.Guid != GlobalDefinitions.Templates.TeneoPersonTemplate.Id)) {
  477.                     return;
  478.                 }
  479.  
  480.                 var glassContext = new SitecoreContext(Sitecore.Context.ContentDatabase);
  481.                 var glassPerson = glassContext.GetItem<BlueRubicon.Models.Templates.Data.Person>(person.ID.Guid);
  482.  
  483.                 if (glassPerson == null)
  484.                     return;
  485.  
  486.                 var valueIdArray = value.Split(',');
  487.                 var calculatedIdArray = CalculatedValue != null ? CalculatedValue.Split(',') : new String[0];
  488.                 var clientProfilesRemoved = valueIdArray.Except(calculatedIdArray).ToArray();
  489.  
  490.                 var counter = 0;
  491.                 ClientProfile clientProfile = null;
  492.  
  493.                 // Add the person to the Client Profiles that have been added
  494.                 for (counter = 0; counter < valueIdArray.Length; counter++) {
  495.                     clientProfile = glassContext.GetItem<ClientProfile>(valueIdArray[counter]);
  496.  
  497.                     if (clientProfile != null) {
  498.                         if (!clientProfile.CurrentTeam.Contains(glassPerson)) {
  499.                            
  500.                             var ct = clientProfile.CurrentTeam.ToList();
  501.                             ct.Add(glassPerson);
  502.                             clientProfile.CurrentTeam = ct;
  503.  
  504.                             glassContext.Save(clientProfile);
  505.                         }
  506.                     }
  507.                 }
  508.  
  509.                 // Remove the person from the Client Profiles that have been discarded
  510.                 for (counter = 0; counter < clientProfilesRemoved.Length; counter++) {
  511.                     clientProfile = glassContext.GetItem<ClientProfile>(clientProfilesRemoved[counter]);
  512.  
  513.                     if (clientProfile != null) {
  514.                         if (clientProfile.CurrentTeam.Contains(glassPerson)) {
  515.  
  516.                             var ct = clientProfile.CurrentTeam.ToList();
  517.                             ct.Remove(glassPerson);
  518.                             clientProfile.CurrentTeam = ct;
  519.  
  520.                             glassContext.Save(clientProfile);
  521.                         }
  522.                     }
  523.                 }
  524.  
  525.                 value = CalculatedValue;
  526.             }
  527.  
  528.             Value = value;
  529.         }
  530.  
  531.         protected override void OnItemSaved(DataContext context, ID id) {
  532.             base.OnItemSaved(context, id);
  533.         }
  534.  
  535.         /// <summary>Gets the items.</summary>
  536.         /// <param name="current">The current.</param>
  537.         /// <returns>The items.</returns>
  538.         protected virtual Item[] GetItems(Item current) {
  539.             Assert.ArgumentNotNull((object)current, "current");
  540.             NameValueCollection nameValues1 = StringUtil.GetNameValues(this.Source, '=', '&');
  541.             foreach (string allKey in nameValues1.AllKeys)
  542.                 nameValues1[allKey] = HttpUtility.JavaScriptStringEncode(nameValues1[allKey]);
  543.             bool.TryParse(nameValues1["EnableSetNewStartLocation"], out this.enableSetNewStartLocation);
  544.             string str1 = nameValues1["StartSearchLocation"];
  545.             if (str1.IsNullOrEmpty())
  546.                 str1 = ItemIDs.RootID.ToString();
  547.             string str2 = this.MakeFilterQueryable(str1);
  548.             if (!Sitecore.Buckets.Extensions.StringExtensions.IsGuid(str2)) {
  549.                 string paramValue = str2;
  550.                 str2 = ItemIDs.RootID.ToString();
  551.                 this.LogSourceQueryError(current, "StartSearchLocation", paramValue, str2);
  552.             }
  553.             string str3 = nameValues1["Filter"];
  554.             if (str3 != null) {
  555.                 NameValueCollection nameValues2 = StringUtil.GetNameValues(str3, ':', '|');
  556.                 if (nameValues2.Count == 0 && str3 != string.Empty)
  557.                     this.filter = this.filter + "&_content=" + str3;
  558.                 foreach (string key in nameValues2.Keys)
  559.                     this.filter = this.filter + "&" + key + "=" + nameValues2[key];
  560.             }
  561.             List<SearchStringModel> searchStringModel = str3.IsNullOrEmpty() ? new List<SearchStringModel>() : SearchStringModel.ParseQueryString(str3).ToList<SearchStringModel>();
  562.             searchStringModel.Add(new SearchStringModel("_path", Sitecore.Buckets.Util.IdHelper.NormalizeGuid(str2).ToLowerInvariant(), "must"));
  563.             this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "FullTextQuery", "_content", "_content", false);
  564.             this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "Language", "language", "parsedlanguage", false);
  565.             this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "SortField", "sort", "sort", false);
  566.             this.ExtractQueryStringAndPopulateModel(nameValues1, searchStringModel, "TemplateFilter", "template", "template", true);
  567.             string sourceString = nameValues1["PageSize"];
  568.             string str4 = sourceString.IsNullOrEmpty() ? "10" : sourceString;
  569.             int result;
  570.             if (!int.TryParse(str4, out result)) {
  571.                 result = 10;
  572.                 this.LogSourceQueryError(current, "PageSize", str4, result.ToString());
  573.             }
  574.             int pageSize = str4.IsNullOrEmpty() ? 10 : result;
  575.             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;
  576.             using (IProviderSearchContext searchContext = ContentSearchManager.GetIndex((IIndexable)(SitecoreIndexableItem)Sitecore.Context.ContentDatabase.GetItem(str2)).CreateSearchContext(SearchSecurityOptions.Default)) {
  577.                 System.Linq.IQueryable<SitecoreUISearchResultItem> query = LinqHelper.CreateQuery<SitecoreUISearchResultItem>(searchContext, (IEnumerable<SearchStringModel>)searchStringModel);
  578.                 int num = query.Count<SitecoreUISearchResultItem>();
  579.                 this.pageNumber = num % pageSize == 0 ? num / pageSize : num / pageSize + 1;
  580.                 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>();
  581.             }
  582.         }
  583.  
  584.         protected virtual void LogSourceQueryError(Item current, string paramName, string paramValue, string value) {
  585.             Assert.ArgumentNotNull((object)current, "current");
  586.             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);
  587.         }
  588.  
  589.         protected virtual void ExtractQueryStringAndPopulateModel(NameValueCollection values, List<SearchStringModel> searchStringModel, string parameterName, string filterName, string indexFieldName, bool checkForQuery) {
  590.             string str1 = values[parameterName] ?? string.Empty;
  591.             if (!(str1 != string.Empty))
  592.                 return;
  593.             string operation = "must";
  594.             string[] strArray = str1.Split('|');
  595.             if (((IEnumerable<string>)strArray).Count<string>() > 1)
  596.                 operation = "should";
  597.             foreach (string templateFilter in strArray) {
  598.                 string str2 = templateFilter;
  599.                 if (checkForQuery)
  600.                     str2 = this.MakeTemplateFilterQueryable(templateFilter);
  601.                 if (parameterName == "SortField") {
  602.                     if (templateFilter.Contains("[") && templateFilter.Contains("]")) {
  603.                         operation = templateFilter.Substring(templateFilter.IndexOf('[') + 1, templateFilter.IndexOf(']') - templateFilter.IndexOf('[') - 1).ToLowerInvariant();
  604.                         str2 = str2.Remove(str2.IndexOf('['), str2.IndexOf(']') - str2.IndexOf('[') + 1);
  605.                     } else
  606.                         operation = "asc";
  607.                 }
  608.                 this.filter += string.Format("&{0}={1}", (object)filterName, (object)str2);
  609.                 searchStringModel.Add(new SearchStringModel(indexFieldName, str2, operation) {
  610.                     Operation = operation
  611.                 });
  612.             }
  613.         }
  614.  
  615.         protected virtual string MakeTemplateFilterQueryable(string templateFilter) {
  616.             if (templateFilter != null && templateFilter.StartsWith("query:")) {
  617.                 templateFilter = templateFilter.Replace("->", "=");
  618.                 string query = templateFilter.Substring(6);
  619.                 bool flag = query.StartsWith("fast:");
  620.                 if (!flag)
  621.                     QueryParser.Parse(query);
  622.                 Item[] objArray = !flag ? Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Axes.SelectItems(query) : Sitecore.Context.ContentDatabase.GetItem(this.ItemID).Database.SelectItems(query);
  623.                 templateFilter = string.Empty;
  624.                 templateFilter = ((IEnumerable<Item>)objArray).Aggregate<Item, string>(templateFilter, (Func<string, Item, string>)((current1, item) => current1 + item.ID.ToString()));
  625.             }
  626.             return templateFilter;
  627.         }
  628.     }
  629. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement