Beispiel #1
0
        public static void AddFooter(WidgetObject menu, int recordCount)
        {
            jQueryObject footer = menu.Next();

            if (footer.Length == 0 || !footer.HasClass("sparkle-menu-footer"))
            {
                footer = jQuery.FromHtml("<div class='sparkle-menu-footer ui-front'></div>");
                menu.Parent().Append(footer);
            }

            if (footer != null)
            {
                footer.Html("");
                jQueryObject footerContent = jQuery.FromHtml("<span class='sparkle-menu-footer-content'></span>");
                jQueryObject footerLeft    = jQuery.FromHtml("<span class='sparkle-menu-footer-left'></span>");
                jQueryObject footerRight   = jQuery.FromHtml("<span class='sparkle-menu-footer-right'></span>");
                footerContent.Append(footerLeft);
                footerContent.Append(footerRight);
                footerLeft.Append(String.Format(SparkleResourceStrings.LookupFooter, recordCount));
                footer.Append(footerContent);
            }

            jQueryPosition pos    = menu.Position();
            int            height = menu.GetHeight();
            int            width  = menu.GetWidth();

            if (footer != null && footer.Length > 0)
            {
                footer.Show();
                footer.CSS("top", (pos.Top + height + 4).ToString() + "px");
                footer.CSS("left", (pos.Left).ToString() + "px");
                footer.Width(width);
            }
        }
Beispiel #2
0
        public ActionResult DeleteWidget()
        {
            bool ret = true;

            try
            {
                DashboardWidget qw = new DashboardWidget(ConnectionString);

                GetDashboardObject DashBoardObject = (GetDashboardObject)Session["DashBoard"];
                WidgetObject       PostDataArrived = CS.GetPostData <WidgetObject>(this.Request);

                ret = qw.DeleteWidget(PostDataArrived.id);

                DashboardRow dRow = DashBoardObject.rows.Find(r => r.widgets.Find(w => w.id == PostDataArrived.id) != null);

                dRow.widgets.Remove(dRow.widgets.Find(w => w.id == PostDataArrived.id));

                Session["DashBoard"] = DashBoardObject;

                return(CS.ReturnForJQuery(ret));
            }
            catch (Exception ex)
            {
                return(CS.ReturnForJQuery(new JavaScriptSerializer().Serialize(new ISTAT.WebClient.Models.ControllerSupport.StringResult()
                {
                    Msg = ex.Message
                })));
            }
        }
Beispiel #3
0
        public ActionResult AddWidget()
        {
            WidgetObject woRet;

            try
            {
                DashboardWidget qw = new DashboardWidget(ConnectionString);

                GetDashboardObject DashBoardObject = (GetDashboardObject)Session["DashBoard"];
                WidgetObject       PostDataArrived = CS.GetPostData <WidgetObject>(this.Request);

                woRet = qw.AddWidget(PostDataArrived);

                DashboardRow dbRow = DashBoardObject.rows.Find(r => r.id == woRet.rowID);

                if (dbRow.widgets == null)
                {
                    dbRow.widgets = new List <WidgetObject>();
                }

                dbRow.widgets.Add(woRet);

                Session["DashBoard"] = DashBoardObject;

                return(CS.ReturnForJQuery(woRet));
            }
            catch (Exception ex)
            {
                return(CS.ReturnForJQuery(new JavaScriptSerializer().Serialize(new ISTAT.WebClient.Models.ControllerSupport.StringResult()
                {
                    Msg = ex.Message
                })));
            }
        }
        public List <WidgetObject> GetDashBoardWidget(int rowId)
        {
            List <WidgetObject> lWidgets = new List <WidgetObject>();
            SqlDataReader       oReader;

            try
            {
                using (SqlCommand oComm = new SqlCommand())
                {
                    if (Sqlconn.State == ConnectionState.Closed)
                    {
                        Sqlconn.Open();
                    }

                    oComm.Connection  = Sqlconn;
                    oComm.CommandType = CommandType.StoredProcedure;
                    oComm.CommandText = "DashBoard.GetDashBoardWidget";

                    SqlParameter pRowID = new SqlParameter("@IDROW", SqlDbType.Int);
                    pRowID.Value = rowId;
                    oComm.Parameters.Add(pRowID);

                    oReader = oComm.ExecuteReader();

                    while (oReader.Read())
                    {
                        WidgetObject widget = new WidgetObject()
                        {
                            id                       = (int)oReader["wdg_id"],
                            cssClass                 = oReader["wdg_class"] != DBNull.Value ? oReader["wdg_class"].ToString() : string.Empty,
                            rowID                    = (int)oReader["wdg_row_id"],
                            cell                     = (int)oReader["wdg_cell"],
                            type                     = oReader["wdg_type"] != DBNull.Value ? oReader["wdg_type"].ToString() : string.Empty,
                            chartype                 = oReader["wdg_chartType"] != DBNull.Value ? oReader["wdg_chartType"].ToString() : string.Empty,
                            v                        = oReader["wdg_v"] != DBNull.Value ? (bool)oReader["wdg_v"] : false,
                            vt                       = oReader["wdg_vt"] != DBNull.Value ? (bool)oReader["wdg_vt"] : false,
                            vc                       = oReader["wdg_vc"] != DBNull.Value ? (bool)oReader["wdg_vc"] : false,
                            endPoint                 = oReader["wdg_endPoint"] != DBNull.Value ? oReader["wdg_endPoint"].ToString() : string.Empty,
                            endPointType             = oReader["wdg_endPointType"] != DBNull.Value ? oReader["wdg_endPointType"].ToString() : string.Empty,
                            endPointV20              = oReader["wdg_endPointV20"] != DBNull.Value ? oReader["wdg_endPointV20"].ToString() : string.Empty,
                            endPointSource           = oReader["wdg_endPointSource"] != DBNull.Value ? oReader["wdg_endPointSource"].ToString() : string.Empty,
                            endPointDecimalSeparator = oReader["wdg_decimalCulture"] != DBNull.Value ? oReader["wdg_decimalCulture"].ToString() : string.Empty,
                            dataflow_id              = oReader["wdg_dataflow_id"] != DBNull.Value ? oReader["wdg_dataflow_id"].ToString() : string.Empty,
                            dataflow_agency_id       = oReader["wdg_dataflow_agency_id"] != DBNull.Value ? oReader["wdg_dataflow_agency_id"].ToString() : string.Empty,
                            dataflow_version         = oReader["wdg_dataflow_version"] != DBNull.Value ? oReader["wdg_dataflow_version"].ToString() : string.Empty,
                            criteria                 = oReader["wdg_criteria"] != DBNull.Value ? oReader["wdg_criteria"].ToString() : string.Empty,
                            layout                   = oReader["wdg_layout"] != DBNull.Value ? oReader["wdg_layout"].ToString() : string.Empty
                        };

                        lWidgets.Add(widget);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (Sqlconn.State == ConnectionState.Open)
                {
                    Sqlconn.Close();
                }
            }

            return(lWidgets);
        }
        public WidgetObject UpdateWidget(WidgetObject widgetObject)
        {
            bool ret = true;

            try
            {
                using (SqlCommand oComm = new SqlCommand())
                {
                    if (Sqlconn.State == ConnectionState.Closed)
                    {
                        Sqlconn.Open();
                    }
                    oComm.Connection  = Sqlconn;
                    oComm.CommandType = CommandType.StoredProcedure;
                    oComm.CommandText = "DashBoard.UpdateWidget";

                    SqlParameter pWDGID = new SqlParameter("@WDG_ID", SqlDbType.Int);
                    pWDGID.Value = widgetObject.id;
                    oComm.Parameters.Add(pWDGID);

                    SqlParameter pWdgClass = new SqlParameter("@WDG_CLASS", SqlDbType.NVarChar);
                    pWdgClass.Value = widgetObject.cssClass;
                    oComm.Parameters.Add(pWdgClass);

                    SqlParameter pRowID = new SqlParameter("@WDG_ROW_ID", SqlDbType.Int);
                    pRowID.Value = widgetObject.rowID;
                    oComm.Parameters.Add(pRowID);

                    SqlParameter pWdgCell = new SqlParameter("@WDG_CELL", SqlDbType.Int);
                    pWdgCell.Value = widgetObject.cell;
                    oComm.Parameters.Add(pWdgCell);

                    SqlParameter pType = new SqlParameter("@WDG_TYPE", SqlDbType.NVarChar);
                    pType.Value = widgetObject.type;
                    oComm.Parameters.Add(pType);

                    SqlParameter pChartType = new SqlParameter("@WDG_CHARTTYPE", SqlDbType.NVarChar);
                    pChartType.Value = widgetObject.chartype;
                    oComm.Parameters.Add(pChartType);

                    SqlParameter pV = new SqlParameter("@WDG_V", SqlDbType.Bit);
                    pV.Value = widgetObject.v;
                    oComm.Parameters.Add(pV);

                    SqlParameter pVT = new SqlParameter("@WDG_VT", SqlDbType.Bit);
                    pVT.Value = widgetObject.vt;
                    oComm.Parameters.Add(pVT);

                    SqlParameter pVC = new SqlParameter("@WDG_VC", SqlDbType.Bit);
                    pVC.Value = widgetObject.vc;
                    oComm.Parameters.Add(pVC);

                    SqlParameter pEndPoint = new SqlParameter("@WDG_ENDPOINT", SqlDbType.NVarChar);
                    pEndPoint.Value = widgetObject.endPoint;
                    oComm.Parameters.Add(pEndPoint);

                    SqlParameter pEndPointType = new SqlParameter("@WDG_ENDPOINTTYPE", SqlDbType.NVarChar);
                    pEndPointType.Value = widgetObject.endPointType;
                    oComm.Parameters.Add(pEndPointType);

                    SqlParameter pEndPointV20 = new SqlParameter("@WDG_ENDPOINTV20", SqlDbType.NVarChar);
                    pEndPointV20.Value = widgetObject.endPointV20;
                    oComm.Parameters.Add(pEndPointV20);


                    SqlParameter pEndPointSource = new SqlParameter("@WDG_ENDPOINTSOURCE", SqlDbType.NVarChar);
                    pEndPointSource.Value = widgetObject.endPointSource;
                    oComm.Parameters.Add(pEndPointSource);

                    SqlParameter pEndPointDecimal = new SqlParameter("@WDG_ENDPOINTDECIMAL", SqlDbType.NVarChar);
                    pEndPointDecimal.Value = widgetObject.endPointDecimalSeparator;
                    oComm.Parameters.Add(pEndPointDecimal);

                    SqlParameter pDataFlowID = new SqlParameter("@WDG_DATAFLOW_ID", SqlDbType.NVarChar);
                    pDataFlowID.Value = widgetObject.dataflow_id;
                    oComm.Parameters.Add(pDataFlowID);

                    SqlParameter pAgencyID = new SqlParameter("@WDG_DATAFLOW_AGENCY_ID", SqlDbType.NVarChar);
                    pAgencyID.Value = widgetObject.dataflow_agency_id;
                    oComm.Parameters.Add(pAgencyID);

                    SqlParameter pVersion = new SqlParameter("@WDG_DATAFLOW_VERSION", SqlDbType.NVarChar);
                    pVersion.Value = widgetObject.dataflow_version;
                    oComm.Parameters.Add(pVersion);

                    SqlParameter pCriteria = new SqlParameter("@WDG_CRITERIA", SqlDbType.NText);
                    pCriteria.Value = widgetObject.criteria;
                    oComm.Parameters.Add(pCriteria);

                    SqlParameter pLayout = new SqlParameter("@WDG_LAYOUT", SqlDbType.NText);
                    pLayout.Value = widgetObject.layout;
                    oComm.Parameters.Add(pLayout);

                    oComm.ExecuteNonQuery();

                    foreach (TextLocalised tl in widgetObject.text)
                    {
                        UpdateWidgetText(widgetObject.id, tl);
                    }
                }
            }
            catch (Exception ex)
            {
                ret = false;
                throw ex;
            }
            finally
            {
                if (Sqlconn.State == ConnectionState.Open)
                {
                    Sqlconn.Close();
                }
            }

            return(widgetObject);
        }
Beispiel #6
0
        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;
            });
        }
Beispiel #7
0
        public List <WidgetObject> GetUpdateableWidgets()
        {
            List <WidgetObject> lWidgets = new List <WidgetObject>();
            SqlDataReader       oReader;

            try
            {
                using (SqlCommand oComm = new SqlCommand())
                {
                    if (Sqlconn.State == ConnectionState.Closed)
                    {
                        Sqlconn.Open();
                    }

                    oComm.Connection  = Sqlconn;
                    oComm.CommandType = CommandType.StoredProcedure;
                    oComm.CommandText = "Caching.GetUpdateableWidgets";

                    oReader = oComm.ExecuteReader();

                    while (oReader.Read())
                    {
                        WidgetObject widget = new WidgetObject()
                        {
                            id                       = (int)oReader["wdg_id"],
                            cssClass                 = oReader["wdg_class"] != DBNull.Value ? oReader["wdg_class"].ToString() : string.Empty,
                            rowID                    = (int)oReader["wdg_row_id"],
                            cell                     = (int)oReader["wdg_cell"],
                            type                     = oReader["wdg_type"] != DBNull.Value ? oReader["wdg_type"].ToString() : string.Empty,
                            chartype                 = oReader["wdg_chartType"] != DBNull.Value ? oReader["wdg_chartType"].ToString() : string.Empty,
                            v                        = oReader["wdg_v"] != DBNull.Value ? (bool)oReader["wdg_v"] : false,
                            vt                       = oReader["wdg_vt"] != DBNull.Value ? (bool)oReader["wdg_vt"] : false,
                            vc                       = oReader["wdg_vc"] != DBNull.Value ? (bool)oReader["wdg_vc"] : false,
                            endPoint                 = oReader["wdg_endPoint"] != DBNull.Value ? oReader["wdg_endPoint"].ToString() : string.Empty,
                            endPointType             = oReader["wdg_endPointType"] != DBNull.Value ? oReader["wdg_endPointType"].ToString() : string.Empty,
                            endPointV20              = oReader["wdg_endPointV20"] != DBNull.Value ? oReader["wdg_endPointV20"].ToString() : string.Empty,
                            endPointDecimalSeparator = oReader["wdg_decimalCulture"] != DBNull.Value ? oReader["wdg_decimalCulture"].ToString() : string.Empty,
                            endPointSource           = oReader["wdg_endpointSource"] != DBNull.Value ? oReader["wdg_endpointSource"].ToString() : string.Empty,
                            dataflow_id              = oReader["wdg_dataflow_id"] != DBNull.Value ? oReader["wdg_dataflow_id"].ToString() : string.Empty,
                            dataflow_agency_id       = oReader["wdg_dataflow_agency_id"] != DBNull.Value ? oReader["wdg_dataflow_agency_id"].ToString() : string.Empty,
                            dataflow_version         = oReader["wdg_dataflow_version"] != DBNull.Value ? oReader["wdg_dataflow_version"].ToString() : string.Empty,
                            criteria                 = oReader["wdg_criteria"] != DBNull.Value ? oReader["wdg_criteria"].ToString() : string.Empty,
                            layout                   = oReader["wdg_layout"] != DBNull.Value ? oReader["wdg_layout"].ToString() : string.Empty
                        };

                        widget.text = new List <TextLocalised>()
                        {
                            new TextLocalised()
                            {
                                locale = oReader["wdg_text_Locale"].ToString()
                            }
                        };

                        lWidgets.Add(widget);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (Sqlconn.State == ConnectionState.Open)
                {
                    Sqlconn.Close();
                }
            }

            return(lWidgets);
        }
Beispiel #8
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 };");
        }
        static Default()
        {
            jQuery.OnDocumentReady(delegate() {
                // the widget definition, where "custom" is the namespace,
                // "colorize" the widget name
                jQueryUI.CreateWidget("custom.colorize",
                                      new WidgetOptions(
                                          // default options
                                          "options", new ColorizeOptions(
                                              ColorizeOption.Red, 255,
                                              ColorizeOption.Green, 0,
                                              ColorizeOption.Blue, 0,
                                              ColorizeMethod.Change, null,
                                              ColorizeMethod.Random, null),
                                          // the constructor
                                          WidgetMethod.Create, new Action(delegate() {
                    jQuery.Current
                    .Plugin <WidgetObject>()
                    .Element
                    .AddClass("custom-colorize")
                    .Plugin <jQueryUIObject>()
                    .DisableSelection();

                    jQuery.Current
                    .Plugin <ColorizeObject>()
                    .Changer = jQuery.FromHtml("<button>", new System.Collections.Dictionary("text", "change", "class", "custom-colorize-changer"))
                               .AppendTo(jQuery.Current
                                         .Plugin <WidgetObject>()
                                         .Element)
                               .Plugin <ButtonObject>()
                               .Button();

                    // bind click events on the changer button to the random method
                    // in 1.9 would use this._bind( this.changer, { click: "random" });
                    WidgetObject that = jQuery.Current.Plugin <WidgetObject>();

                    jQuery.Current
                    .Plugin <ColorizeObject>()
                    .Changer
                    .Bind("click.colorize", delegate(jQueryEvent e) {
                        // _bind would handle this check
                        if (((ColorizeOptions)that.Options).Disabled)
                        {
                            return;
                        }
                        that.Plugin <ColorizeObject>().Random.Apply(that, Arguments.Current);
                    });

                    jQuery.Current
                    .Plugin <ColorizeObject>()
                    .Refresh();
                }),
                                          // called when created, and later when changing options
                                          ColorizeMethod.Refresh, new Action(delegate() {
                    jQuery.Current
                    .Plugin <WidgetObject>()
                    .Element.CSS("background-color", "rgb(" +
                                 ((ColorizeOptions)jQuery.Current.Plugin <WidgetObject>().Options).Red + "," +
                                 ((ColorizeOptions)jQuery.Current.Plugin <WidgetObject>().Options).Green + "," +
                                 ((ColorizeOptions)jQuery.Current.Plugin <WidgetObject>().Options).Blue + ")"
                                 );

                    // trigger a callback/event
                    jQuery.Current
                    .Plugin <WidgetObject>()
                    .Trigger("change");
                }),
                                          // a public method to change the color to a random value
                                          // can be called directly via .colorize( "random" )
                                          ColorizeMethod.Random, new jQueryEventHandler(delegate(jQueryEvent e) {
                    ColorizeOptions colors = new ColorizeOptions(
                        ColorizeOption.Red, Math.Floor(Math.Random() * 256),
                        ColorizeOption.Green, Math.Floor(Math.Random() * 256),
                        ColorizeOption.Blue, Math.Floor(Math.Random() * 256)
                        );

                    // trigger an event, check if it's canceled
                    if (jQuery.Current
                        .Plugin <WidgetObject>()
                        .Trigger("random", e, colors))
                    {
                        jQuery.Current
                        .Plugin <WidgetObject>()
                        .Option(colors);
                    }
                }),
                                          // events bound via _bind are removed automatically
                                          // revert other modifications here
                                          WidgetMethod.Destroy, new Action(delegate() {
                    // remove generated elements
                    jQuery.Current
                    .Plugin <ColorizeObject>()
                    .Changer
                    .Remove();

                    jQuery.Current
                    .Plugin <WidgetObject>()
                    .Element
                    .RemoveClass("custom-colorize")
                    .Plugin <jQueryUIObject>()
                    .EnableSelection()
                    .CSS("background-color", "transparent");
                }),
                                          // _setOptions is called with a hash of all options that are changing
                                          // always refresh when changing options
                                          WidgetMethod.SetOptions, new Action(delegate() {
                    // in 1.9 would use _superApply( arguments)
                    ((WidgetObject)WidgetObject.Prototype).SetOptions.Apply(jQuery.Current, Arguments.Current);

                    jQuery.Current
                    .Plugin <ColorizeObject>()
                    .Refresh();
                }),
                                          // _setOption is called for each individual option that is changing
                                          WidgetMethod.SetOption, new Action <string, int>(delegate(string key, int value) {
                    // prevent invalid color values
                    if (new System.RegularExpression("red|green|blue").Test(key) && (value < 0 || value > 255))
                    {
                        return;
                    }
                    // in 1.9 would use _super
                    //$.Widget.prototype._setOption.call( this, key, value );
                    ((WidgetObject)WidgetObject.Prototype).SetOption.Call(jQuery.Current, key, value);
                })

                                          ));

                // initialize with default options
                jQuery.Select("#my-widget1")
                .Plugin <ColorizeObject>()
                .Colorize();

                // initialize with two customized options
                jQuery.Select("#my-widget2")
                .Plugin <ColorizeObject>()
                .Colorize(new ColorizeOptions(
                              ColorizeOption.Red, 60,
                              ColorizeOption.Blue, 60
                              ));

                // initialize with custom green value
                // and a random callback to allow only colors with enough green
                jQuery.Select("#my-widget3")
                .Plugin <ColorizeObject>()
                .Colorize(new ColorizeOptions(
                              ColorizeOption.Green, 128,
                              ColorizeMethod.Random, new Func <jQueryEvent, ColorizeOptions, bool>(delegate(jQueryEvent e, ColorizeOptions ui) {
                    return(ui.Green > 128);
                })
                              ));

                // click to toggle enabled/disabled
                jQuery.Select("#disable").Toggle(
                    new jQueryEventHandler(delegate(jQueryEvent e) {
                    // use the custom selector created for each widget to find all instances
                    jQuery.Select(":custom-colorize")
                    .Plugin <ColorizeObject>()
                    .Colorize(ColorizeMethod.Disable);
                }),
                    new jQueryEventHandler(delegate(jQueryEvent e) {
                    jQuery.Select(":custom-colorize")
                    .Plugin <ColorizeObject>()
                    .Colorize(ColorizeMethod.Enable);
                }));

                // click to set options after initalization
                jQuery.Select("#black").Click(delegate(jQueryEvent e) {
                    jQuery.Select(":custom-colorize")
                    .Plugin <ColorizeObject>()
                    .Colorize(ColorizeMethod.Option, new ColorizeOptions(
                                  ColorizeOption.Red, 0,
                                  ColorizeOption.Green, 0,
                                  ColorizeOption.Blue, 0
                                  ));
                });
            });
        }