예제 #1
0
        private void clientAutoComplete_OnConfirmCompletion(object sender, AutoCompleteItem e)
        {
            var asClientItem = e as ModelItem;

            if (asClientItem == null)
            {
                return;
            }

            var item = asClientItem.Item;

            this.selectClient(item);

            this.projectTextBox.Focus();
        }
예제 #2
0
        private void workspaceAutoComplete_OnConfirmCompletion(object sender, AutoCompleteItem e)
        {
            var asWorkspaceItem = e as ModelItem;

            if (asWorkspaceItem == null)
            {
                return;
            }

            var item = asWorkspaceItem.Item;

            this.selectWorkspace(item);

            this.clientTextBox.Focus();
        }
        private void PutAutoCompleteSuggestion()
        {
            if (_autoBox.SelectedItems.Count == 1)
            {
                int    pos = ExpressionText.SelectionStart;
                string context;
                char?  c = GetContextBuffer(out context);

                AutoCompleteItem aci = (_autoBox.SelectedItem as ImageListBoxItem).Tag as AutoCompleteItem;

                string fullText = aci.AutoCompleteText;

                int start     = pos - context.Length;
                int newPos    = start + fullText.Length;
                int selLength = -1;

                //if it's a function, highlight the parameter (or the first parameter if there is multiple arguments
                if (aci.Type == AutoCompleteItemType.Function)
                {
                    newPos = start + aci.Name.Length + 1; //Position the caret just after the opening bracket

                    //Has at least two arguments
                    int idx = fullText.IndexOf(",");
                    if (idx > 0)
                    {
                        selLength = idx - aci.Name.Length - 1;
                    }
                    else
                    {
                        selLength = fullText.IndexOf(")") - fullText.IndexOf("(") - 1;
                    }
                }

                string prefix = ExpressionText.Text.Substring(0, start);
                string suffix = ExpressionText.Text.Substring(pos, ExpressionText.Text.Length - pos);

                ExpressionText.Text           = prefix + fullText + suffix;
                ExpressionText.SelectionStart = newPos;
                if (selLength > 0)
                {
                    ExpressionText.SelectionLength = selLength;
                }
                ExpressionText.ScrollToCaret();
            }
        }
        public dynamic AutoCompleteSearch(string searchText, string indexName)
        {
            // Pass the specified suggestion text and return the fields
            Uri uri = new Uri(_serviceUri, "/indexes/" + indexName + "/docs/autocomplete?suggesterName=sg&$top=7&autoCompleteMode=oneterm&search=" + Uri.EscapeDataString(searchText));
            HttpResponseMessage response = AzureSearchHelper.SendSearchRequest(_httpClient, HttpMethod.Get, uri);

            AzureSearchHelper.EnsureSuccessfulSearchResponse(response);
            List <AutoCompleteItem> aciList = new List <AutoCompleteItem>();

            foreach (var option in AzureSearchHelper.DeserializeJson <dynamic>(response.Content.ReadAsStringAsync().Result).value)
            {
                AutoCompleteItem aci = new AutoCompleteItem();
                aci.id   = (string)option["id"];
                aci.desc = (string)option["queryPlusText"];
                aciList.Add(aci);
            }

            return(aciList);
        }
예제 #5
0
        private void autoComplete_OnConfirmCompletion(object sender, AutoCompleteItem e)
        {
            var asStringItem = e as StringItem;

            if (asStringItem == null)
            {
                return;
            }

            var tag = asStringItem.Text;

            this.tryAddTag(tag);
            this.textBox.SetText("");

            if (this.autoComplete.IsOpen)
            {
                this.autoComplete.OpenAndShowAll();
            }
        }
예제 #6
0
        private string GetInsertText(AutoCompleteItem autoCompleteItem)
        {
            if (String.IsNullOrEmpty(autoCompleteItem.Description) &&
                autoCompleteItem.ItemType == AutoCompleteItemType.Method &&
                autoCompleteItem.Params != null && autoCompleteItem.Params.Length > 0
                )
            {
                List <string> functionParams = new List <string>();
                var           i = 1;

                foreach (var param in autoCompleteItem.Params)
                {
                    functionParams.Add(Handle.ToString("param" + i++));
                }

                return($"{autoCompleteItem.Name}({String.Join(", ", functionParams)})");
            }
            return(autoCompleteItem.Name);
        }
예제 #7
0
        private string GetLabelWithDescription(AutoCompleteItem autoCompleteItem)
        {
            if (autoCompleteItem.ItemType == AutoCompleteItemType.Method)
            {
                if (autoCompleteItem.Params != null && autoCompleteItem.Params.Length > 0)
                {
                    List <string> functionParams = new List <string>();
                    var           i = 1;
                    foreach (var param in autoCompleteItem.Params)
                    {
                        functionParams.Add(Handle.ToString(param.Type) + " param" + i++);
                    }

                    return($"{autoCompleteItem.Name}({String.Join(", ", functionParams)})");
                }
                return($"{autoCompleteItem.Name}()");
            }

            return(autoCompleteItem.Name);
        }
예제 #8
0
        /// <summary>
        /// Add item to selected list.
        /// </summary>
        /// <param name="item">The item to be added.</param>
        void AddSelectedItem(AutoCompleteItem item)
        {
            // Reset text field value.
            TextInputValue = "";

            // Hide the list.
            isShown = false;

            // Empty the list if MultiSelect is disabled.
            if (!MultiSelect)
            {
                SelectedItems.Clear();
            }

            // Add the item if its not exists.
            if (SelectedItems.Find((it) => it.Key == item.Key) == null)
            {
                SelectedItems.Add(item);
            }
        }
예제 #9
0
        private void descriptionAutoComplete_OnConfirmCompletion(object sender, AutoCompleteItem e)
        {
            var asTimerItem = e as TimerItem;

            if (asTimerItem == null)
            {
                return;
            }

            if (!this.hasTimeEntry())
            {
                Console.WriteLine("Cannot apply description change: No time entry.");
                return;
            }

            var item = asTimerItem.Item;

            this.descriptionTextBox.SetText(item.Description);

            Toggl.SetTimeEntryDescription(this.timeEntry.GUID, item.Description);

            if (item.ProjectID != 0)
            {
                Toggl.SetTimeEntryProject(this.timeEntry.GUID, item.TaskID, item.ProjectID, "");
            }

            this.billableCheckBox.IsChecked = item.Billable;
            this.billableCheckBox_OnClick(null, null);

            if (!string.IsNullOrEmpty(item.Tags) && this.tagList.TagCount == 0)
            {
                this.tagList.Clear(true);
                if (item.Tags != null)
                {
                    this.tagList.AddTags(item.Tags.Split(new[] { Toggl.TagSeparator },
                                                         StringSplitOptions.RemoveEmptyEntries));
                }
                this.updateTagListEmptyText();
                this.saveTags();
            }
        }
        private void descriptionAutoComplete_OnConfirmCompletion(object sender, AutoCompleteItem e)
        {
            var asTimerItem = e as TimerItem;

            if (asTimerItem == null)
            {
                return;
            }

            if (!this.hasTimeEntry())
            {
                Console.WriteLine("Cannot apply description change: No time entry.");
                return;
            }

            var item = asTimerItem.Item;

            // TODO: fill in project already if possible (instead of waiting for dll)?

            Toggl.SetTimeEntryDescription(this.timeEntry.GUID, item.Description);
            Toggl.SetTimeEntryProject(this.timeEntry.GUID, item.TaskID, item.ProjectID, "");
        }
예제 #11
0
        public ActionResult AutoComplete()
        {
            if (DoAction == ActionType.Add) //Nếu thêm từ khóa
            {
                JsonMessage msg;
                var         tagValue = Request["Values"];

                if (string.IsNullOrEmpty(tagValue))
                {
                    msg = new JsonMessage
                    {
                        Erros   = true,
                        Message = "Bạn phải nhập tên từ khóa"
                    };
                }
                else
                {
                    var tag = _tagDa.AddOrGet(tagValue);
                    msg = new JsonMessage
                    {
                        Erros   = false,
                        ID      = tag.ID.ToString(),
                        Message = tag.Name
                    };
                }
                return(Json(msg, JsonRequestBehavior.AllowGet));
            }
            var query       = Request["query"];
            var ltsResults  = _tagDa.GetListSimpleByAutoComplete(query, 10);
            var resulValues = new AutoCompleteItem
            {
                query       = query,
                data        = ltsResults.Select(o => o.ID.ToString()).ToList(),
                suggestions = ltsResults.Select(o => o.Name).ToList()
            };

            return(Json(resulValues, JsonRequestBehavior.AllowGet));
        }
예제 #12
0
 // Sets the selected item (from user initiated action)
 // This may be overriden to handle different types of selecteditems        
 internal void UserSetSelectedItem(AutoCompleteItem selectedItem)
 {
     SelectedItem = selectedItem;
     System.Diagnostics.Debug.WriteLine("Selected Item set: {0}", selectedItem == null ? "null" : selectedItem.Name);
 }
예제 #13
0
        public string ConstructorShouldWorkCorrectly(string displayValue, string description)
        {
            var item = new AutoCompleteItem(displayValue, description);

            return(String.Format("{0}:{1}", item.DisplayName, item.Description));
        }
예제 #14
0
 public void SetUp()
 {
     testee = new AutoCompleteItem("Test", "Test Description");
 }
예제 #15
0
 private void select(AutoCompleteItem item)
 {
     this.select(item, false);
 }
예제 #16
0
        public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            jQueryObject        container    = jQuery.FromElement(element);
            jQueryObject        inputField   = container.Find(".sparkle-input-lookup-part");
            jQueryObject        selectButton = container.Find(".sparkle-input-lookup-button-part");
            EntityReference     _value       = new EntityReference(null, null, null);
            AutoCompleteOptions options      = new AutoCompleteOptions();

            options.MinLength = 100000; // Don't enable type down - use search button (or return)
            options.Delay     = 0;
            options.Position  = new Dictionary <string, object>("collision", "fit");

            bool justSelected = false;

            // Set the value when selected
            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item;
                if (_value == null)
                {
                    _value = new EntityReference(null, null, null);
                }
                string value = item.Label;
                inputField.Value(value);
                _value.Id          = ((Guid)item.Value);
                _value.Name        = item.Label;
                _value.LogicalName = (string)item.Data;
                justSelected       = true;
                TrySetObservable(valueAccessor, inputField, _value);
                Script.Literal("return false;");
            };


            // Get the query command
            Action <string, Action <EntityCollection> > queryCommand = (Action <string, Action <EntityCollection> >)((object)allBindingsAccessor()["queryCommand"]);
            string nameAttribute     = ((string)allBindingsAccessor()["nameAttribute"]);
            string idAttribute       = ((string)allBindingsAccessor()["idAttribute"]);
            string typeCodeAttribute = ((string)allBindingsAccessor()["typeCodeAttribute"]);

            // wire up source to CRM search
            Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response)
            {
                Action <EntityCollection> queryCallBack = delegate(EntityCollection fetchResult)
                {
                    AutoCompleteItem[] results = new AutoCompleteItem[fetchResult.Entities.Count];

                    for (int i = 0; i < fetchResult.Entities.Count; i++)
                    {
                        results[i]       = new AutoCompleteItem();
                        results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(nameAttribute);
                        results[i].Value = fetchResult.Entities[i].GetAttributeValue(idAttribute);
                        results[i].Data  = fetchResult.Entities[i].LogicalName;
                        string typeCodeName = fetchResult.Entities[i].LogicalName;
                        // Get the type code from the name to find the icon
                        if (!string.IsNullOrEmpty(typeCodeAttribute))
                        {
                            typeCodeName = fetchResult.Entities[i].GetAttributeValue(typeCodeAttribute).ToString();
                        }

                        results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName);
                    }


                    response(results);

                    // Disable it now so typing doesn't trigger a search
                    AutoCompleteOptions disableOption = new AutoCompleteOptions();
                    disableOption.MinLength = 100000;
                    inputField.Plugin <AutoCompleteObject>().AutoComplete(disableOption);
                };

                // Call the function with the correct 'this' context
                Script.Literal("{0}.call({1}.$parent,{2},{3})", queryCommand, context, request.Term, queryCallBack);
            };

            options.Source = queryDelegate;
            options.Focus  = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent)
            {
                // Prevent the value being updated in the text box we scroll through the results
                Script.Literal("return false;");
            };
            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);

            // Set render template
            ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item)
            {
                return((object)jQuery.Select("<li>").Append("<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span><span class='sparkle-menu-item-label'>" + item.Label + "</span></a>").AppendTo((jQueryObject)ul));
            };

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                AutoCompleteOptions enableOption = new AutoCompleteOptions();
                enableOption.MinLength           = 0;
                inputField.Focus();
                inputField.Plugin <AutoCompleteObject>().AutoComplete(enableOption);

                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search);
            });

            // handle the field changing
            inputField.Change(delegate(jQueryEvent e)
            {
                if (inputField.GetValue() != _value.Name)
                {
                    TrySetObservable(valueAccessor, inputField, null);
                }
            });

            Action disposeCallBack = delegate()
            {
                if ((bool)Script.Literal("$({0}).data('ui-autocomplete')!=undefined", inputField))
                {
                    //inputField.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Destroy);
                    Script.Literal("$({0}).autocomplete(\"destroy\")", inputField);
                }
            };

            //handle disposal (if KO removes by the template binding)
            Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack);
            Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null);



            // Bind return to searching
            inputField.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    selectButton.Click();
                }
                else if (e.Which == 13)
                {
                    return;
                }
                switch (e.Which)
                {
                case 13:     // Return
                case 38:     // Up - don't navigate - but use the dropdown to select search results
                case 40:     // Down - don't navigate - but use the dropdown to select search results
                    e.PreventDefault();
                    e.StopPropagation();
                    break;
                }
                justSelected = false;
            });

            //Script.Literal("return { controlsDescendantBindings: true };");
        }
 // Sets the selected item (from user initiated action)
 // This may be overriden to handle different types of selecteditems
 internal void UserSetSelectedItem(AutoCompleteItem selectedItem)
 {
     SelectedItem = selectedItem;
     System.Diagnostics.Debug.WriteLine("Selected Item set: {0}", selectedItem == null ? "null" : selectedItem.Name);
 }
예제 #18
0
 internal static void Add(this SortedDictionary <string, AutoCompleteItem> dict, AutoCompleteItem item)
 {
     dict[item.Value] = item;
 }
		private static IEnumerable<AutoCompleteItem> GetAutoCompleteItem(ISymbol symbol, bool showClassesAsStatic)
		{
			var result = new List<AutoCompleteItem>();

			var item = new AutoCompleteItem {Name = symbol.Name};

			var itemDoc = symbol.GetDocumentationComment(CultureInfo.GetCultureInfo("en-US"));
				
			if (itemDoc != null)
				item.Description = itemDoc.SummaryTextOpt;

			switch (symbol.Kind)
			{
				case CommonSymbolKind.Method:
					item.ItemType = AutoCompleteItemType.Method;
					var methodSymbol = (IMethodSymbol) symbol;
					item.IsExtension = methodSymbol.IsExtensionMethod;
					item.IsStatic = methodSymbol.IsStatic;
					item.Type = methodSymbol.ReturnsVoid ? "void" : methodSymbol.ReturnType.Name;
					//args
					item.Params = GetSymbolParameters(methodSymbol.Parameters, itemDoc);
					item.IsGeneric = methodSymbol.IsGenericMethod;
					break;
				case CommonSymbolKind.Local:
					item.ItemType = AutoCompleteItemType.Variable;
					var localSymbol = (ILocalSymbol) symbol;
					item.Type = localSymbol.Type.Name;
					break;
				case CommonSymbolKind.Field:
					item.ItemType = AutoCompleteItemType.Variable;
					var fieldSymbol = (IFieldSymbol) symbol;
					item.Type = fieldSymbol.Type.Name;
					break;
				case CommonSymbolKind.Property:
					item.ItemType = AutoCompleteItemType.Property;
					var propertySymbol = (IPropertySymbol) symbol;
					item.Type = propertySymbol.Type.Name;
					break;
				case CommonSymbolKind.Namespace:
					item.ItemType = AutoCompleteItemType.Namespace;
					var namespaceSymbol = (INamespaceSymbol) symbol;
					item.Name = namespaceSymbol.Name;
					break;
				case CommonSymbolKind.NamedType:
					item.ItemType = AutoCompleteItemType.Class;
					var classSymbol = (INamedTypeSymbol) symbol;
					item.Name = classSymbol.Name;
					item.IsStatic = showClassesAsStatic || classSymbol.IsStatic;
					item.IsGeneric = classSymbol.IsGenericType;
					
					if (!showClassesAsStatic)
					{
						var constructors = classSymbol.GetConstructors();
						foreach (var constructor in constructors)
						{
							itemDoc = constructor.GetDocumentationComment(CultureInfo.GetCultureInfo("en-US"));

							var consItem = (AutoCompleteItem) item.Clone();
							if (itemDoc != null)
								consItem.Description = itemDoc.SummaryTextOpt;
							consItem.Params = GetSymbolParameters(constructor.Parameters, itemDoc);
							result.Add(consItem);
						}
					}
					break;
			}

			if (result.Count == 0)
				result.Add(item);

			return result;
		}
예제 #20
0
        private static IEnumerable <AutoCompleteItem> GetAutoCompleteItem(ISymbol symbol, bool showClassesAsStatic)
        {
            var result = new List <AutoCompleteItem>();

            var item = new AutoCompleteItem {
                Name = symbol.Name
            };

            var itemDoc = symbol.GetDocumentationComment(CultureInfo.GetCultureInfo("en-US"));

            if (itemDoc != null)
            {
                item.Description = itemDoc.SummaryTextOpt;
            }

            switch (symbol.Kind)
            {
            case CommonSymbolKind.Method:
                item.ItemType = AutoCompleteItemType.Method;
                var methodSymbol = (IMethodSymbol)symbol;
                item.IsExtension = methodSymbol.IsExtensionMethod;
                item.IsStatic    = methodSymbol.IsStatic;
                item.Type        = methodSymbol.ReturnsVoid ? "void" : methodSymbol.ReturnType.Name;
                //args
                item.Params    = GetSymbolParameters(methodSymbol.Parameters, itemDoc);
                item.IsGeneric = methodSymbol.IsGenericMethod;
                break;

            case CommonSymbolKind.Local:
                item.ItemType = AutoCompleteItemType.Variable;
                var localSymbol = (ILocalSymbol)symbol;
                item.Type = localSymbol.Type.Name;
                break;

            case CommonSymbolKind.Field:
                item.ItemType = AutoCompleteItemType.Variable;
                var fieldSymbol = (IFieldSymbol)symbol;
                item.Type = fieldSymbol.Type.Name;
                break;

            case CommonSymbolKind.Property:
                item.ItemType = AutoCompleteItemType.Property;
                var propertySymbol = (IPropertySymbol)symbol;
                item.Type = propertySymbol.Type.Name;
                break;

            case CommonSymbolKind.Namespace:
                item.ItemType = AutoCompleteItemType.Namespace;
                var namespaceSymbol = (INamespaceSymbol)symbol;
                item.Name = namespaceSymbol.Name;
                break;

            case CommonSymbolKind.NamedType:
                item.ItemType = AutoCompleteItemType.Class;
                var classSymbol = (INamedTypeSymbol)symbol;
                item.Name      = classSymbol.Name;
                item.IsStatic  = showClassesAsStatic || classSymbol.IsStatic;
                item.IsGeneric = classSymbol.IsGenericType;

                if (!showClassesAsStatic)
                {
                    var constructors = classSymbol.GetConstructors();
                    foreach (var constructor in constructors)
                    {
                        itemDoc = constructor.GetDocumentationComment(CultureInfo.GetCultureInfo("en-US"));

                        var consItem = (AutoCompleteItem)item.Clone();
                        if (itemDoc != null)
                        {
                            consItem.Description = itemDoc.SummaryTextOpt;
                        }
                        consItem.Params = GetSymbolParameters(constructor.Parameters, itemDoc);
                        result.Add(consItem);
                    }
                }
                break;
            }

            if (result.Count == 0)
            {
                result.Add(item);
            }

            return(result);
        }
예제 #21
0
        /// <summary>
        /// Inits the specified current node id.
        /// </summary>
        /// <param name="CurrentNodeId">The current node id.</param>
        /// <param name="PropertyData">The property data.</param>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public bool Init(int CurrentNodeId, string PropertyData, out object instance)
        {
            // check if the data is XML
            if (Helper.Xml.CouldItBeXml(PropertyData))
            {
                // if model binding is disbaled, return a DynamicXml object
                if (!Settings.RazorModelBindingEnabled)
                {
#pragma warning disable 0618
                    instance = new DynamicXml(PropertyData);
#pragma warning restore 0618
                    return(true);
                }

                // parse the XML
                var xdoc = XDocument.Parse(PropertyData);
                if (xdoc != null)
                {
                    // select the Item nodes
                    var nodes = xdoc.XPathSelectElements("//Item");
                    if (nodes != null && nodes.Count() > 0)
                    {
                        // iterate over the nodes; building collection of AutoCompleteItem(s)
                        var items = new List <AutoCompleteItem>();
                        foreach (var node in nodes)
                        {
                            // check if the node has any attributes
                            if (!node.HasAttributes)
                            {
                                continue;
                            }

                            var item = new AutoCompleteItem();

                            // loop through the attributes, setting the properties accordingly
                            foreach (var attribute in node.Attributes())
                            {
                                switch (attribute.Name.LocalName)
                                {
                                case "Text":
                                    item.Text = attribute.Value;
                                    break;

                                case "Value":
                                    item.Value = attribute.Value;
                                    break;

                                default:
                                    break;
                                }
                            }

                            items.Add(item);
                        }

                        instance = items;
                        return(true);
                    }
                }
            }

            // all else fails, return default value
            instance = PropertyData;
            return(true);
        }
예제 #22
0
        /// <summary>
        /// Attempts to convert the value specified into a useable value on the front-end
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public Attempt <object> ConvertPropertyValue(object value)
        {
            if (value != null && value.ToString().Length > 0)
            {
                var data = value.ToString();

                // check if the data is XML
                if (XmlHelper.CouldItBeXml(data))
                {
                    // TODO [LK->HR] Discuss with Hendy whether to return a collection of AutoCompleteItem(s)?
                    // ... or a collection of Content-specific objects; e.g. List<Media>, List<Member>, List<INodeFactory>?

                    // parse the XML
                    var xdoc = XDocument.Parse(data);
                    if (xdoc != null)
                    {
                        // select the Item nodes
                        var nodes = xdoc.XPathSelectElements("//Item");
                        if (nodes != null && nodes.Count() > 0)
                        {
                            // iterate over the nodes; building collection of AutoCompleteItem(s)
                            var items = new List <AutoCompleteItem>();
                            foreach (var node in nodes)
                            {
                                // check if the node has any attributes
                                if (!node.HasAttributes)
                                {
                                    continue;
                                }

                                var item = new AutoCompleteItem();

                                // loop through the attributes, setting the properties accordingly
                                foreach (var attribute in node.Attributes())
                                {
                                    switch (attribute.Name.LocalName)
                                    {
                                    case "Text":
                                        item.Text = attribute.Value;
                                        break;

                                    case "Value":
                                        item.Value = attribute.Value;
                                        break;

                                    default:
                                        break;
                                    }
                                }

                                items.Add(item);
                            }

                            return(new Attempt <object>(true, items));
                        }
                    }
                }
            }

            return(Attempt <object> .False);
        }
예제 #23
0
 /// <summary>
 /// Remove item from selected list.
 /// </summary>
 /// <param name="item">The item to be removed.</param>
 void RemoveItem(AutoCompleteItem item)
 {
     SelectedItems.Remove(item);
 }
예제 #24
0
        public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            XrmLookupEditorButton footerButton = (XrmLookupEditorButton)allBindingsAccessor()["footerButton"];
            bool                showFooter     = (bool)allBindingsAccessor()["showFooter"];
            jQueryObject        container      = jQuery.FromElement(element);
            jQueryObject        inputField     = container.Find(".sparkle-input-lookup-part");
            jQueryObject        selectButton   = container.Find(".sparkle-input-lookup-button-part");
            EntityReference     _value         = new EntityReference(null, null, null);
            AutoCompleteOptions options        = new AutoCompleteOptions();

            options.MinLength = 100000; // Don't enable type down - use search button (or return)
            options.Delay     = 0;
            options.Position  = new Dictionary <string, object>("collision", "fit");
            bool justSelected         = false;
            int  totalRecordsReturned = 0;
            Action <AutoCompleteItem, bool> setValue = delegate(AutoCompleteItem item, bool setFocus)
            {
                if (_value == null)
                {
                    _value = new EntityReference(null, null, null);
                }
                string value = item.Label;
                inputField.Value(value);
                _value.Id          = ((Guid)item.Value);
                _value.Name        = item.Label;
                _value.LogicalName = (string)item.Data;
                justSelected       = true;
                TrySetObservable(valueAccessor, inputField, _value, setFocus);
            };

            // Set the value when selected
            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item;
                string           data = ((string)item.Data);
                if (data == "footerlink" || data == null)
                {
                    footerButton.OnClick(item);
                    e.PreventDefault();
                    e.StopImmediatePropagation();
                    Script.Literal("return false;");
                }
                else
                {
                    setValue(item, true);
                    Script.Literal("return false;");
                }
            };

            options.Open = delegate(jQueryEvent e, jQueryObject o)
            {
                if (showFooter && totalRecordsReturned > 0)
                {
                    WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget");
                    XrmLookupEditor.AddFooter(menu, totalRecordsReturned);
                }
            };

            options.Close = delegate(jQueryEvent e, jQueryObject o)
            {
                WidgetObject menu   = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget");
                jQueryObject footer = menu.Next();
                if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer"))
                {
                    footer.Hide();
                }
            };
            // Get the query command
            Action <string, Action <EntityCollection> > queryCommand = (Action <string, Action <EntityCollection> >)((object)allBindingsAccessor()["queryCommand"]);
            string nameAttribute     = ((string)allBindingsAccessor()["nameAttribute"]);
            string idAttribute       = ((string)allBindingsAccessor()["idAttribute"]);
            string typeCodeAttribute = ((string)allBindingsAccessor()["typeCodeAttribute"]);

            string[] columnAttributes = null;
            // If there multiple names, add them to the columnAttributes
            string[] columns = nameAttribute.Split(",");

            if (columns.Length > 1)
            {
                columnAttributes = columns;
                nameAttribute    = columnAttributes[0];
            }

            // wire up source to CRM search
            Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response)
            {
                Action <EntityCollection> queryCallBack = delegate(EntityCollection fetchResult)
                {
                    int  recordsFound          = fetchResult.Entities.Count;
                    bool noRecordsFound        = recordsFound == 0;
                    AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton != null ? 1 : 0) + (noRecordsFound ? 1 : 0)];

                    for (int i = 0; i < recordsFound; i++)
                    {
                        results[i]       = new AutoCompleteItem();
                        results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(nameAttribute);
                        results[i].Value = fetchResult.Entities[i].GetAttributeValue(idAttribute);
                        results[i].Data  = fetchResult.Entities[i].LogicalName;
                        GetExtraColumns(columnAttributes, fetchResult, results, i);

                        string typeCodeName = fetchResult.Entities[i].LogicalName;
                        // Get the type code from the name to find the icon
                        if (!string.IsNullOrEmpty(typeCodeAttribute))
                        {
                            typeCodeName = fetchResult.Entities[i].GetAttributeValue(typeCodeAttribute).ToString();
                        }

                        results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName);
                    }

                    if (fetchResult.TotalRecordCount > fetchResult.Entities.Count)
                    {
                        totalRecordsReturned = fetchResult.TotalRecordCount;
                    }
                    else
                    {
                        totalRecordsReturned = fetchResult.Entities.Count;
                    }
                    int itemsCount = recordsFound;
                    if (noRecordsFound)
                    {
                        AutoCompleteItem noRecordsItem = new AutoCompleteItem();
                        noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound;
                        results[itemsCount] = noRecordsItem;
                        itemsCount++;
                    }
                    if (footerButton != null)
                    {
                        // Add the add new
                        AutoCompleteItem addNewLink = new AutoCompleteItem();
                        addNewLink.Label        = footerButton.Label;
                        addNewLink.Image        = footerButton.Image;
                        addNewLink.ColumnValues = null;
                        addNewLink.Data         = "footerlink";
                        results[itemsCount]     = addNewLink;
                    }
                    response(results);

                    // Disable it now so typing doesn't trigger a search
                    AutoCompleteOptions disableOption = new AutoCompleteOptions();
                    disableOption.MinLength = 100000;
                    inputField.Plugin <AutoCompleteObject>().AutoComplete(disableOption);
                };

                // Call the function with the correct 'this' context
                Script.Literal("{0}.call({1}.$parent,{2},{3})", queryCommand, context, request.Term, queryCallBack);
            };

            options.Source = queryDelegate;
            options.Focus  = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent)
            {
                // Prevent the value being updated in the text box we scroll through the results
                Script.Literal("return false;");
            };
            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);

            // Set render template
            ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item)
            {
                if (item.Data == null)
                {
                    return((object)jQuery.Select("<li class='ui-state-disabled'>" + item.Label + "</li>").AppendTo((jQueryObject)ul));
                }

                string html = "<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'>";
                if (item.Image != null)
                {
                    html += @"<img src='" + item.Image + "'/>";
                }
                html += @"</span><span class='sparkle-menu-item-label'>" + item.Label + "</span><br>";

                if (item.ColumnValues != null && item.ColumnValues.Length > 0)
                {
                    foreach (string value in item.ColumnValues)
                    {
                        html += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>";
                    }
                }
                html += "</a>";
                return((object)jQuery.Select("<li>").Append(html).AppendTo((jQueryObject)ul));
            };

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                AutoCompleteOptions enableOption = new AutoCompleteOptions();
                enableOption.MinLength           = 0;
                inputField.Focus();
                inputField.Plugin <AutoCompleteObject>().AutoComplete(enableOption);
                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search);
            });

            // handle the field changing
            inputField.Change(delegate(jQueryEvent e)
            {
                string inputValue = inputField.GetValue();
                if (inputValue != _value.Name)
                {
                    // The name is different from the name of the lookup reference
                    // search to see if we can auto resolve it
                    TrySetObservable(valueAccessor, inputField, null, false);
                    AutoCompleteRequest lookup = new AutoCompleteRequest();
                    lookup.Term = inputValue;
                    Action <AutoCompleteItem[]> lookupResults = delegate(AutoCompleteItem[] results)
                    {
                        int selectableItems = 0;
                        // If there is only one, then auto-set
                        if (results != null)
                        {
                            foreach (AutoCompleteItem item in results)
                            {
                                if (isItemSelectable(item))
                                {
                                    selectableItems++;
                                }
                                if (selectableItems > 2)
                                {
                                    break;
                                }
                            }
                        }

                        if (selectableItems == 1)
                        {
                            // There is only a single value so set it now
                            setValue(results[0], false);
                        }
                        else
                        {
                            inputField.Value(String.Empty);
                        }
                    };

                    queryDelegate(lookup, lookupResults);
                }
            });

            Action disposeCallBack = delegate()
            {
                if ((bool)Script.Literal("$({0}).data('ui-autocomplete')!=undefined", inputField))
                {
                    Script.Literal("$({0}).autocomplete(\"destroy\")", inputField);
                }
            };

            //handle disposal (if KO removes by the template binding)
            Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack);
            Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null);

            // Bind return to searching
            inputField.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    selectButton.Click();
                }
                else if (e.Which == 13)
                {
                    return;
                }
                switch (e.Which)
                {
                case 13:     // Return
                case 38:     // Up - don't navigate - but use the dropdown to select search results
                case 40:     // Down - don't navigate - but use the dropdown to select search results
                    e.PreventDefault();
                    e.StopPropagation();
                    break;
                }
                justSelected = false;
            });

            //Script.Literal("return { controlsDescendantBindings: true };");
        }
예제 #25
0
        private static bool isItemSelectable(AutoCompleteItem item)
        {
            string data = (string)item.Data;

            return(data != null && data != "footerlink");
        }