public XrmTimeEditor(EditorArguments args) : base(args)
        {
            if (OrganizationServiceProxy.UserSettings != null)
            {
                _formatString = OrganizationServiceProxy.UserSettings.TimeFormatString;
            }


            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='autocompleteButton' /></td></tr></table></div>");

            _container.AppendTo(_args.Container);

            jQueryObject inputField = _container.Find(".sparkle-input-inline");

            _input = inputField;
            _input.Focus().Select();
            string timeFormatString     = _formatString;
            AutoCompleteOptions options = GetTimePickerAutoCompleteOptions(timeFormatString);

            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                //string value = ((Dictionary)uiEvent.Item)["value"].ToString();
            };

            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);
            jQueryObject selectButton = _container.Find(".autocompleteButton");

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, "");
            });
        }
        public string GetFetchXmlForQuery(FetchQuerySettings config, string searchTerm)
        {
            jQueryObject fetchElement = config.FetchXml.Find("fetch");

            fetchElement.Attribute("count", "{0}");
            fetchElement.Attribute("paging-cookie", "{1}");
            fetchElement.Attribute("page", "{2}");
            fetchElement.Attribute("returntotalrecordcount", "true");
            fetchElement.Attribute("distinct", "true");
            fetchElement.Attribute("no-lock", "true");

            jQueryObject orderByElement = fetchElement.Find("order");

            orderByElement.Remove();

            // Add the search string and adjust any lookup columns
            jQueryObject conditions = fetchElement.Find("filter[isquickfindfields='1']");

            conditions.First().Children().Each(delegate(int index, Element element)
            {
                // Is this a lookup column?
                string logicalName = element.GetAttribute("attribute").ToString();
                if (LookupAttributes.ContainsKey(logicalName))
                {
                    element.SetAttribute("attribute", logicalName + "name");
                }
            });
            // Add the sort order placeholder
            string fetchXml = config.FetchXml.GetHtml().Replace("</entity>", "{3}</entity>");

            // Add the Query term
            fetchXml = fetchXml.Replace("#Query#", XmlHelper.Encode(searchTerm));
            return(fetchXml);
        }
Exemple #3
0
        private void SaveDetails(jQueryEvent e)
        {
            this.EditButton.Hide(EffectDuration.Fast);
            this.Obj.Attribute("disabled", "disabled").AddClass("ui-state-disabled");

            // Find the objects with the .edit class that are descendants of objects with .keyvaluerow class
            // These are the editable key/value pairs
            jQueryObject edits = this.Obj.Find(".keyvaluerow .edit");

            string ntrp           = edits.Find(".ntrp").GetValue();
            string court          = edits.Find(".placesAutoValue").GetValue();
            string playPreference = edits.Find(".preference").GetValue();
            string style          = edits.Find(".style").GetValue();
            string email          = ((CheckBoxElement)edits.Find(".email").GetElement(0)).Checked ? "true" : "false";

            JsonObject parameters = new JsonObject
                                    (
                "ntrp", ntrp,
                "preference", playPreference,
                "courtData", court,
                "style", style,
                "emailOffers", email
                                    );

            // Post the user data to the service
            jQuery.Post("/services/PostTennisUserDetails" + "?signed_request=" + Utility.GetSignedRequest(), Json.Stringify(parameters), (AjaxRequestCallback <object>) delegate(object data, string textStatus, jQueryXmlHttpRequest <object> request)
            {
                Utility.ProcessResponse((Dictionary)data);
            });
        }
Exemple #4
0
        public XrmDateEditor(EditorArguments args) : base(args)
        {
            XrmDateEditor self = this;

            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" +
                                         "<td><INPUT type=text class='sparkle-input-inline' /></td>" +
                                         "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            _input = _container.Find(".sparkle-input-inline");
            _input.Bind("keydown.nav", delegate(jQueryEvent e)
            {
                if (!_calendarOpen && (e.Which == 38 || e.Which == 40) && e.CtrlKey) // Ctrl-Up/Down shows date picker
                {
                    _input.Plugin <DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
                    e.StopImmediatePropagation();
                }
                else if (_calendarOpen && e.Which == 13)
                {
                    e.PreventDefault();
                }
            });
            jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon");

            _input.Focus().Select();
            DatePickerOptions2 options2 = new DatePickerOptions2();

            options2.ShowOtherMonths = true;
            options2.ShowOn          = ""; // Date Pickers in CRM do not show when they are focused - you click the button
            options2.FirstDay        = OrganizationServiceProxy.OrganizationSettings != null ? OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value : 0;
            options2.BeforeShow      = delegate()
            {
                this._calendarOpen = true;
            };

            options2.OnClose = delegate()
            {
                this._calendarOpen = false;
                _selectedValue     = GetSelectedValue();
            };

            options2.OnSelect = delegate(string dateString, object instance)
            {
                // Select the date text field when selecting a date
                Focus();
            };

            if (OrganizationServiceProxy.UserSettings != null)
            {
                _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
            }
            options2.DateFormat = _dateFormat;
            _input.Plugin <DatePickerPlugIn>().DatePicker(options2);

            // Wire up the date picker button
            selectButton.Click(delegate(jQueryEvent e){
                _input.Plugin <DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
                Focus();
            });
        }
        public XrmDateEditor(EditorArguments args)
            : base(args)
        {
            XrmDateEditor self = this;
            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" +
                "<td><INPUT type=text class='sparkle-input-inline' /></td>" +
                "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            _input = _container.Find(".sparkle-input-inline");
            _input.Bind("keydown.nav", delegate(jQueryEvent e)
            {
                if (!_calendarOpen && (e.Which == 38 || e.Which == 40) && e.CtrlKey) // Ctrl-Up/Down shows date picker
                {
                    _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
                    e.StopImmediatePropagation();
                }
                else if (_calendarOpen && e.Which == 13)
                {
                    e.PreventDefault();
                }

            });
            jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon");
            _input.Focus().Select();
            DatePickerOptions2 options2 = new DatePickerOptions2();
            options2.ShowOtherMonths = true;
            options2.ShowOn = ""; // Date Pickers in CRM do not show when they are focused - you click the button
            options2.FirstDay = OrganizationServiceProxy.OrganizationSettings != null ? OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value : 0;
            options2.BeforeShow = delegate()
            {
                this._calendarOpen = true;
            };

            options2.OnClose = delegate()
            {
                this._calendarOpen = false;
                _selectedValue = GetSelectedValue();
            };

            options2.OnSelect = delegate(string dateString, object instance)
            {
                // Select the date text field when selecting a date
                Focus();
            };

            if (OrganizationServiceProxy.UserSettings != null)
            {
                _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
            }
            options2.DateFormat = _dateFormat;
            _input.Plugin<DatePickerPlugIn>().DatePicker(options2);

            // Wire up the date picker button
            selectButton.Click(delegate(jQueryEvent e){
                _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
                Focus();
            });
        }
Exemple #6
0
        private jQueryObject AddEmptyRow(bool popupField)
        {
            jQueryObject emptyRow = FindEmptyRow();

            if (emptyRow != null)
            {
                emptyRow.Find("input.field-select").Select2("focus");

                if (popupField)
                {
                    emptyRow.Find("input.field-select").Select2("open");
                }

                return(emptyRow);
            }

            bool isLastRowOr = this.rowsDiv.Children().Last().Children("a.andor").HasClass("or");

            jQueryObject row = J(RowTemplate).AppendTo(this.rowsDiv);

            jQueryObject parenDiv = row.Children("div.l").Hide();

            parenDiv.Children("a.leftparen, a.rightparen").Click(LeftRightParenClick);

            jQueryObject andor = parenDiv.Children("a.andor").Attribute("title", Q.Text("Controls.FilterPanel.ChangeAndOr"));

            if (isLastRowOr)
            {
                andor.AddClass("or").Text(Q.Text("Controls.FilterPanel.Or"));
            }
            else
            {
                andor.Text(Q.Text("Controls.FilterPanel.And"));
            }

            andor.Click(AndOrClick);

            row.Children("a.delete").Attribute("title", Q.Text("Controls.FilterPanel.RemoveField")).Click(DeleteRowClick);

            var fieldSel = new FieldSelect(row.Children("div.f").Children("input"), this.Store.Fields);

            fieldSel.ChangeSelect2(OnRowFieldChange);

            UpdateParens();
            UpdateButtons();

            row.Find("input.field-select").Select2("focus");

            if (popupField)
            {
                row.Find("input.field-select").Select2("open");
            }

            return(row);
        }
Exemple #7
0
        public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            string       formatString = GetFormatString();
            jQueryObject container    = jQuery.FromElement(element);

            jQueryObject inputField   = container.Find(".sparkle-input-timeofday-part");
            jQueryObject selectButton = container.Find(".sparkle-input-timeofday-button-part");

            AutoCompleteOptions options = XrmTimeEditor.GetTimePickerAutoCompleteOptions(formatString);

            options.Position = new Dictionary <string, object>("collision", "fit");
            options.Select   = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                string value = ((Dictionary)uiEvent.Item)["value"].ToString();

                TrySetObservable(valueAccessor, inputField, value);
            };

            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);


            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, ""); // Give "" to show all items
            });
            //// Set initial value
            //Observable<DateTime> dateValueAccessor = (Observable<DateTime>)valueAccessor();
            //DateTime intialValue = dateValueAccessor.GetValue();
            //FormatterUpdate(inputField, intialValue);

            //handle the field changing
            KnockoutUtils.RegisterEventHandler(inputField.GetElement(0), "change", delegate(object sender, EventArgs e)
            {
                string value = inputField.GetValue();
                TrySetObservable(valueAccessor, inputField, value);
            });

            Action disposeCallBack = delegate()
            {
                Script.Literal("$({0}).autocomplete(\"destroy\")", element);
            };

            //handle disposal (if KO removes by the template binding)
            Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack);

            // Note: Because the time picker is always part of the date picker - we don't need to display validation messages
            //Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null);
        }
Exemple #8
0
        public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            // Get the text box element
            jQueryObject select = jQuery.FromElement(element).Find(".sparkle-input-optionset-part");

            jQueryEventHandler onChangeHandler = delegate(jQueryEvent e)
            {
                Observable <OptionSetValue> observable = (Observable <OptionSetValue>)valueAccessor();
                string newValue    = select.GetValue();
                int?   newValueInt = null;
                if (!String.IsNullOrEmpty(newValue))
                {
                    newValueInt = int.Parse(newValue);
                }
                // Set the optionset value
                OptionSetValue newValueOptionSetValue = new OptionSetValue(newValueInt);
                newValueOptionSetValue.Name = select.Find("option:selected").GetText();
                observable.SetValue(newValueOptionSetValue);
            };

            select.Change(onChangeHandler);

            allBindingsAccessor()["optionsValue"] = "value";
            allBindingsAccessor()["optionsText"]  = "name";

            OptionSetBindingOptions optionSetOptions = (OptionSetBindingOptions)((object)allBindingsAccessor()["optionSetOptions"]);
            // Create a value accessor for the optionset options
            Func <List <OptionSetItem> > optionsValueAccessor = delegate() {
                return(MetadataCache.GetOptionSetValues(optionSetOptions.entityLogicalName, optionSetOptions.attributeLogicalName, optionSetOptions.allowEmpty));
            };

            Script.Literal("ko.bindingHandlers.options.update({0},{1},{2},{3},{4})", select.GetElement(0), optionsValueAccessor, allBindingsAccessor, viewModel, context);

            //Script.Literal("return { controlsDescendantBindings: true };");
        }
        public static string GetFetchXmlParentFilter(FetchQuerySettings query, string parentAttribute)
        {
            jQueryObject fetchElement = query.FetchXml.Find("fetch");

            fetchElement.Attribute("count", "{0}");
            fetchElement.Attribute("paging-cookie", "{1}");
            fetchElement.Attribute("page", "{2}");
            fetchElement.Attribute("returntotalrecordcount", "true");
            fetchElement.Attribute("distinct", "true");
            fetchElement.Attribute("no-lock", "true");
            jQueryObject orderByElement = fetchElement.Find("order");

            // Get the default order by field - currently only supports a single sort by column
            query.OrderByAttribute = orderByElement.GetAttribute("attribute");
            query.OrderByDesending = orderByElement.GetAttribute("descending") == "true";

            orderByElement.Remove();

            // Get the root filter (if there is one)
            jQueryObject filter = fetchElement.Find("entity>filter");

            if (filter != null)
            {
                // Check that it is an 'and' filter
                string filterType = filter.GetAttribute("type");
                if (filterType == "or")
                {
                    // wrap up in an and filter
                    jQueryObject andFilter = jQuery.FromHtml("<filter type='and'>" + filter.GetHtml() + "</filter>");

                    // remove existing filter
                    filter.Remove();

                    filter = andFilter;
                    // Add in the existing filter
                    fetchElement.Find("entity").Append(andFilter);
                }
            }

            // Add in the parent query filter
            jQueryObject parentFilter = jQuery.FromHtml("<condition attribute='" + parentAttribute + "' operator='eq' value='" + ParentRecordPlaceholder + "'/>");

            filter.Append(parentFilter);

            // Add the order by placeholder for the EntityDataViewModel
            return(query.FetchXml.GetHtml().Replace("</entity>", "{3}</entity>"));
        }
        private List <Column> ParseLayoutXml(EntityQuery rootEntity, string layoutXml)
        {
            jQueryObject  layout  = jQuery.FromHtml(layoutXml);
            jQueryObject  cells   = layout.Find("cell");
            List <Column> columns = new List <Column>();

            cells.Each(delegate(int index, Element element)
            {
                string cellName    = element.GetAttribute("name").ToString();
                string logicalName = cellName;
                EntityQuery entity;
                AttributeQuery attribute;

                // Is this an alias attribute?
                int pos = cellName.IndexOf('.');
                if (pos > -1)
                {
                    // Aliased entity
                    string alias = cellName.Substr(0, pos);
                    logicalName  = cellName.Substr(pos + 1);
                    entity       = AliasEntityLookup[alias];
                }
                else
                {
                    // Root entity
                    entity = rootEntity;
                }

                // Does the attribute allready exist?
                if (entity.Attributes.ContainsKey(logicalName))
                {
                    // Already exists
                    attribute = entity.Attributes[logicalName];
                }
                else
                {
                    // New
                    attribute             = new AttributeQuery();
                    attribute.Columns     = new List <Column>();
                    attribute.LogicalName = logicalName;
                    entity.Attributes[attribute.LogicalName] = attribute;
                }

                // Add column
                object widthAttribute = element.GetAttribute("width");
                if (widthAttribute != null)
                {
                    int width             = int.Parse(element.GetAttribute("width").ToString());
                    object disableSorting = element.GetAttribute("disableSorting");
                    Column col            = GridDataViewBinder.NewColumn(attribute.LogicalName, attribute.LogicalName, width); // Display name get's queried later
                    col.Sortable          = !(disableSorting != null && disableSorting.ToString() == "1");
                    attribute.Columns.Add(col);
                    columns.Add(col);
                }
            });

            return(columns);
        }
Exemple #11
0
        public XrmDateEditor(EditorArguments args)
            : base(args)
        {
            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" +
                "<td><INPUT type=text class='sparkle-input-inline' /></td>" +
                "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            _input = _container.Find(".sparkle-input-inline");
            jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon");

            _input.Focus().Select();

            DatePickerOptions2 options2 = new DatePickerOptions2();
            options2.ShowOtherMonths = true;
            options2.FirstDay = OrganizationServiceProxy.OrganizationSettings != null ? OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value : 0;
            options2.BeforeShow = delegate()
            {
                this._calendarOpen = true;
            };

            options2.OnClose = delegate()
            {
                this._calendarOpen = false;
                _selectedValue = GetSelectedValue();
            };

            if (OrganizationServiceProxy.UserSettings != null)
            {
                _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
            }

            options2.DateFormat = _dateFormat;

            _input.Plugin<DatePickerPlugIn>().DatePicker(options2);

            // Wire up the date picker button
            selectButton.Click(delegate(jQueryEvent e){

                _input.Plugin<DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
            });

            //_input.Width(_input.GetWidth() - 24);
        }
Exemple #12
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-duration-part");
            jQueryObject        selectButton = container.Find(".sparkle-input-duration-button-part");
            AutoCompleteOptions options      = new AutoCompleteOptions();

            options.Position  = new Dictionary <string, object>("collision", "fit");
            options.Source    = new string[] { "1 m", "2 m", "1 h", "2 h", "1 d" };
            options.Delay     = 0;
            options.MinLength = 0;

            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                string value = ((Dictionary)uiEvent.Item)["value"].ToString();

                TrySetObservable(valueAccessor, inputField, value);
            };

            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, "");// Give "" to show all items
            });

            //handle the field changing
            KnockoutUtils.RegisterEventHandler(element, "change", delegate(object sender, EventArgs e)
            {
                string value = inputField.GetValue();
                TrySetObservable(valueAccessor, inputField, value);
            });

            Action disposeCallBack = delegate()
            {
                Script.Literal("$({0}).autocomplete(\"destroy\")", element);
            };

            //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);
        }
Exemple #13
0
        public XrmDateEditor(EditorArguments args) : base(args)
        {
            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr>" +
                                         "<td><INPUT type=text class='sparkle-input-inline' /></td>" +
                                         "<td class='lookup-button-td'><input type=button class='sparkle-imagestrip-inlineedit_calendar_icon' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            _input = _container.Find(".sparkle-input-inline");
            jQueryObject selectButton = _container.Find(".sparkle-imagestrip-inlineedit_calendar_icon");


            _input.Focus().Select();
            DatePickerOptions  options  = new DatePickerOptions();
            DatePickerOptions2 options2 = (DatePickerOptions2)(object)options;

            options2.BeforeShow = delegate()
            {
                this._calendarOpen = true;
            };

            options2.OnClose = delegate()
            {
                this._calendarOpen = false;
                _selectedValue     = GetSelectedValue();
            };

            if (OrganizationServiceProxy.UserSettings != null)
            {
                _dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString;
            }

            options.DateFormat = _dateFormat;

            _input.Plugin <DatePickerObject>().DatePicker(options);

            // Wire up the date picker button
            selectButton.Click(delegate(jQueryEvent e){
                _input.Plugin <DatePickerPlugIn>().DatePicker(DatePickerMethod2.Show);
            });

            //_input.Width(_input.GetWidth() - 24);
        }
        public void AddRefreshButton(string gridId, DataViewBase dataView)
        {
            jQueryObject gridDiv       = jQuery.Select("#" + gridId);
            jQueryObject refreshButton = jQuery.FromHtml("<div id='refreshButton' class='sparkle-grid-refresh-button' style='left: auto; right: 0px; display: inline;'><a href='#' id='refreshButtonLink' tabindex='0'><span id='grid_refresh' class='sparkle-grid-refresh-button-img' style='cursor:pointer'></span></a></div>").AppendTo(gridDiv);

            refreshButton.Find("#refreshButtonLink").Click(delegate(jQueryEvent e)
            {
                dataView.Reset();
                dataView.Refresh();
            });
        }
Exemple #15
0
        public override void Update(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-timeofday-part");
            DateTime     value          = (DateTime)KnockoutUtils.UnwrapObservable(valueAccessor());
            string       formatString   = GetFormatString();
            string       formattedValue = DateTimeEx.FormatTimeSpecific(value, formatString);

            inputField.Value((string)formattedValue);
        }
Exemple #16
0
        public override void Update(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-duration-part");
            object       value      = KnockoutUtils.UnwrapObservable(valueAccessor());

            // Get the value in duration format
            int?   duration       = (int?)value;
            string durationString = formatDuration(duration);

            inputField.Value(durationString);
        }
        protected virtual void UpdateInterface()
        {
            bool isDeleted          = IsDeleted;
            bool isLocalizationMode = IsLocalizationMode;

            if (deleteButton != null)
            {
                deleteButton.Toggle(!isLocalizationMode && IsEditMode && !isDeleted);
            }

            if (undeleteButton != null)
            {
                undeleteButton.Toggle(!isLocalizationMode && IsEditMode && isDeleted);
            }

            if (saveAndCloseButton != null)
            {
                saveAndCloseButton.Toggle(!isLocalizationMode && !isDeleted);

                saveAndCloseButton.Find(".button-inner").Text(
                    IsNew ? Texts.Controls.EntityDialog.SaveButton : Texts.Controls.EntityDialog.UpdateButton);
            }

            if (applyChangesButton != null)
            {
                applyChangesButton.Toggle(isLocalizationMode || !isDeleted);
            }

            if (cloneButton != null)
            {
                cloneButton.Toggle(false);
            }

            if (propertyGrid != null)
            {
                propertyGrid.Element.Toggle(!isLocalizationMode);
            }

            if (localizationGrid != null)
            {
                localizationGrid.Element.Toggle(isLocalizationMode);
            }

            if (localizationSelect != null)
            {
                localizationSelect.Toggle(IsEditMode && !IsCloneMode);
            }

            if (tabs != null)
            {
                tabs.SetDisabled("Log", IsNewOrDeleted);
            }
        }
        public string GetFetchXmlForQuery(string entityLogicalName, string queryName, string searchTerm)
        {
            FetchQuerySettings config;

            if (queryName == "QuickFind")
            {
                config = EntityLookup[entityLogicalName].QuickFindQuery;
            }
            else
            {
                config = EntityLookup[entityLogicalName].Views[queryName];
            }
            jQueryObject fetchElement = config.FetchXml.Find("fetch");

            fetchElement.Attribute("distinct", "true");
            fetchElement.Attribute("no-lock", "true");

            jQueryObject orderByElement = fetchElement.Find("order");

            orderByElement.Remove();

            // Add the search string and adjust any lookup columns
            jQueryObject conditions = fetchElement.Find("filter[isquickfindfields='1']");

            conditions.First().Children().Each(delegate(int index, Element element)
            {
                // Is this a lookup column?
                string logicalName = element.GetAttribute("attribute").ToString();
                if (LookupAttributes.ContainsKey(logicalName))
                {
                    element.SetAttribute("attribute", logicalName + "name");
                }
            });
            // Add the sort order placeholder
            string fetchXml = config.FetchXml.GetHtml();//.Replace("</entity>", "{3}</entity>");

            // Add the Query term
            fetchXml = fetchXml.Replace("#Query#", XmlHelper.Encode(searchTerm));
            return(fetchXml);
        }
        private void ParseFetchXml(FetchQuerySettings querySettings)
        {
            jQueryObject fetchElement = querySettings.FetchXml;

            // Get the entities and link entities - only support 1 level deep
            jQueryObject entityElement = fetchElement.Find("entity");
            string       logicalName   = entityElement.GetAttribute("name");

            EntityQuery rootEntity;

            // Get query from cache or create new
            if (!EntityLookup.ContainsKey(logicalName))
            {
                rootEntity             = new EntityQuery();
                rootEntity.LogicalName = logicalName;
                rootEntity.Attributes  = new Dictionary <string, AttributeQuery>();
                EntityLookup[rootEntity.LogicalName] = rootEntity;
            }
            else
            {
                rootEntity = EntityLookup[logicalName];
            }

            // Get Linked Entities(1 deep)
            jQueryObject linkEntities = entityElement.Find("link-entity");

            linkEntities.Each(delegate(int index, Element element)
            {
                EntityQuery link = new EntityQuery();
                link.Attributes  = new Dictionary <string, AttributeQuery>();
                link.AliasName   = element.GetAttribute("alias").ToString();
                link.LogicalName = element.GetAttribute("name").ToString();

                if (!EntityLookup.ContainsKey(link.LogicalName))
                {
                    EntityLookup[link.LogicalName] = link;
                }
                else
                {
                    string alias   = link.AliasName;
                    link           = EntityLookup[link.LogicalName];
                    link.AliasName = alias;
                }

                if (!AliasEntityLookup.ContainsKey(link.AliasName))
                {
                    AliasEntityLookup[link.AliasName] = link;
                }
            });

            querySettings.RootEntity = rootEntity;
        }
        public override void Update(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            jQueryObject container = jQuery.FromElement(element);
            jQueryObject dateTime  = container.Find(".sparkle-input-datepicker-part");
            object       value     = KnockoutUtils.UnwrapObservable(valueAccessor());

            if ((string)Script.Literal("typeof({0})", value) == "string")
            {
                value = Date.Parse((string)value);
            }

            dateTime.Plugin <DatePickerObject>().DatePicker(DatePickerMethod.SetDate, value);
        }
        public override void Update(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");
            EntityReference value      = (EntityReference)KnockoutUtils.UnwrapObservable(valueAccessor());

            string displayName = "";

            if (value != null)
            {
                displayName = value.Name;
            }
            inputField.Value(displayName);
        }
        public XrmTimeEditor(EditorArguments args)
            : base(args)
        {
            if (OrganizationServiceProxy.UserSettings != null)
            {
                _formatString = OrganizationServiceProxy.UserSettings.TimeFormatString;
            }

            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='autocompleteButton' /></td></tr></table></div>");

            _container.AppendTo(_args.Container);

            jQueryObject inputField = _container.Find(".sparkle-input-inline");

            _input = inputField;
            _input.Focus().Select();
            string timeFormatString = _formatString;
            AutoCompleteOptions options = GetTimePickerAutoCompleteOptions(timeFormatString);

            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {

                // Note we assume that the binding has added an array of string items
                //string value = ((Dictionary)uiEvent.Item)["value"].ToString();

            };

            inputField = inputField.Plugin<AutoCompleteObject>().AutoComplete(options);
            jQueryObject selectButton = _container.Find(".autocompleteButton");
            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {

                inputField.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, "");
            });
        }
        public void constructPagerUI()
        {
            _container.Empty();

            jQueryObject pager = jQuery.FromHtml("<table cellspacing='0' cellpadding='0' class='sparkle-grid-status'><tbody><tr>" +
                                                 "<td class='sparkle-grid-status-label'>1 - 1 of 1&nbsp;(0 selected)</td>" +
                                                 "<td class='sparkle-grid-status-paging'>" +
                                                 "<img src='../../sparkle_/css/images/transparent_spacer.gif' class='sparkle-grid-paging-first'>" +
                                                 "<img src='../../sparkle_/css/images/transparent_spacer.gif' class='sparkle-grid-paging-back'>" +
                                                 "<span class='sparkle-grid-status-paging-page'>Page 1</span>" +
                                                 "<img src='../../sparkle_/css/images/transparent_spacer.gif' class='sparkle-grid-paging-next'>" +
                                                 "&nbsp;</td></tr></tbody></table>");

            jQueryObject firstButton = pager.Find(".sparkle-grid-paging-first");
            jQueryObject backButton  = pager.Find(".sparkle-grid-paging-back");
            jQueryObject nextButton  = pager.Find(".sparkle-grid-paging-next");
            jQueryObject label       = pager.Find(".sparkle-grid-status-label");
            jQueryObject pageInfo    = pager.Find(".sparkle-grid-status-paging-page");

            _container.Append(pager);
            firstButton.Click(gotoFirst);
            backButton.Click(gotoPrev);
            nextButton.Click(gotoNext);
        }
        private FetchQuerySettings Parse(string fetchXml, string layoutXml)
        {
            FetchQuerySettings querySettings = new FetchQuerySettings();


            jQueryObject fetchXmlDOM  = jQuery.FromHtml("<query>" + fetchXml.Replace("{0}", "#Query#") + "</query>");
            jQueryObject fetchElement = fetchXmlDOM.Find("fetch");

            querySettings.FetchXml = fetchXmlDOM;

            ParseFetchXml(querySettings);

            querySettings.Columns = ParseLayoutXml(querySettings.RootEntity, layoutXml);

            return(querySettings);
        }
Exemple #25
0
        private void UpdateMatchFlags(string text)
        {
            var liList = menuUL.Find("li").RemoveClass("non-match");

            text = text.TrimToNull();
            if (text == null)
            {
                liList.RemoveClass("active");
                liList.Show();
                liList.Children("ul").AddClass("collapse");
                return;
            }

            var parts = text.Split(new char[] { ',', ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

            for (var i = 0; i < parts.Length; i++)
            {
                parts[i] = Q.Externals.StripDiacritics(parts[i]).ToUpperCase().TrimToNull();
            }

            var items = liList;

            items.Each((i, e) =>
            {
                var x     = J(e);
                var title = Q.Externals.StripDiacritics((x.GetText() ?? "").ToUpperCase());


                foreach (var p in parts)
                {
                    if (p != null && !title.Contains(p))
                    {
                        x.AddClass("non-match");
                        break;
                    }
                }
            });

            var matchingItems = items.Not(".non-match");
            var visibles      = matchingItems.Parents("li").Add(matchingItems);
            var nonVisibles   = liList.Not(visibles);

            nonVisibles.Hide().AddClass("non-match");
            visibles.Show();

            liList.Children("ul").RemoveClass("collapse");
        }
Exemple #26
0
        // image recycle function
        static void RecycleImage(jQueryObject item)
        {
            string trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";

            item.FadeOut(EffectDuration.Slow, delegate()
            {
                item.Find("a.ui-icon-refresh")
                .Remove()
                .End()
                .CSS("width", "96px")
                .Append(trash_icon)
                .Find("img")
                .CSS("height", "72px")
                .End()
                .AppendTo("#gallery")
                .FadeIn();
            });
        }
Exemple #27
0
        // image deletion function
        static void DeleteImage(jQueryObject item)
        {
            string recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";

            item.FadeOut(EffectDuration.Slow, delegate()
            {
                jQueryObject list = jQuery.Select("ul", jQuery.Select("#trash")).Length > 0 ?
                                    jQuery.Select("ul", jQuery.Select("#trash")) :
                                    jQuery.Select("<ul class='gallery ui-helper-reset'/>").AppendTo("#trash");

                item.Find("a.ui-icon-trash").Remove();
                item.Append(recycle_icon).AppendTo(list).FadeIn(EffectDuration.Slow, delegate()
                {
                    item.Animate(new Dictionary("width", "48px"))
                    .Find("img")
                    .Animate(new Dictionary("height", "36px"));
                });
            });
        }
Exemple #28
0
        public void DoFilter(jQueryObject obj, bool postBack)
        {
            jQueryUIObject selects = (jQueryUIObject)obj.Find("th select");
            string filterValue = "";

            selects.Each((ElementIterationCallback)delegate(int index, Element el)
            {
                jQueryUIObject select = (jQueryUIObject)jQuery.FromElement(el);
                Array checkedItems = select.MultiSelect("getChecked");

                if (checkedItems.Length > 0)
                {
                    if (filterValue.Length > 0)
                    {
                        filterValue = filterValue + ",,";
                    }

                    filterValue = filterValue + select.GetAttribute("name") + "=";

                    for (int i = 0; i < checkedItems.Length; ++i)
                    {
                        if (i > 0)
                        {
                            filterValue = filterValue + "||";
                        }

                        filterValue = filterValue + ((InputElement)checkedItems[i]).Value;
                    }

                }
            });

            if (this.Filter != filterValue)
            {
                this.Filter = filterValue;

                if (postBack)
                {
                    PostBack(0);
                }
            }
        }
Exemple #29
0
    static PhotoGridPage()
    {
        jQuery.OnDocumentReady(delegate() {
            string apiKey = (string)jQuery.FromElement(Document.Body).GetDataValue("flickrKey");
            IPhotoService flickrService = new FlickrPhotoService();

            jQuery.Select("#searchButton").Click(delegate(jQueryEvent e) {
                string tags = jQuery.Select("#tagsTextBox").GetValue();

                flickrService.SearchPhotos(tags, 20).Done(
                    delegate(IEnumerable <Photo> photos) {
                    jQueryObject thumbnailList = jQuery.Select("#thumbsList");
                    thumbnailList.Empty();

                    if (photos == null)
                    {
                        return;
                    }

                    jQuery.Select("#thumbnailTemplate").Plugin <jQueryTemplateObject>().
                    RenderTemplate(photos).
                    AppendTo(thumbnailList);

                    thumbnailList.
                    Plugin <jQueryIsotopeObject>().Isotope(new IsotopeOptions("layoutMode", IsotopeLayout.Masonry)).
                    Find("a").
                    Plugin <jQueryLightBoxObject>().LightBox();

                    thumbnailList.Find("li").
                    MouseOver(delegate(jQueryEvent e2) {
                        jQuery.This.CSS("box-shadow", "0 0 15px #888");
                    }).
                    MouseOut(delegate(jQueryEvent e2) {
                        jQuery.This.CSS("box-shadow", "");
                    });
                });

                jQuery.FromElement(Document.Body).Focus();
                e.PreventDefault();
            });
        });
    }
Exemple #30
0
        public void DoFilter(jQueryObject obj, bool postBack)
        {
            jQueryUIObject selects     = (jQueryUIObject)obj.Find("th select");
            string         filterValue = "";

            selects.Each((ElementIterationCallback) delegate(int index, Element el)
            {
                jQueryUIObject select = (jQueryUIObject)jQuery.FromElement(el);
                Array checkedItems    = select.MultiSelect("getChecked");

                if (checkedItems.Length > 0)
                {
                    if (filterValue.Length > 0)
                    {
                        filterValue = filterValue + ",,";
                    }

                    filterValue = filterValue + select.GetAttribute("name") + "=";

                    for (int i = 0; i < checkedItems.Length; ++i)
                    {
                        if (i > 0)
                        {
                            filterValue = filterValue + "||";
                        }

                        filterValue = filterValue + ((InputElement)checkedItems[i]).Value;
                    }
                }
            });

            if (this.Filter != filterValue)
            {
                this.Filter = filterValue;

                if (postBack)
                {
                    PostBack(0);
                }
            }
        }
        public static void PendingChangesConfirmation(jQueryObject element,
            Func<bool> hasPendingChanges)
        {
            element.Bind("dialogbeforeclose", e =>
            {
                if (!e.HasOriginalEvent() || !hasPendingChanges())
                    return;

                e.PreventDefault();

                Q.Confirm("You have pending changes. Save them?", () =>
                {
                    element.Find("div.save-and-close-button").Click();
                }, new ConfirmOptions
                {
                    OnNo = () =>
                    {
                        element.Dialog().Close();
                    }
                });
            });
        }
Exemple #32
0
        private void ResizeElements()
        {
            var width        = element.GetWidth();
            var initialWidth = element.GetDataValue("flexify-width").As <int?>();

            if (initialWidth == null)
            {
                element.Data("flexify-width", width);
                initialWidth = width;
            }

            var height        = element.GetHeight();
            var initialHeight = element.GetDataValue("flexify-height").As <int?>();

            if (initialHeight == null)
            {
                element.Data("flexify-height", height);
                initialHeight = height;
            }

            xDifference = width - initialWidth.Value;
            yDifference = height - initialHeight.Value;

            var self = this;

            jQueryObject containers = element;

            var tabPanels = element.Find(".ui-tabs-panel");

            if (tabPanels.Length > 0)
            {
                containers = tabPanels.Filter(":visible");
            }

            containers.Find(".flexify").Add(tabPanels.Filter(".flexify:visible")).Each((i, e) =>
            {
                self.ResizeElement(J(e));
            });
        }
        private FetchQuerySettings Parse(string fetchXml, string layoutXml)
        {
            FetchQuerySettings querySettings = new FetchQuerySettings();

            //Quick find view features placeholders from {0} up to {4} based on attribute type.
            jQueryObject fetchXmlDOM = jQuery.FromHtml("<query>" + fetchXml
                                                       .Replace("{0}", "#Query#")
                                                       .Replace("{1}", "#QueryInt#")
                                                       .Replace("{2}", "#QueryCurrency#")
                                                       .Replace("{3}", "#QueryDateTime#")
                                                       .Replace("{4}", "#QueryFloat#")
                                                       + "</query>");
            jQueryObject fetchElement = fetchXmlDOM.Find("fetch");

            querySettings.FetchXml = fetchXmlDOM;

            ParseFetchXml(querySettings);

            querySettings.Columns = ParseLayoutXml(querySettings.RootEntity, layoutXml);

            return(querySettings);
        }
Exemple #34
0
        public static void PendingChangesConfirmation(jQueryObject element,
                                                      Func <bool> hasPendingChanges)
        {
            element.Bind("dialogbeforeclose", e =>
            {
                if (!e.HasOriginalEvent() || !hasPendingChanges())
                {
                    return;
                }

                e.PreventDefault();

                Q.Confirm("You have pending changes. Save them?", () =>
                {
                    element.Find("div.save-and-close-button").Click();
                }, new ConfirmOptions
                {
                    OnNo = () =>
                    {
                        element.Dialog().Close();
                    }
                });
            });
        }
        public void updatePager(PagingInfo pagingInfo)
        {
            NavigationState state = getNavState();

            jQueryObject firstButton = _container.Find(".sparkle-grid-paging-first");
            jQueryObject backButton  = _container.Find(".sparkle-grid-paging-back");
            jQueryObject nextButton  = _container.Find(".sparkle-grid-paging-next");
            jQueryObject label       = _container.Find(".sparkle-grid-status-label");
            jQueryObject pageInfo    = _container.Find(".sparkle-grid-status-paging-page");
            jQueryObject status      = _container.Find(".sparkle-grid-status-label");

            if (state.CanGotoFirst)
            {
                firstButton.RemoveClass("disabled");
            }
            else
            {
                firstButton.AddClass("disabled");
            }

            if (state.CanGotoPrev)
            {
                backButton.RemoveClass("disabled");
            }
            else
            {
                backButton.AddClass("disabled");
            }

            if (state.CanGotoNext)
            {
                nextButton.RemoveClass("disabled");
            }
            else
            {
                nextButton.AddClass("disabled");
            }

            status.Text(string.Format("{0} - {1} of {2} ({3} selected)", pagingInfo.FromRecord, pagingInfo.ToRecord, pagingInfo.TotalRows, _dataView.GetSelectedRows().Length.ToString()));
            pageInfo.Text(string.Format("Page {0}", pagingInfo.PageNum + 1));
        }
        public XrmLookupEditor(EditorArguments args)
            : base(args)
        {
            _args = args;
            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            jQueryObject inputField = _container.Find(".sparkle-input-inline");
            jQueryObject selectButton = _container.Find(".sparkle-lookup-button");
            _input = inputField;
            _input.Focus().Select();

            _autoComplete = inputField.Plugin<AutoCompleteObject>();

            AutoCompleteOptions options = new AutoCompleteOptions();

            options.MinLength = 100000;
            options.Delay = 0; // TODO- set to something that makes sense

            bool justSelected = false;
            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                if (_value == null) _value = new EntityReference(null,null,null);

                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item;
                string value = item.Label;
                _input.Value(value);
                _value.Id = ((EntityReference)item.Value).Id;
                _value.Name = ((EntityReference)item.Value).Name;
                _value.LogicalName = ((EntityReference)item.Value).LogicalName;
                justSelected = true;
                Script.Literal("return false;");

            };
            //
            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;");
            };

            XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options;

            // wire up source to CRM search
            Action<AutoCompleteRequest, Action<AutoCompleteItem[]>> queryDelegate = delegate(AutoCompleteRequest request, Action<AutoCompleteItem[]> response)
            {

                 // Get the option set values
                editorOptions.queryCommand(request.Term, 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(editorOptions.nameAttribute);
                        EntityReference id = new EntityReference(null, null, null);
                        id.Name = results[i].Label;
                        id.LogicalName = fetchResult.Entities[i].LogicalName;
                        id.Id = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute);
                        results[i].Value = id;

                        string typeCodeName = fetchResult.Entities[i].LogicalName;

                        // Get the type code from the name to find the icon
                        if (!string.IsNullOrEmpty(editorOptions.typeCodeAttribute))
                        {
                            typeCodeName = fetchResult.Entities[i].GetAttributeValue(editorOptions.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;
                    _autoComplete.AutoComplete(disableOption);
                });

            };

            options.Source = queryDelegate;
            inputField = _autoComplete.AutoComplete(options);
            ((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;
                _autoComplete.AutoComplete(enableOption);
                _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue());

            });

            // Bind return to searching
            _input.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    if (inputField.GetValue().Length > 0)
                        selectButton.Click();
                    else
                    {
                        // Set value to null
                        _value = null;
                        return;
                    }
                }
                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;
            });
        }
        public XrmLookupEditor(EditorArguments args)
            : base(args)
        {
            XrmLookupEditor self = this;

            _args = args;
            _container = jQuery.FromHtml("<div><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            jQueryObject inputField = _container.Find(".sparkle-input-inline");
            jQueryObject selectButton = _container.Find(".sparkle-lookup-button");
            _input = inputField;
            _input.Focus().Select();

            _autoComplete = inputField.Plugin<AutoCompleteObject>();

            AutoCompleteOptions options = new AutoCompleteOptions();
            options.Position = new Dictionary<string, object>("collision", "fit");
            options.MinLength = 100000;
            options.Delay = 0; // TODO- set to something that makes sense
            XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options;

            bool justSelected = false;
            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                if (_value == null) _value = new EntityReference(null,null,null);

                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item;
                EntityReference itemRef = (EntityReference)item.Value;
                if (itemRef.LogicalName == "footerlink")
                {
                    XrmLookupEditorButton button = editorOptions.footerButton;
                    button.OnClick(item);
                }
                else
                {
                    string value = item.Label;
                    _input.Value(value);
                    _value.Id = itemRef.Id;
                    _value.Name = itemRef.Name;
                    _value.LogicalName = ((EntityReference)item.Value).LogicalName;
                    justSelected = true;
                }
                Script.Literal("return false;");

            };

            options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent)
            {
                // Prevent the value being updated in the text box as we scroll through the results
                Script.Literal("return false;");
            };

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

            options.Close = delegate(jQueryEvent e, jQueryObject o)
            {
                self._searchOpen = false;
                WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget");
                jQueryObject footer = menu.Next();
                if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer"))
                {
                    footer.Hide();
                }
            };

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

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

            // wire up source to CRM search
            Action<AutoCompleteRequest, Action<AutoCompleteItem[]>> queryDelegate = delegate(AutoCompleteRequest request, Action<AutoCompleteItem[]> response)
            {
                 // Get the option set values
                editorOptions.queryCommand(request.Term, delegate(EntityCollection fetchResult)
                {
                    if (fetchResult.TotalRecordCount > fetchResult.Entities.Count)
                    {
                        totalRecordsReturned = fetchResult.TotalRecordCount;
                    }
                    else
                    {
                        totalRecordsReturned = fetchResult.Entities.Count;
                    }

                    int recordsFound = fetchResult.Entities.Count;
                    bool noRecordsFound = recordsFound == 0;
                    XrmLookupEditorButton button = editorOptions.footerButton;
                    bool footerButton = (button != null);

                    AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton ? 1 : 0) + (noRecordsFound ? 1 :0) ];

                    for (int i = 0; i < recordsFound; i++)
                    {
                        results[i] = new AutoCompleteItem();
                        results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(editorOptions.nameAttribute);
                        EntityReference id = new EntityReference(null, null, null);
                        id.Name = results[i].Label;
                        id.LogicalName = fetchResult.Entities[i].LogicalName;
                        id.Id = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute);
                        results[i].Value = id;
                        XrmLookupBinding.GetExtraColumns(editorOptions.columns, fetchResult, results, i);
                        string typeCodeName = fetchResult.Entities[i].LogicalName;

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

                        if (editorOptions.showImage)
                        {
                            results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName);
                        }
                    }

                    int itemsCount = recordsFound;
                    if (noRecordsFound)
                    {
                        AutoCompleteItem noRecordsItem = new AutoCompleteItem();
                        noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound;
                        results[itemsCount] = noRecordsItem;
                        itemsCount++;
                    }

                    if (footerButton)
                    {
                        // Add the add new
                        AutoCompleteItem addNewLink = new AutoCompleteItem();
                        addNewLink.Label = button.Label;
                        addNewLink.Image = button.Image;
                        addNewLink.ColumnValues = null;
                        addNewLink.Value = new Entity("footerlink");
                        results[itemsCount] = addNewLink;
                    }
                    response(results);

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

            };

            options.Source = queryDelegate;
            inputField = _autoComplete.AutoComplete(options);
            RenderItemDelegate autoCompleteDelegates = ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField));
            autoCompleteDelegates._renderItem = delegate(object ul, AutoCompleteItem item)
            {
                if(item.Value==item.Label)
                {
                    return (object)jQuery.Select("<li class='ui-state-disabled'>"+item.Label+"</li>").AppendTo((jQueryObject)ul);
                }

                string itemHtml = "<a class='sparkle-menu-item'>";
                // Allow for no image by passing false to 'ShowImage' on the XrmLookupEditorOptions options
                if (item.Image != null)
                {
                    itemHtml += "<span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span>";
                }
                itemHtml += "<span class='sparkle-menu-item-label'>" + item.Label + "</span><br/>";
                if (item.ColumnValues != null && item.ColumnValues.Length > 0)
                {
                    foreach (string value in item.ColumnValues)
                    {
                        itemHtml += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>";
                    }
                }
                itemHtml += "</a>";
                return (object)jQuery.Select("<li>").Append(itemHtml).AppendTo((jQueryObject)ul);
            };

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                AutoCompleteOptions enableOption = new AutoCompleteOptions();
                enableOption.MinLength = 0;
                _autoComplete.AutoComplete(enableOption);
                _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue());

            });

            // Bind return to searching
            _input.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    if (inputField.GetValue().Length > 0)
                        selectButton.Click();
                    else
                    {
                        // Set value to null
                        _value = null;
                        return;
                    }
                }
                else if (e.Which == 13)
                {
                    return;
                }
                if (self._searchOpen)
                {
                    switch (e.Which)
                    {
                        case 9:
                        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;
                    }
                }
                else
                {
                    switch (e.Which)
                    {
                        case 13: // Return
                            e.PreventDefault();
                            e.StopPropagation();
                            break;

                    }
                }
                justSelected = false;
            });
        }
Exemple #38
0
        public XrmTimeEditor(EditorArguments args)
            : base(args)
        {
            bool justSelected = false;

            XrmTimeEditor self = this;
            if (OrganizationServiceProxy.UserSettings != null)
            {
                _formatString = OrganizationServiceProxy.UserSettings.TimeFormatString;
            }

            _container = jQuery.FromHtml("<div ><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='autocompleteButton' /></td></tr></table></div>");

            _container.AppendTo(_args.Container);

            jQueryObject inputField = _container.Find(".sparkle-input-inline");

            _input = inputField;
            _input.Focus().Select();
            string timeFormatString = _formatString;
            AutoCompleteOptions options = GetTimePickerAutoCompleteOptions(timeFormatString);

            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                justSelected = true;
            };
            options.Open = delegate(jQueryEvent e, jQueryObject o)
            {
                self._searchOpen = true;
            };

            options.Close = delegate(jQueryEvent e, jQueryObject o)
            {
                self._searchOpen = false;
            };

            inputField = inputField.Plugin<AutoCompleteObject>().AutoComplete(options);
            jQueryObject selectButton = _container.Find(".autocompleteButton");
            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                inputField.Plugin<AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search, "");
            });

            // Bind return to searching

            _input.Keydown(delegate(jQueryEvent e)
            {

                if (self._searchOpen)
                {
                    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;
            });
        }
        public TemplateControl(object oTemplate)
        {
            // init static stuff
            if (!_bStaticConstructionFinished)
            {
                StaticConstructor();
            }

            // continue instance setup..
            this._strInstanceId = GenerateNewInstanceId();

            string strTemplate;

            // grab template
            if (Script.IsNullOrUndefined(oTemplate))
            {
                strTemplate = FindTemplate(this);
#if DEBUG
                if (string.IsNullOrEmpty(strTemplate))
                {
                    throw new Exception(this.GetType().FullName + " is missing a Template member and no template was provided.");
                }
#endif
            }
            else
            {
                if (oTemplate is string)
                {
                    strTemplate = (string)oTemplate;
                }
                else
                {
                    jQueryObject jqTemplate = jQuery.FromObject(oTemplate);
                    strTemplate = "<" + jqTemplate[0].TagName + ">" + jqTemplate.GetHtml() + "</" + jqTemplate[0].TagName + ">";
                }
            }

            _hash_oNamedChildControls = new Dictionary();
            _hash_oNamedChildElements = new Dictionary();

            jQueryObject jqHead = jQuery.Select("head");

            // grab template
            if (Script.IsNullOrUndefined(strTemplate))
            {
                strTemplate = (string)Type.GetField(this, "template");
            }
#if DEBUG
            if (string.IsNullOrEmpty(strTemplate))
            {
                throw new Exception(this.GetType().FullName + " is missing a Template member.");
            }
#endif
            // generate an absolute id for this control
            string newId = GenerateNewAutoId();

#if DEBUG
            // is there a conflict in the auto gen'd id?
            {
                int numOtherControlsWithId = jQuery.Select("#" + newId).Length;
                if (numOtherControlsWithId != 0)
                {
                    throw new Exception("Auto generated id conflict.");
                }
            }
#endif

            // parse template
            jQueryObject jqContent = jQuery.FromHtml(strTemplate.Replace("`", "\""));

            // are there style tags?
            string strStyleRules = string.Empty;
            jqContent.Filter("style").Each(delegate(int i, Element e)
            {
                jQueryObject jqElement = jQuery.FromElement(e);
                strStyleRules += jqElement.GetHtml();
                jqElement.Remove();
            });

            // proceed with non-style tags
            jqContent = jqContent.Not("style").Remove();

            // remove attribute id if any
#if DEBUG
            if (!string.IsNullOrEmpty(jqContent.GetAttribute("id")))
            {
                throw new Exception("Global ID's not permitted. Element with ID \"" + jqContent.GetAttribute("id") + "\" found.");
            }
#endif
            jqContent.RemoveAttr("id");

            // store reference
            _jqRootElement = jqContent;

            // store reference from element back to this control
            _jqRootElement.Data(DataNameControl, this);

            // identify locally-named elements. this runs before parsing children because we don't want to add children's locally-named html elements.
            {
                jqContent.Find("*[" + AttributeNameLocalId + "]").Each(
                    delegate(int i, Element e)
                    {
                        jQueryObject jqElement = jQuery.FromElement(e);
                        if (!string.IsNullOrEmpty(jqElement.GetAttribute(AttributeNameControlClass)))
                        {
                            return;
                        }

                        string strLocalId = GetLocalId(jqElement);
                        if (strLocalId == null)
                        {
                            return;
                        }

                        // store record of it
                        this._hash_oNamedChildElements[strLocalId] = jqElement;

                        // remove absolute id if any
#if DEBUG
                        if (!string.IsNullOrEmpty(jqElement.GetAttribute("id")))
                        {
                            throw new Exception("Global ID's not permitted. Element with ID \"" + jqElement.GetAttribute("id") + "\" found.");
                        }
#endif
                        jqElement.RemoveAttr("id");
                    })
                ;
            }

            // rewrite image and image button paths
            {
                string baseUrl = BaseUrlImages;
                if (baseUrl.Length > 0)
                {
                    jqContent.Find("img, input[type=image]").Each(
                        delegate(int i, Element e)
                        {
                            jQueryObject jqe = jQuery.FromElement(e);
                            string src = jqe.GetAttribute("src");
                            if (string.IsNullOrEmpty(src))
                            {
                                string nullSrc = "http://null-image";

                                if (Window.Location.Protocol == "https:")
                                {
                                    nullSrc = "https://null-image";
                                }

                                jqe.Attribute("src", nullSrc);
                                return;
                            }

                            if (src.StartsWith("http://") || src.StartsWith("https://"))
                            {
                                return;
                            }

                            jqe.Attribute("src", CombinePaths(baseUrl, src));
                        }
                    );
                }
            }

            // calculcate search namespace
            Type currentType = this.GetType();
            string currentTopLevelNamespace
                = currentType
                .FullName
                .Substr(0, currentType.FullName.IndexOf('.'))
            ;

            // add class for identifying this as a template control
            _jqRootElement.AddClass(CssClassNameControl);

            // add class for identifying this as a newly added template control
            _jqRootElement.AddClass(CssClassNameControlUnadded);

            // recurse into child controls // todo: move this to *after* processing labels and images?
            jqContent.Find("div[" + AttributeNameControlClass + "]").Each(
                delegate(int index, Element element)
                {
                    jQueryObject jqElement = jQuery.FromElement(element);
                    string strChildTypeName = jqElement.GetAttribute(AttributeNameControlClass);

                    string strChildTypeNameResolved
                        = ResolveTypeName(
                            strChildTypeName,
                            currentTopLevelNamespace
                        )
                    ;
                    Type oChildType = Type.GetType(strChildTypeNameResolved);

                    if (Script.IsNullOrUndefined(oChildType))
                    {
#if DEBUG
                        throw new Exception("Could not locate type \"" + (strChildTypeNameResolved ?? strChildTypeName) + "\"");
#else
                        return;
#endif
                    }

                    TemplateControl childControl = Type.CreateInstance(oChildType, null) as TemplateControl;

                    if (!(childControl is TemplateControl))
                    {
                        // this check is still needed because of how the 'as' operator behaves in Script#.
#if DEBUG
                        throw new Exception("Control must derive from 'TemplateControl'.");
#else
                        return;
#endif
                    }

                    // grab local id if any
                    string strLocalId = GetLocalId(jqElement) ?? GenerateNewAutoId();

                    // store named control
                    if (strLocalId != null)
                    {
                        this._hash_oNamedChildControls[strLocalId] = childControl;
                    }

                    // merge style and class attributes
                    string strClass = jqElement.GetAttribute("class");
                    string strStyle = jqElement.GetAttribute("style");
                    if (!string.IsNullOrEmpty(strClass))
                    {
                        string strClassFromTemplate = childControl.RootElement.GetAttribute("class") ?? string.Empty;
                        childControl.RootElement.Attribute("class", strClassFromTemplate + " " + strClass);
                    }
                    if (!string.IsNullOrEmpty(strStyle))
                    {
                        string strStyleFromTemplate = childControl.RootElement.GetAttribute("style") ?? string.Empty;
                        childControl.RootElement.Attribute("style", strStyleFromTemplate + " " + strStyle);
                    }

                    // preserve other attributes
                    for (int i = 0, m = jqElement[0].Attributes.Length; i < m; ++i)
                    {
                        ElementAttribute a = (ElementAttribute)Type.GetField(jqElement[0].Attributes, (string)(object)i);
                        if (jQuery.Browser.Version == "7.0" && jQuery.Browser.MSIE && !a.Specified)
                        {
                            continue;
                        }
                        string attributeName = a.Name.ToLowerCase();
                        switch (attributeName)
                        {
                            case "id":
                            case "xid":
                            case "class":
                            case "style":
                            case "control":
                                break;
                            default:
                                childControl.RootElement.Attribute(a.Name, a.Value);
                                break;
                        }
                    }

                    // replace the placeholder element with the new control.
                    jqElement.RemoveAttr("id").After(childControl.RootElement).Remove();

                    // preserve local id & control type name
                    if (strLocalId != null)
                    {
                        childControl.RootElement.Attribute("xid", strLocalId);
                    }
                    childControl.RootElement.Attribute("control", jqElement.GetAttribute(AttributeNameControlClass));

                    // any children content?
                    jQueryObject jqChildContent = jqElement.Find(">*");
                    if (jqChildContent.Length > 0)
                    {
                        childControl.ProcessChildContent(jqChildContent);
                    }
                }
            );

            // rewrite radio input groups // todo: do this before processing child controls?
            {
                jQueryObject jqRadioInputs = _jqRootElement.Find("input[type=radio]");
                Dictionary hash_rewrittenGroupNames = new Dictionary();
                jqRadioInputs.Each(delegate(int index, Element element)
                {
                    jQueryObject jqRadio = jQuery.FromElement(element);

                    // rewrite name attribute
                    {
                        string strGroupName = jqRadio.GetAttribute("name");
                        if (string.IsNullOrEmpty(strGroupName))
                        {
                            return;
                        }
                        // need a new name?
                        string strNewGroupName;
                        if (hash_rewrittenGroupNames.ContainsKey(strGroupName))
                        {
                            strNewGroupName = (string)hash_rewrittenGroupNames[strGroupName];
                        }
                        else
                        {
                            hash_rewrittenGroupNames[strGroupName] = strNewGroupName = GenerateNewAutoId();
                        }
                        jqRadio.Attribute("name", strNewGroupName);
                    }

                    // make sure the element has an id, for label elements to use
                    if (string.IsNullOrEmpty(jqRadio.GetAttribute("id")))
                    {
                        jqRadio.Attribute("id", GenerateNewAutoId());
                    }
                });
                this._hash_rewrittenGroupNames = hash_rewrittenGroupNames;
            }

            // rewrite label elements // todo: do this before processing child controls?
            {
                jQueryObject jqLabels = _jqRootElement.Find("label[for]");
                jqLabels.Each(delegate(int index, Element element)
                {
                    if (_bPresented) { } // workaround to delegate bug in Script# 0.7.0.0
                    jQueryObject jqLabelElement = jQuery.FromElement(element);
                    string strForId = jqLabelElement.GetAttribute("for");
                    // is this element rewritten?
                    jQueryObject jqTargetElement = TryGetElement(strForId);
                    if (jqTargetElement == null)
                    {
                        return;
                    }
                    string strTargetElementNewId = jqTargetElement.GetAttribute("id");
                    // make sure the "for" element has an id
                    if (string.IsNullOrEmpty(strTargetElementNewId))
                    {
                        jqTargetElement.Attribute("id", strTargetElementNewId = GenerateNewAutoId());
                    }
                    jqLabelElement.Attribute("for", strTargetElementNewId);

                    return;
                });
            }

            // fixup css rules & add to head
            if (strStyleRules.Length != 0)
            {
                ProcessCss(this, strStyleRules);
            }

            // auto fill members that point to elements/controls
            AutoFillMemberFields();

            // any elements with advanced layout enabled?
            AdvancedLayout.AutoEnable(_jqRootElement);
        }
        // image deletion function
        static void DeleteImage(jQueryObject item)
        {
            string recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";

            item.FadeOut(EffectDuration.Slow, delegate()
            {
                jQueryObject list = jQuery.Select("ul", jQuery.Select("#trash")).Length > 0 ?
                                    jQuery.Select("ul", jQuery.Select("#trash")) :
                                    jQuery.Select("<ul class='gallery ui-helper-reset'/>").AppendTo("#trash");

                item.Find("a.ui-icon-trash").Remove();
                item.Append(recycle_icon).AppendTo(list).FadeIn(EffectDuration.Slow, delegate()
                {
                    item.Animate(new Dictionary("width", "48px"))
                        .Find("img")
                        .Animate(new Dictionary("height", "36px"));
                });
            });
        }
        // image recycle function
        static void RecycleImage(jQueryObject item)
        {
            string trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";

            item.FadeOut(EffectDuration.Slow, delegate()
            {
                item.Find("a.ui-icon-refresh")
                    .Remove()
                    .End()
                    .CSS("width", "96px")
                    .Append(trash_icon)
                    .Find("img")
                    .CSS("height", "72px")
                    .End()
                    .AppendTo("#gallery")
                    .FadeIn();
            });
        }