private void AddThrottledControls()
        {
            var    maxItemsPerThrottledOperation = Web.Site.WebApplication.MaxItemsPerThrottledOperation;
            string throttleMessage = base.Field.Required
                ? throttleMessage = SPResource.GetString(
                "RequiredLookupThrottleMessage",
                new object[]
            {
                maxItemsPerThrottledOperation.ToString(CultureInfo.InvariantCulture)
            })
                : throttleMessage = SPResource.GetString(
                "LookupThrottleMessage",
                new object[]
            {
                maxItemsPerThrottledOperation.ToString(CultureInfo.InvariantCulture)
            });

            ThrottleMessageLiteral = new Literal
            {
                Text = SPHttpUtility.HtmlEncode(throttleMessage)
            };
            SpanLiteral = new Literal
            {
                Text = "<span style=\"vertical-align:middle\">"
            };
            SpanClosingLiteral = new Literal
            {
                Text = "</span>"
            };
            Controls.Add(SpanLiteral);
            Controls.Add(ThrottleMessageLiteral);
            Controls.Add(SpanClosingLiteral);
        }
 private void AddDropImage(SPFieldLookup field)
 {
     TextField = new TextBox();
     TextField.Attributes.Add("choices", Choices);
     TextField.Attributes.Add("match", string.Empty);
     TextField.Attributes.Add("onkeydown", "CoreInvoke('HandleKey')");
     TextField.Attributes.Add("onkeypress", "CoreInvoke('HandleChar')");
     TextField.Attributes.Add("onfocusout", "CoreInvoke('HandleLoseFocus')");
     TextField.Attributes.Add("onchange", "CoreInvoke('HandleChange')");
     TextField.Attributes.Add("class", "ms-lookuptypeintextbox");
     TextField.Attributes.Add("title", SPHttpUtility.HtmlEncode(field.Title));
     TextField.TabIndex             = TabIndex;
     TextField.Attributes["optHid"] = HiddenFieldName;
     SpanLiteral = new Literal
     {
         Text = "<span style=\"vertical-align:middle\">"
     };
     SpanClosingLiteral = new Literal
     {
         Text = "</span>"
     };
     Controls.Add(SpanLiteral);
     Controls.Add(TextField);
     TextField.Attributes.Add("opt", "_Select");
     DropImage          = new Image();
     DropImage.ImageUrl = "/_layouts/images/dropdown.gif";
     DropImage.Attributes.Add("alt", SPResource.GetString("LookupWordWheelDropdownAlt", new object[0]));
     DropImage.Attributes.Add("style", "vertical-align:middle;");
     Controls.Add(DropImage);
     Controls.Add(SpanClosingLiteral);
 }
Esempio n. 3
0
        public void AddToolbarButton(
            string buttonId,
            string buttonText,
            string navigationUrl,
            string tooltipText,
            string buttonImageSrc)
        {
            Literal buttonMarkupLiteral = new Literal();

            if (!string.IsNullOrEmpty(buttonImageSrc))
            {
                buttonMarkupLiteral.Text = String.Format(
                    SPSToolbarButtonImageHtmlFormatNav,
                    SPHttpUtility.HtmlEncode(buttonText),
                    SPHttpUtility.HtmlEncode(navigationUrl),
                    SPHttpUtility.HtmlEncode(tooltipText),
                    SPHttpUtility.HtmlUrlAttributeEncode(buttonImageSrc));
            }
            else
            {
                // No image
                buttonMarkupLiteral.Text = String.Format(
                    SPSToolbarButtonHtmlFormatNav,
                    SPHttpUtility.HtmlEncode(buttonText),
                    SPHttpUtility.HtmlEncode(navigationUrl),
                    SPHttpUtility.HtmlEncode(tooltipText));
            }

            buttonMarkupLiteral.ID = buttonId;

            Controls.Add(buttonMarkupLiteral);
        }
        public virtual void Validate()
        {
            this.m_fIsValid = true;
            Label label = null;

            if (webControl.ErrorMessageLabelControl.Length > 0)
            {
                label = webControl.FindControl(webControl.ErrorMessageLabelControl) as Label;
            }
            if ((webControl.Enabled && (webControl.MaxLength > 0)) && ((webControl.Text != null) && (webControl.Text.Length > webControl.MaxLength)))
            {
                webControl.ErrorMessage = SPHttpUtility.NoEncode(SPResource.GetString("InputLengthGreaterThanMaxLength", new object[] { webControl.MaxLength }));
                this.m_fIsValid         = false;
            }
            if (label != null)
            {
                if (this.m_fIsValid)
                {
                    label.Text = string.Empty;
                }
                else
                {
                    label.Text = SPHttpUtility.HtmlEncode(webControl.ErrorMessage);
                }
            }
        }
Esempio n. 5
0
 private static string GetFormattedErrorValue(string strType, string strData)
 {
     if (strType == "ERROR")
     {
         return(GetCalcLibErrorString(strData));
     }
     return(SPHttpUtility.HtmlEncode(SPResource.GetString("CalcLibErrorName", new object[0])));
 }
 private static string GetTermDefXml(Keyword keyword)
 {
     if (string.IsNullOrEmpty(keyword.Term) || string.IsNullOrEmpty(keyword.Definition))
     {
         return(string.Empty);
     }
     return(string.Format(
                "<SpecialTermInformation><Keyword>{0}</Keyword><Description>{1}</Description></SpecialTermInformation>",
                SPHttpUtility.HtmlEncode(keyword.Term), SPHttpUtility.HtmlEncode(keyword.Definition)));
 }
Esempio n. 7
0
 public static string HtmlEncode(string value)
 {
     if (!string.IsNullOrEmpty(value))
     {
         return(SPHttpUtility.HtmlEncode(value));
     }
     else
     {
         return(string.Empty);
     }
 }
Esempio n. 8
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         string scriptLiteralToEncode = base.Request.QueryString["Dialog"];
         this.PageName.Text = SPHttpUtility.EcmaScriptStringLiteralEncode(scriptLiteralToEncode);
         if (!string.IsNullOrEmpty(scriptLiteralToEncode) && (((scriptLiteralToEncode == "CreateLink") || (scriptLiteralToEncode == "InsertImage")) || (scriptLiteralToEncode == "InsertTable")))
         {
             this.PageTitle.Text     = SPHttpUtility.HtmlEncode("插入图片");
             this.FirstCaption.Text  = SPHttpUtility.HtmlEncode("提示:");
             this.SecondCaption.Text = SPHttpUtility.HtmlEncode("地址:");
         }
     }
 }
        private RequiredFieldValidator CreateRequiredFieldValidator(Control control)
        {
            RequiredFieldValidator requiredFieldValidator = new RequiredFieldValidator();

            requiredFieldValidator.ControlToValidate = control.ID;
            requiredFieldValidator.Display           = ValidatorDisplay.Dynamic;
            requiredFieldValidator.ForeColor         = Color.Empty;
            requiredFieldValidator.CssClass          = "ms-formvalidation";
            string @string = SPResource.GetString(Thread.CurrentThread.CurrentCulture, "MissingRequiredField", new object[0]);

            requiredFieldValidator.ErrorMessage       = "<span role=\"alert\" >" + SPHttpUtility.HtmlEncode(@string) + "</span><br/>";
            requiredFieldValidator.SetFocusOnError    = true;
            requiredFieldValidator.EnableClientScript = false;
            return(requiredFieldValidator);
        }
        private static string BuildBestBetXml(Keyword keyword, BestBet bestBet)
        {
            return(string.Format(
                       @"
                                            <Result>
			<id>{0}</id>
			<title>{1}</title>
			<description>{2}</description>
			<url>{3}</url>
			<urlEncoded>{3}</urlEncoded>
			<teaserContentType/>
			<FS14Description/>
			<keyword>KD[{4}]</keyword>
		</Result>"        ,
                       1, SPHttpUtility.HtmlEncode(bestBet.Name), SPHttpUtility.HtmlEncode(bestBet.Description),
                       bestBet.Uri.OriginalString, SPHttpUtility.HtmlEncode(keyword.Term)));
        }
Esempio n. 11
0
        public void AddToolBarActionButton(
            string buttonId,
            string buttonText,
            string clientOnClick,
            string tooltipText)
        {
            Literal buttonMarkupLiteral = new Literal();

            buttonMarkupLiteral.Text = String.Format(
                SPSToolbarButtonHtmlFormat,
                SPHttpUtility.HtmlEncode(buttonText),
                SPHttpUtility.HtmlEncode(clientOnClick),
                SPHttpUtility.HtmlEncode(tooltipText));
            buttonMarkupLiteral.ID = buttonId;

            Controls.Add(buttonMarkupLiteral);
        }
        public void OnSaveChange(SPField field, bool isNewField)
        {
            FilteredLookupField _f = null;

            try { _f = field as FilteredLookupField; }
            catch { }

            if (_f != null)
            {
                string s    = txtQueryFilter.Text;
                bool   rec  = cbxRecursiveFilter.Checked;
                string view = (listTargetListView.SelectedIndex > -1) ?
                              listTargetListView.SelectedItem.Value : string.Empty;
                string col   = listTargetColumn.SelectedItem.Value;
                string list  = listTargetList.SelectedItem.Value;
                bool   multi = cbxAllowMultiValue.Checked;

                if (isNewField)
                { // can only change list and web if new field
                    SPSite _site = SPControl.GetContextSite(this.Context);
                    using (SPWeb _web = _site.OpenWeb(new Guid(listTargetWeb.SelectedItem.Value)))
                    {
                        _f.LookupWebId = _web.ID;
                        _f.LookupList  = list;
                    }
                }

                if (rdFilterOption.SelectedItem.Value == "Query")
                {
                    _f.QueryFilterAsString = (!string.IsNullOrEmpty(s)) ? SPHttpUtility.HtmlEncode(s) : "";
                    _f.ListViewFilter      = "";
                }
                else if (rdFilterOption.SelectedItem.Value == "ListView")
                {
                    _f.ListViewFilter      = (!string.IsNullOrEmpty(view)) ? view : "";
                    _f.QueryFilterAsString = "";
                }

                _f.LookupField       = col;
                _f.IsFilterRecursive = rec;
                _f.UnlimitedLengthInDocumentLibrary = cbxUnlimitedLengthInDocLib.Checked;
                _f.CountRelated        = IsCountRelated(_f.LookupField, _f.LookupList);
                _f.AllowMultipleValues = (_f.CountRelated) ? false : multi;
            }
        }
Esempio n. 13
0
        public void AddToolBarActionButton(
            string buttonId,
            string buttonText,
            string clientOnClick,
            string tooltipText,
            string buttonImageSrc)
        {
            Literal buttonMarkupLiteral = new Literal();

            buttonMarkupLiteral.Text = String.Format(
                SPSToolBarActionButton,
                SPHttpUtility.HtmlEncode(buttonText),
                SPHttpUtility.HtmlEncode(clientOnClick),
                SPHttpUtility.HtmlEncode(tooltipText),
                SPHttpUtility.HtmlUrlAttributeEncode(buttonImageSrc));
            buttonMarkupLiteral.ID = buttonId;

            Controls.Add(buttonMarkupLiteral);
            //AddWithSeparator(buttonMarkupLiteral);
        }
Esempio n. 14
0
        public string GetXml()
        {
            StringBuilder result = new StringBuilder();

            result.AppendFormat("<ChatMessage ID='{0}'>", this.ID);
            result.AppendFormat("<{0}>{1}</{0}>", "Title", SPHttpUtility.HtmlEncode(this.Title));
            result.AppendFormat("<{0}>{1}</{0}>", "Message", SPHttpUtility.HtmlEncode(this.Message));

            result.Append("<Receivers>");
            foreach (Contact receiver in this.Receivers)
            {
                result.AppendFormat("<{0} ID='{2}'>{1}</{0}>", "Receiver", SPHttpUtility.HtmlEncode(receiver.Name), receiver.ID);
            }
            result.Append("</Receivers>");

            result.AppendFormat("<{0}>{1}</{0}>", "Created", this.Created);
            result.AppendFormat("<{0} ID='{2}'>{1}</{0}>", "CreatedBy", SPHttpUtility.HtmlEncode(this.CreatedBy.Name), this.CreatedBy.ID);
            result.AppendFormat("<{0}>{1}</{0}>", "IsRead", this.IsRead);
            result.Append("</ChatMessage>");
            return(result.ToString());
        }
        protected override void CreateChildControls()
        {
            if (String.IsNullOrEmpty(ChartTitle) || String.IsNullOrEmpty(LibraryTitle))
            {
                this.Controls.Add(new LiteralControl(
                                      "Configuration Error: Chart Title or Library Title has not been set."));
            }
            else
            {
                try
                {
                    SPSite site      = SPContext.Current.Site;
                    SPList mpGallery = site.RootWeb.GetCatalog(SPListTemplateType.MasterPageCatalog);
                    string xapUrl    = SPUrlUtility.CombineUrl(mpGallery.RootFolder.ServerRelativeUrl, "Chapter11.Silverlight.xap");

                    string markup = String.Format(
                        @"<div id=""silverlightControlHost"">
                            <object data=""data:application/x-silverlight-2,"" type=""application/x-silverlight-2"" width=""100%"" height=""100%"">
                                <param name=""source"" value=""{0}""/>
                                <param name=""minRuntimeVersion"" value=""5.0.61118.0"" />
                                <param name=""initParams"" value=""MS.SP.url={1},ChartTitle={2},LibraryTitle={3}"" />
                                <param name=""autoUpgrade"" value=""true"" />
                                <a href=""http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0"" style=""text-decoration:none"">
                                    <img src=""http://go.microsoft.com/fwlink/?LinkId=161376"" alt=""Get Microsoft Silverlight"" style=""border-style:none""/>
                                </a>
                            </object><iframe id=""_sl_historyFrame"" style=""visibility:hidden;height:0px;width:0px;border:0px""></iframe>
                        </div>",
                        xapUrl,
                        SPHttpUtility.HtmlEncode(SPContext.Current.Web.Url),
                        this.ChartTitle,
                        this.LibraryTitle);

                    this.Controls.Add(new LiteralControl(markup));
                }
                catch (Exception ex)
                {
                    this.Controls.Add(new LiteralControl("Error: " + ex.Message));
                }
            }
        }
Esempio n. 16
0
        public static string GetFieldValueAsTextOrHtml(this SPFieldCalculated calcField, object value, bool asHtml)
        {
            if (value == null)
            {
                return(string.Empty);
            }


            string strType = string.Empty;
            string str2    = string.Empty;
            string str3    = value as string;

            if (str3 == null)
            {
                throw new ArgumentOutOfRangeException();
            }
            str2 = str3;
            int length = StsBinaryCompareIndexOf(str2, ";#");

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            strType = str2.Substring(0, length).ToUpper(CultureInfo.InvariantCulture);
            str2    = str2.Substring(length + ";#".Length);
            if (((calcField.OutputType == SPFieldType.Invalid) || (calcField.OutputType == SPFieldType.Error)) || (strType == "ERROR"))
            {
                string formattedErrorValue = GetFormattedErrorValue(strType, str2);
                if (asHtml)
                {
                    return(SPHttpUtility.HtmlEncode(formattedErrorValue));
                }
                return(formattedErrorValue);
            }
            try
            {
                bool flag = false;;
                switch (strType)
                {
                case "FLOAT":
                {
                    //double data = Convert.ToDouble(str2, CultureInfo.InvariantCulture);
                    //CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
                    //if (calcField.OutputType == SPFieldType.Currency)
                    //{
                    //    string valueToEncode = FormatValue(data, calcField.Currency..DisplayFormat);
                    //    if (asHtml)
                    //    {
                    //        valueToEncode = SPHttpUtility.HtmlEncode(valueToEncode);
                    //    }
                    //    return valueToEncode;
                    //}
                    //if (asHtml)
                    //{
                    //    return SPFieldNumber.GetFieldValueAsHtml(data, currentCulture, calcField.ShowAsPercentage, calcField.DisplayFormat);
                    //}
                    //return SPFieldNumber.GetFieldValueAsText(data, currentCulture, calcField.ShowAsPercentage, calcField.DisplayFormat);
                }
                break;

                case "DATETIME":
                {
                    //SPDateFormat dateTime;
                    //if (base.IsXLVWPConnection)
                    //{
                    //    return str2;
                    //}
                    //DateTime time = SPUtility.CreateSystemDateTimeFromXmlDataDateTimeFormat(str2);
                    //if (this.DateFormat == SPDateTimeFieldFormatType.DateTime)
                    //{
                    //    dateTime = SPDateFormat.DateTime;
                    //}
                    //else
                    //{
                    //    dateTime = SPDateFormat.DateOnly;
                    //}
                    //if (asHtml)
                    //{
                    //    return SPFieldDateTime.GetFieldValueAsHtml(time, base.Fields.Web, dateTime);
                    //}
                    //return SPFieldDateTime.GetFieldValueAsText(time, base.Fields.Web, dateTime);
                }
                break;

                default:
                    if (!(strType == "BOOLEAN"))
                    {
                        goto Label_01FA;
                    }
                    switch (str2)
                    {
                    case "TRUE":
                    case "-1":
                    case "1":
                        flag = true;
                        break;
                    }
                    flag = false;
                    break;
                }
                //if (asHtml)
                //{
                //    return SPFieldBoolean.GetFieldValueAsHtml(flag);
                //}
                return(SPFieldBoolean.GetFieldValueAsText(flag));

Label_01FA:
                if (asHtml)
                {
                    return(SPHttpUtility.HtmlEncode(str2));
                }
                return(str2);
            }
            catch (ArgumentOutOfRangeException)
            {
                if (asHtml)
                {
                    return(SPHttpUtility.HtmlEncode(str2));
                }
                return(str2);
            }

            //return string.Empty;
        }
Esempio n. 17
0
        protected override void CreateChildControls()
        {
            //Copied from base class
            SPWeb contextWeb = SPControl.GetContextWeb(this.Context);

            Table child = new Table();

            child.Width = Unit.Percentage(100.0);
            child.Attributes.Add("cellspacing", "0");
            child.Attributes.Add("cellpadding", "0");
            TableRow row = new TableRow();

            row.Width = Unit.Percentage(100.0);
            Label     label = new Label();
            TableCell cell  = new TableCell();

            cell.CssClass = "ms-descriptiontext";
            cell.Attributes.Add("style", "white-space:nowrap");
            string str = SPHttpUtility.HtmlEncode(SPResource.GetString("PickerDialogDefaultSearchLabel", new object[0]));

            str        = string.Format(CultureInfo.InvariantCulture, "<b>{0}</b>&nbsp;", new object[] { str });
            label.Text = str;
            cell.Controls.Add(label);
            this.ColumnList          = new DropDownList();
            this.ColumnList.ID       = "columnList";
            this.ColumnList.CssClass = "ms-pickerdropdown";
            cell.Controls.Add(this.ColumnList);
            row.Cells.Add(cell);

            //Punches-in the search operators dropdown
            cell = new TableCell();
            drpdSearchOperators    = new HtmlSelect();
            drpdSearchOperators.ID = "queryOperators";
            drpdSearchOperators.Attributes.Add("class", "ms-pickerdropdown");

            cell.Controls.Add(drpdSearchOperators);
            row.Cells.Add(cell);

            cell                        = new TableCell();
            cell.Width                  = Unit.Percentage(100.0);
            this.QueryTextBox           = new InputFormTextBox();
            this.QueryTextBox.ID        = "queryTextBox";
            this.QueryTextBox.CssClass  = "ms-pickersearchbox";
            this.QueryTextBox.AccessKey = SPResource.GetString("PickerDialogSearchAccessKey", new object[0]);
            this.QueryTextBox.Width     = Unit.Percentage(100.0);
            this.QueryTextBox.MaxLength = 0x3e8;
            this.QueryTextBox.Text      = QueryText;
            cell.Controls.Add(this.QueryTextBox);
            row.Cells.Add(cell);
            label.AssociatedControlID = "queryTextBox";
            cell                           = new TableCell();
            this.QueryButton               = new ImageButton();
            this.QueryButton.ID            = "queryButton";
            this.QueryButton.OnClientClick = "executeQuery();return false;";
            this.QueryButton.ToolTip       = SPResource.GetString("PickerDialogSearchToolTip", new object[0]);
            this.QueryButton.AlternateText = SPResource.GetString("PickerDialogSearchToolTip", new object[0]);
            if (!contextWeb.RegionalSettings.IsRightToLeft)
            {
                this.QueryButton.ImageUrl = "/_layouts/images/gosearch.gif";
            }
            else
            {
                this.QueryButton.ImageUrl = "/_layouts/images/gortl.gif";
            }
            HtmlGenericControl control = new HtmlGenericControl("div");

            control.Attributes.Add("class", "ms-searchimage");
            control.Controls.Add(this.QueryButton);
            cell.Controls.Add(control);
            row.Cells.Add(cell);
            child.Rows.Add(row);
            this.Controls.Add(child);

            //fills the search fields initially
            if (!Page.IsPostBack)
            {
                SPWeb  web  = SPContext.Current.Site.OpenWeb(propertyBag.WebId);
                SPList list = web.Lists[propertyBag.ListId];

                foreach (SPField field in list.Fields)
                {
                    List <string> searchFields = propertyBag.SearchFields;

                    if (searchFields.Contains(field.Id.ToString()))
                    {
                        mColumnList.Items.Add(new ListItem(field.Title, field.Id.ToString()));
                    }
                }

                //fills the search operators initally
                FillSearchOperators(ColumnList.SelectedValue);
            }
        }
Esempio n. 18
0
        protected override void CreateChildControls()
        {
            if (IsFieldValueCached)
            {
                base.CreateChildControls();
            }
            else if (Field != null)
            {
                base.CreateChildControls();
                if (ControlMode != SPControlMode.Display)
                {
                    var field = (SPFieldLookup)Field;
                    if (!field.AllowMultipleValues)
                    {
                        Controls.Clear();
                        if (Throttled)
                        {
                            var maxItemsPerThrottledOperation = Web.Site.WebApplication.MaxItemsPerThrottledOperation;
                            var str =
                                SPResource.GetString(
                                    Field.Required ? "RequiredLookupThrottleMessage" : "LookupThrottleMessage",
                                    new object[]
                            {
                                maxItemsPerThrottledOperation.ToString(
                                    CultureInfo.InvariantCulture)
                            });
                            var child = new Literal {
                                Text = SPHttpUtility.HtmlEncode(str)
                            };
                            var literal2 = new Literal {
                                Text = @"<span style=""vertical-align:middle"">"
                            };
                            var literal3 = new Literal {
                                Text = @"</span>"
                            };
                            Controls.Add(literal2);
                            Controls.Add(child);
                            Controls.Add(literal3);
                        }
                        else
                        {
                            if (AutoPostBack || ((DataSource == null) || (DataSource.Count <= 20)) ||
                                ((InDesign || !IsIE55Up(Page.Request)) || IsAccessibilityMode(Page.Request)))
                            {
                                dropList = new DropDownList
                                {
                                    ID             = "Lookup",
                                    TabIndex       = TabIndex,
                                    DataSource     = DataSource,
                                    DataValueField = "ValueField",
                                    DataTextField  = "TextField",
                                    ToolTip        = SPHttpUtility.NoEncode(field.Title),
                                };

                                if (AutoPostBack)
                                {
                                    dropList.AutoPostBack          = true;
                                    dropList.SelectedIndexChanged += OnSelectedIndexChanged;
                                }

                                dropList.DataBind();
                                Controls.Add(dropList);
                            }
                            else
                            {
                                textBox = new TextBox();
                                textBox.Attributes.Add("choices", Choices);
                                textBox.Attributes.Add("match", "");
                                textBox.Attributes.Add("onkeydown", "CoreInvoke('HandleKey')");
                                textBox.Attributes.Add("onkeypress", "CoreInvoke('HandleChar')");
                                textBox.Attributes.Add("onfocusout", "CoreInvoke('HandleLoseFocus')");
                                textBox.Attributes.Add("onchange", "CoreInvoke('HandleChange')");
                                textBox.Attributes.Add("class", "ms-lookuptypeintextbox");
                                textBox.Attributes.Add("title", SPHttpUtility.HtmlEncode(field.Title));
                                textBox.TabIndex             = TabIndex;
                                textBox.Attributes["optHid"] = HiddenFieldName;
                                var literal4 = new Literal {
                                    Text = @"<span style=""vertical-align:middle"">"
                                };
                                var literal5 = new Literal {
                                    Text = @"</span>"
                                };
                                Controls.Add(literal4);
                                Controls.Add(textBox);
                                textBox.Attributes.Add("opt", "_Select");
                                dropImage = new Image {
                                    ImageUrl = "/_layouts/images/dropdown.gif"
                                };
                                dropImage.Attributes.Add("alt",
                                                         SPResource.GetString("LookupWordWheelDropdownAlt",
                                                                              new object[0]));
                                dropImage.Attributes.Add("style", "vertical-align:middle;");
                                Controls.Add(dropImage);
                                Controls.Add(literal5);
                            }
                            if (webForeign != null)
                            {
                                webForeign.Close();
                                webForeign = null;
                            }
                            Controls.Add(new LiteralControl("<br/>"));
                            SetFieldControlValue(ItemFieldValue);
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SPContext spContext = SPContext.Current;

            _spWeb = spContext.Web;

            SiteId     = _spWeb.Site.ID.ToString();
            SiteUrl    = _spWeb.Site.Url;
            WebFullUrl = _spWeb.Url;
            WebId      = _spWeb.ID.ToString();
            WebUrl     = _spWeb.SafeServerRelativeUrl();
            RootWebId  = spContext.Site.RootWeb.ID.ToString().ToLower();

            ListTitle = string.Empty;
            try
            {
                if (spContext.List != null)
                {
                    ListTitle = HttpUtility.JavaScriptStringEncode(spContext.List.Title);
                }
            }
            catch { }

            ListId = Guid.Empty.ToString();
            try
            {
                if (spContext.List != null)
                {
                    ListId = spContext.ListId.ToString();
                }
            }
            catch { }

            ListViewUrl = string.Empty;
            try
            {
                if (spContext.ViewContext != null && spContext.ViewContext.View != null)
                {
                    ListViewUrl = spContext.ViewContext.View.Url;
                }
            }
            catch { }

            ListViewTitle = string.Empty;
            try
            {
                if (spContext.ViewContext != null && spContext.ViewContext.View != null)
                {
                    ListViewTitle = HttpUtility.JavaScriptStringEncode(spContext.ViewContext.View.Title);
                }
            }
            catch { }

            ItemId = "-1";
            try
            {
                ItemId = (spContext.Item != null) ? spContext.ItemId.ToString(CultureInfo.InvariantCulture) : "-1";
            }
            catch { }

            ItemTitle = string.Empty;
            try
            {
                ItemTitle = (spContext.Item != null)
                    ? HttpUtility.JavaScriptStringEncode(spContext.ListItemDisplayName)
                    : string.Empty;
            }
            catch { }

            CurrentFileIsNull = "True";
            try
            {
                CurrentFileIsNull = (spContext.File == null).ToString();
            }
            catch { }

            CurrentFileTitle = string.Empty;
            try
            {
                CurrentFileTitle = Path.GetFileName(Request.FilePath);
                if (!string.IsNullOrEmpty(CurrentFileTitle))
                {
                    CurrentFileTitle = CurrentFileTitle.Replace(".aspx", "");
                }
            }
            catch { }

            ListIconClass = string.Empty;
            try
            {
                if (spContext.List != null)
                {
                    string sIcon = new GridGanttSettings(SPContext.Current.List).ListIcon;
                    ListIconClass = !string.IsNullOrEmpty(sIcon) ? sIcon : "icon-square";
                }
            }
            catch { }

            CurrentUserId = "-1";
            try
            {
                CurrentUserId = _spWeb.CurrentUser.ID.ToString(CultureInfo.InvariantCulture);
            }
            catch { }

            CurrentUserLoginName = string.Empty;
            try
            {
                CurrentUserLoginName = SPHttpUtility.HtmlEncode(_spWeb.CurrentUser.LoginName);
            }
            catch { }

            CurrentUserName = string.Empty;
            try
            {
                CurrentUserName = CoreFunctions.GetSafeUserTitle(_spWeb.CurrentUser.Name);
            }
            catch { }

            CurrentUrl = string.Empty;
            try
            {
                CurrentUrl = new Uri(new Uri(_spWeb.Url), HttpContext.Current.Request.RawUrl).AbsoluteUri;
            }
            catch { }
        }
        protected override void CreateChildControls()
        {
            dataTable = new DataTable();

            Table htmlTable = new Table();

            htmlTable.Width = Unit.Percentage(100.0);
            htmlTable.Attributes.Add("cellspacing", "0");
            htmlTable.Attributes.Add("cellpadding", "0");
            TableRow row = new TableRow();

            row.Width = Unit.Percentage(100.0);
            Label     label = new Label();
            TableCell cell  = new TableCell();

            cell.CssClass = "ms-descriptiontext";
            cell.Attributes.Add("style", "white-space:nowrap");
            string str = SPHttpUtility.HtmlEncode(SPResource.GetString("PickerDialogDefaultSearchLabel", new object[0]));

            str        = string.Format(CultureInfo.InvariantCulture, "<b>{0}</b>&nbsp;", new object[] { str });
            label.Text = str;
            cell.Controls.Add(label);
            this.ColumnList          = new DropDownList();
            this.ColumnList.ID       = "columnList";
            this.ColumnList.CssClass = "ms-pickerdropdown";
            cell.Controls.Add(this.ColumnList);
            row.Cells.Add(cell);

            //Punches-in the search operator dropdown
            cell = new TableCell();
            cell.Style.Add("padding-right", "20px");
            drpdSearchOperators    = new HtmlSelect();
            drpdSearchOperators.ID = "queryOperators";
            drpdSearchOperators.Attributes.Add("class", "ms-pickerdropdown");

            cell.Controls.Add(drpdSearchOperators);
            row.Cells.Add(cell);

            cell                        = new TableCell();
            cell.Width                  = Unit.Percentage(100.0);
            this.QueryTextBox           = new InputFormTextBox();
            this.QueryTextBox.ID        = "queryTextBox";
            this.QueryTextBox.CssClass  = "ms-pickersearchbox";
            this.QueryTextBox.AccessKey = SPResource.GetString("PickerDialogSearchAccessKey", new object[0]);
            this.QueryTextBox.Width     = Unit.Percentage(100.0);
            this.QueryTextBox.MaxLength = 0x3e8;
            this.QueryTextBox.Text      = QueryText;
            cell.Controls.Add(this.QueryTextBox);
            row.Cells.Add(cell);
            label.AssociatedControlID = "queryTextBox";
            cell                           = new TableCell();
            this.QueryButton               = new ImageButton();
            this.QueryButton.ID            = "queryButton";
            this.QueryButton.OnClientClick = "executeQuery();return false;";
            this.QueryButton.ToolTip       = SPResource.GetString("PickerDialogSearchToolTip", new object[0]);
            this.QueryButton.AlternateText = SPResource.GetString("PickerDialogSearchToolTip", new object[0]);
            if (!Web.RegionalSettings.IsRightToLeft)
            {
                this.QueryButton.ImageUrl = "/_layouts/images/gosearch.gif";
            }
            else
            {
                this.QueryButton.ImageUrl = "/_layouts/images/gortl.gif";
            }
            HtmlGenericControl control = new HtmlGenericControl("div");

            control.Attributes.Add("class", "ms-searchimage");
            control.Controls.Add(this.QueryButton);
            cell.Controls.Add(control);
            row.Cells.Add(cell);
            htmlTable.Rows.Add(row);
            this.Controls.Add(htmlTable);

            SPList list = Web.Lists[propertyBag.LookupListID];

            //fills the search fields initially
            foreach (SPField field in list.Fields)
            {
                if (!field.Hidden && field.Reorderable)
                {
                    // add table columns
                    if (!Page.IsPostBack)
                    {
                        mColumnList.Items.Add(new ListItem(field.Title, field.Id.ToString()));
                    }

                    DataColumn col = dataTable.Columns.Add();
                    col.ColumnName = field.Id.ToString();
                    col.Caption    = field.Title;
                    col.ExtendedProperties.Add("InternalName", field.InternalName);
                }
            }

            if (!dataTable.Columns.Contains(SPBuiltInFieldId.ID.ToString()))
            {
                SPField idField = list.Fields[SPBuiltInFieldId.ID];

                DataColumn col = dataTable.Columns.Add();
                col.ColumnName = idField.Id.ToString();
                col.Caption    = idField.Title;
                col.ExtendedProperties.Add("InternalName", idField.InternalName);
            }

            if (mColumnList.Items.Count == 0)
            {
                SPField field = List.Fields[PropertyBag.LookupFieldInternalName];
                mColumnList.Items.Add(new ListItem(field.Title, field.Id.ToString()));
            }

            // reorder items
            // Make Title the first field
            // then order the rest alphabetically
            string   s  = list.Fields.GetFieldByInternalName(propertyBag.LookupFieldInternalName).Id.ToString();
            ListItem li = mColumnList.Items.Cast <ListItem>().Where(i => i.Value == s).FirstOrDefault();

            ListItem[] liArray = mColumnList.Items.Cast <ListItem>().Where(i => i.Value != s).OrderBy(i => i.Text).ToArray <ListItem>();
            mColumnList.Items.Clear();
            mColumnList.Items.Add(li);
            mColumnList.Items.AddRange(liArray);

            //fills the search operators initally
            FillSearchOperators(ColumnList.SelectedValue);
        }
        // Protected Methods (1) 

        /// <summary>
        ///     Sends the tool part content to the specified HtmlTextWriter object, which writes the content to be rendered on the client.
        /// </summary>
        /// <param name="output">The HtmlTextWriter object that receives the tool part content.</param>
        protected override void RenderToolPart(HtmlTextWriter output)
        {
            var myWorkWebPart = (MyWorkWebPart)ParentToolPane.SelectedWebPart;

            string myWorkWebPartHtmlCode = Resources.MyWorkToolPart.Replace("_ID__", UniqueID.Md5());

            #region Get Settings

            string selectedLists = string.Empty;

            if (myWorkWebPart.SelectedLists != null)
            {
                IOrderedEnumerable <string> selLists = (myWorkWebPart.SelectedLists.Where(
                                                            selectedList => !string.IsNullOrEmpty(selectedList))
                                                        .Select(
                                                            selectedList =>
                                                            string.Format(@"'{0}'", selectedList))).ToList()
                                                       .OrderBy(
                    l =>
                    l);

                selectedLists = string.Join(",", selLists.ToArray());
            }

            string selectedFields = string.Empty;

            if (myWorkWebPart.SelectedFields != null)
            {
                IOrderedEnumerable <string> selFields = (myWorkWebPart.SelectedFields.Where(
                                                             selectedField => !string.IsNullOrEmpty(selectedField))
                                                         .Select(
                                                             selectedField =>
                                                             string.Format(
                                                                 @"{{InternalName:'{0}',PrettyName:'{1}'}}",
                                                                 selectedField,
                                                                 selectedField.ToPrettierName()))).ToList().
                                                        OrderBy(
                    f =>
                    f);

                selectedFields = string.Join(",", selFields.ToArray());
            }

            List <myworksettings.MWList> myWorkLists = myworksettings.GetMyWorkListsFromDb(_web,
                                                                                           MyWork.GetArchivedWebs(
                                                                                               _web.Site.ID));

            var includedMWLists = new List <string>();
            List <myworksettings.MWList> excludedMWLists = myWorkLists.ToList();

            if (myWorkWebPart.MyWorkSelectedLists.Count() > 0)
            {
                foreach (
                    myworksettings.MWList myWorkList in
                    myWorkLists.Where(myWorkList => myWorkWebPart.MyWorkSelectedLists.Contains(myWorkList.Name)))
                {
                    includedMWLists.Add(string.Format(@"{{Id:'{0}',Name:'{1}'}}", myWorkList.Id, myWorkList.Name));
                    excludedMWLists.Remove(myWorkList);
                }
            }
            else
            {
                includedMWLists = excludedMWLists.Select(excludedMWList => string.Format(@"{{Id:'{0}',Name:'{1}'}}",
                                                                                         excludedMWList.Id,
                                                                                         excludedMWList.Name)).ToList();

                excludedMWLists = new List <myworksettings.MWList>();
            }

            string includedMyWorkLists = string.Join(",", includedMWLists.ToArray());

            IEnumerable <string> excludedLists =
                excludedMWLists.Select(
                    excludedMWList =>
                    string.Format(@"{{Id:'{0}',Name:'{1}'}}", excludedMWList.Id,
                                  SPHttpUtility.HtmlEncode(excludedMWList.Name)));
            string excludedMyWorkLists = string.Join(",", excludedLists.ToArray());

            string crossSiteUrls = string.Empty;

            if (myWorkWebPart.CrossSiteUrls != null)
            {
                IOrderedEnumerable <string> crossSites = myWorkWebPart.CrossSiteUrls.Where(
                    crossSiteUrl => !string.IsNullOrEmpty(crossSiteUrl))
                                                         .Select(
                    crossSiteUrl =>
                    string.Format(@"'{0}'", crossSiteUrl))
                                                         .OrderBy(s => s);
                crossSiteUrls = string.Join(",", crossSites.ToArray());
            }

            var defaultGlobalViews = new List <string>();

            bool defaultViewFound = false;

            List <MyWorkGridView> myWorkGridViews =
                MyWork.GetGlobalViews(Utils.GetConfigWeb()).OrderBy(v => v.Name).ToList();

            foreach (MyWorkGridView myWorkGridView in myWorkGridViews)
            {
                bool defaultView = myWorkWebPart.DefaultGlobalView.Equals(myWorkGridView.Id);
                if (defaultView)
                {
                    defaultViewFound = true;
                }

                defaultGlobalViews.Add(string.Format(@"{{Id:'{0}',Name:'{1}',Default:{2}}}", myWorkGridView.Id,
                                                     myWorkGridView.Name, defaultView.Lc()));
            }

            defaultGlobalViews.Insert(0,
                                      string.Format(@"{{Id:'',Name:'Do Not Set View',Default:{0}}}",
                                                    (!defaultViewFound).Lc()));

            string objDefaultGlobalViews = string.Join(",", defaultGlobalViews.ToArray());

            bool agoFilterEnabled   = false;
            int  agoFilterDays      = 0;
            bool afterFilterEnabled = false;
            int  afterFilterDays    = 0;

            bool indicatorActive = true;
            int  indicatorDays   = 2;

            if (!string.IsNullOrEmpty(myWorkWebPart.DueDayFilter))
            {
                string[] filters = myWorkWebPart.DueDayFilter.Split('|');

                bool.TryParse(filters[0], out agoFilterEnabled);
                int.TryParse(filters[1], out agoFilterDays);
                bool.TryParse(filters[2], out afterFilterEnabled);
                int.TryParse(filters[3], out afterFilterDays);
            }

            if (!string.IsNullOrEmpty(myWorkWebPart.NewItemIndicator))
            {
                string[] settings = myWorkWebPart.NewItemIndicator.Split('|');

                bool.TryParse(settings[0], out indicatorActive);
                int.TryParse(settings[1], out indicatorDays);
            }

            string myWorkObjString =
                string.Format(
                    @"useCentralizedSettings:{0}, selectedLists:[{1}], selectedFields:[{2}], crossSiteUrls:[{3}], performanceMode:{4}, hideNewButton:{5}, allowEditToggle:{6}, defaultToEditMode:{7}, defaultGlobalViews:[{8}], includedMyWorkLists:[{9}], excludedMyWorkLists:[{10}], daysAgoEnabled:{11}, daysAfterEnabled:{12}, newItemIndicatorEnabled:{13}, daysAgo:'{14}', daysAfter:'{15}', newItemIndicator:'{16}', showToolbar:{17}",
                    myWorkWebPart.UseCentralizedSettings.Lc(), selectedLists, selectedFields, crossSiteUrls,
                    myWorkWebPart.PerformanceMode.Lc(), myWorkWebPart.HideNewButton.Lc(),
                    myWorkWebPart.AllowEditToggle.Lc(), myWorkWebPart.DefaultToEditMode.Lc(), objDefaultGlobalViews,
                    includedMyWorkLists, excludedMyWorkLists, agoFilterEnabled.Lc(),
                    afterFilterEnabled.Lc(), indicatorActive.Lc(),
                    agoFilterDays, afterFilterDays, indicatorDays, myWorkWebPart.ShowToolbar.Lc());

            myWorkWebPartHtmlCode = myWorkWebPartHtmlCode.Replace("objMyWork__VAL__", myWorkObjString);

            #endregion

            #region Get All Lists and Fields

            var listsAndFields = new Dictionary <string, List <string> >();
            foreach (SPList list in _web.Lists)
            {
                try
                {
                    listsAndFields.Add(list.Title,
                                       (list.Fields.Cast <SPField>()
                                        .Where(spField => !spField.Hidden && spField.Reorderable)
                                        .Select(spField => spField.InternalName)).ToList());
                }
                catch { }
            }

            string allListsAndFieldsString =
                string.Format(@"{0}",
                              string.Join(",", listsAndFields.Select(listAndFields =>
                                                                     string.Format(@"{{List:'{0}',Fields:[{1}]}}",
                                                                                   listAndFields.Key,
                                                                                   string.Join(",",
                                                                                               listAndFields.Value.
                                                                                               Select(
                                                                                                   field
                                                                                                   =>
                                                                                                   string
                                                                                                   .Format
                                                                                                   (
                                                                                                       @"{{InternalName:'{0}',PrettyName:'{1}'}}",
                                                                                                       field,
                                                                                                       field
                                                                                                       .
                                                                                                       ToPrettierName
                                                                                                           ()))
                                                                                               .
                                                                                               ToArray())))
                                          .ToArray()));

            myWorkWebPartHtmlCode = myWorkWebPartHtmlCode.Replace("allListsAndFields__VAL__", allListsAndFieldsString);

            #endregion

            #region Get Field Lists

            var fieldLists = new Dictionary <string, List <string> >();

            foreach (var listAndFields in listsAndFields)
            {
                foreach (string field in listAndFields.Value)
                {
                    if (!fieldLists.ContainsKey(field))
                    {
                        fieldLists.Add(field, new List <string>());
                    }
                    fieldLists[field].Add(listAndFields.Key);
                }
            }

            List <string> fields = fieldLists.Select(fieldList => string.Format(@"{0}:[{1}]", fieldList.Key,
                                                                                string.Join(",",
                                                                                            fieldList.Value.Select(
                                                                                                list =>
                                                                                                string.Format(@"'{0}'",
                                                                                                              list)).
                                                                                            ToArray())))
                                   .ToList();

            string fieldListsString = string.Join(",", fields.ToArray());

            myWorkWebPartHtmlCode = myWorkWebPartHtmlCode.Replace("fieldLists__VAL__", fieldListsString);

            string listWebsString = string.Join(",", (from myWorkList in myWorkLists
                                                      let webs =
                                                          myWorkList.Webs.Select(web => string.Format(@"'{0}'", web))
                                                          select
                                                          string.Format(@"{0}:[{1}]", myWorkList.Id,
                                                                        string.Join(",", webs.ToArray()))).ToArray());

            myWorkWebPartHtmlCode = myWorkWebPartHtmlCode.Replace("listWebs__VAL__", listWebsString);

            #endregion

            output.Write(myWorkWebPartHtmlCode);
        }
Esempio n. 22
0
        private void ManageFields()
        {
            SPWeb  currentWeb  = SPContext.Current.Web;
            SPSite currentSite = SPContext.Current.Site;

            if (!string.IsNullOrEmpty(Request.Params["listId"]))
            {
                _listId         = Request.Params["listId"];
                hdnListId.Value = _listId;
            }

            if (!string.IsNullOrEmpty(Request.Params["itemid"]))
            {
                _itemId                = Request.Params["itemid"];
                hdnItemId.Value        = _itemId.ToString();
                hdnCommentItemId.Value = _itemId.ToString();
            }

            if (!string.IsNullOrEmpty(Request.Params["listId"]))
            {
                SPList     list = currentWeb.Lists[new Guid(_listId)];
                SPListItem item = list.GetItemById(int.Parse(_itemId));
                _listTitle = SPHttpUtility.HtmlEncode(list.Title);
                _itemTitle = (item[item.Fields.GetFieldByInternalName("Title").Id] != null) ? SPHttpUtility.HtmlEncode(item[item.Fields.GetFieldByInternalName("Title").Id].ToString()) : string.Empty;
            }

            if (!string.IsNullOrEmpty(_listId) && !string.IsNullOrEmpty(_itemId))
            {
                SPList     list = currentWeb.Lists[new Guid(_listId)];
                SPListItem item = list.GetItemById(int.Parse(_itemId));
                _authorId    = GetItemAuthorId(item);
                _assigneeIds = GetItemAssigneeIds(item);
            }

            hdnUserId.Value = Web.CurrentUser.ID.ToString();
            string currentWebUrl = SPContext.Current.Web.Url;

            _webUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/EPMLive/CommentsProxy.aspx?";
            _currentUserLoginName = SPHttpUtility.HtmlEncode(Web.CurrentUser.Name);
            //_userProfileUrl = currentWebUrl + "/my/person.aspx?accountname=" + Web.CurrentUser.Name;
            _userProfileUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/userdisp.aspx?Force=True&ID=" + Web.CurrentUser.ID + "&source=" + HttpContext.Current.Request.UrlReferrer;
            // user picture url
            SPList     userInfoList = Web.SiteUserInfoList;
            SPListItem userItem     = userInfoList.GetItemById(Web.CurrentUser.ID);

            _userEmail      = !string.IsNullOrEmpty(Web.CurrentUser.Email) ? Web.CurrentUser.Email : string.Empty;
            _userPictureUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png";

            SPField fldPicture = null;

            try
            {
                fldPicture = userItem.Fields.GetFieldByInternalName("Picture");
            }
            catch (ArgumentException x)
            {
                fldPicture = null;
            }

            if (fldPicture != null)
            {
                try
                {
                    string[] picUrls = userItem[userItem.Fields.GetFieldByInternalName("Picture").Id].ToString().Split(',');
                    _userPictureUrl = picUrls[0];
                }
                catch
                {
                    _userPictureUrl = currentSite.MakeFullUrl(currentWeb.ServerRelativeUrl) + "/_layouts/epmlive/images/O14_person_placeHolder_32.png";
                }
            }
        }
        private void CreateTable()
        {
            resultTable = new Table
            {
                Width       = Unit.Percentage(100.0),
                ID          = "resultTable",
                CssClass    = "ms-pickerresulttable",
                CellSpacing = 0,
                CellPadding = 0,
                BackColor   = Color.White
            };
            resultTable.ID = "resultTable";
            resultTable.Attributes.Add("hideFocus", "true");
            resultTable.Attributes.Add("EditorControlClientId", PickerDialog.EditorControl.ClientID);

            //Create Table Header Row
            TableRow child = null;

            if (PickerDialog.Results != null)
            {
                dt = PickerDialog.Results;


                child = new TableRow
                {
                    CssClass = "ms-pickerresultheadertr"
                };

                foreach (string column in columns)
                {
                    TableHeaderCell cell = new TableHeaderCell
                    {
                        CssClass = "ms-ph"
                    };
                    cell.Attributes.Add("UNSELECTABLE", "on");
                    Literal literal = new Literal
                    {
                        Text = SPHttpUtility.HtmlEncode(column)
                    };

                    cell.Controls.Add(literal);
                    child.Controls.Add(cell);
                }

                resultTable.Controls.Add(child);


                if (dt.Rows.Count == 0)
                {
                    child = new TableRow
                    {
                        CssClass = "ms-pickeremptyresulttexttr"
                    };

                    TableCell cell2 = new TableCell
                    {
                        CssClass   = "ms-descriptiontext",
                        ColumnSpan = columns.Length
                    };
                    Literal literal2 = new Literal
                    {
                        Text = SPHttpUtility.HtmlEncode("No search was given")
                    };
                    cell2.Controls.Add(literal2);
                    child.Controls.Add(cell2);
                    resultTable.Controls.Add(child);
                }
                else
                {
                    int    num          = 0;
                    string selectSingle = "PickerResultsSingleSelectOnClick(this);";
                    string selectDouble = "PickerResultsSingleSelectOnDblClick(this);";

                    foreach (HTML5VideoDataSet.HTML5VideosRow row in dt.Rows)
                    {
                        HTML5VideoPickerEntity entity = PickerDialog.QueryControl.GetEntity(row);

                        if (entity != null)
                        {
                            child = new TableRow
                            {
                                ID = string.Format(CultureInfo.InvariantCulture, "row{0}", new object[] { num })
                            };

                            child.Attributes.Add("tabindex", "-1");
                            child.Attributes.Add("resultRow", "resultRow");

                            if ((num % 2) == 0)
                            {
                                child.CssClass = "ms-alternating";
                            }

                            ArrayList entities = new ArrayList();

                            entities.Add(entity);

                            string callback = PickerDialog.EditorControl.GenerateCallbackData(entities, false);
                            child.Attributes.Add("entityXml", callback);
                            child.Attributes.Add("onmousedown", "return singleselectevent(event);");
                            child.Attributes.Add("onclick", selectSingle);
                            child.Attributes.Add("ondblclick", selectDouble);
                            child.Attributes.Add("onkeydown", "PickerResultsNameOnKeyDown(this, event,false);");
                            child.Attributes.Add("onfocus", "PickerResultsNameOnFocus(this, event, false);");

                            child.Attributes.Add("key", entity.Key);

                            for (int i = 0; i < columns.Length; i++)
                            {
                                this.RenderRowColumn(row, i, child);
                            }
                            resultTable.Controls.Add(child);
                            num++;
                        }
                    }

                    if (base.PickerDialog.Results.Rows.Count > 1)
                    {
                        child = new TableRow
                        {
                            CssClass = "ms-pickersearchsummarytr",
                            ID       = "PickerSearchResultSummaryRow"
                        };
                        TableCell cell3 = new TableCell
                        {
                            CssClass   = "ms-descriptiontext",
                            ColumnSpan = dt.Columns.Count
                        };
                        cell3.Controls.Add(new LiteralControl(SPHttpUtility.HtmlEncode(String.Format("{0} results found.", new object[] { base.PickerDialog.Results.Rows.Count }))));
                        child.Controls.Add(cell3);
                        resultTable.Controls.Add(child);
                    }

                    this.Page.ClientScript.RegisterClientScriptBlock(GetType(), "__SELECTION__HELPER__", "<script type=\"text/javascript\">\r\n                // <![CDATA[\r\n                function " + SPHttpUtility.EcmaScriptStringLiteralEncode(PickerDialog.GetSelectedClientSideFunctionName) + "()\r\n                {\r\n                    var selKeys=new Array(selected.length);\r\n                    for(i=0;i<selected.length;i++)\r\n                    {\r\n                        var uniquekey=selected[i].getAttribute('key').toString();\r\n                        selKeys[i]=uniquekey;\r\n                    }\r\n                    return selKeys;\r\n                }\r\n                // ]]>\r\n                </script>");
                }
            }
        }
Esempio n. 24
0
        protected override void RenderWebPart(HtmlTextWriter output)
        {
            if (this.ServerInitialRender)
            {
                Type       typeWebPartPlatform     = typeof(OriginalSearchBoxScriptWebPart).Assembly.GetType("Microsoft.Office.Server.Search.WebControls.WebPartPlatform");
                object     instanceWebPartPlatform = typeWebPartPlatform.GetProperty("Current", BindingFlags.Static | BindingFlags.NonPublic).GetValue(typeWebPartPlatform);
                MethodInfo wppgetLocResourceString = typeWebPartPlatform.GetMethod("GetLocResourceString", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                Type typeLocStringIdO = typeof(OriginalSearchBoxScriptWebPart).Assembly.GetType("Microsoft.Office.Server.Search.LocStringId");
                Type typeLocStringIdP = typeof(OriginalSearchBoxScriptWebPart).Assembly.GetType("Microsoft.SharePoint.Portal.WebControls.LocStringId");

                Type       typeSearchCommon        = typeof(OriginalSearchBoxScriptWebPart).Assembly.GetType("Microsoft.SharePoint.Portal.WebControls.SearchCommon");
                MethodInfo scGetLocResourceStringO = typeSearchCommon.GetMethod("GetLocResourceString", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeLocStringIdO }, null);
                MethodInfo scGetLocResourceStringP = typeSearchCommon.GetMethod("GetLocResourceString", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeLocStringIdP }, null);

                SPWeb  web      = SPContext.Current.Web;
                bool   flag     = this.NavigationNodes != null && this.NavigationNodes.Length > 1;
                string text     = string.Empty;
                Type   kv       = typeof(OriginalScriptApplicationManager).Assembly.GetType("Microsoft.Office.Server.Search.WebControls.KeywordQueryReader");
                var    instance = kv.GetMethod("GetInstance", new Type[] { this.Page.GetType() }).Invoke(kv, new object[] { this.Page });
                if (instance != null)
                {
                    text = (string)kv.GetProperty("Keywords", BindingFlags.Public | BindingFlags.Instance).GetValue(instance, null);
                }
                string locResourceString = this.InitialPrompt;
                if (string.IsNullOrEmpty(locResourceString))
                {
                    locResourceString = (string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_KeywordTextBoxToolTip_Text") });
                }
                string text2 = "";
                if (string.IsNullOrWhiteSpace(text))
                {
                    text  = locResourceString;
                    text2 = "ms-srch-sb-prompt ms-helperText";
                }
                string text3 = base.CsrContainerId + "_sboxdiv";
                string text4 = base.CsrContainerId + "_sbox";
                string text5 = base.CsrContainerId + "_NavButton";
                string text6 = base.CsrContainerId + "_AutoCompList";
                string text7 = base.CsrContainerId + "_NavDropdownList";
                string text8 = base.CsrContainerId + "_SearchLink";
                string scriptLiteralToEncode = "ms-srch-sbprogress";
                output.Write("<div componentid=\"{0}\" id=\"{0}\"><div id=\"SearchBox\" data-ddd=\"DDD\" name=\"Control\"><div class=\"ms-srch-sb ms-srch-sb-border\" id=\"{1}\">", HttpUtility.HtmlAttributeEncode(base.CsrContainerId), HttpUtility.HtmlAttributeEncode(text3));
                output.Write("<input type=\"text\" value=\"{0}\" maxlength=\"2048\" accessKey=\"{1}\" title=\"{2}\" id=\"{3}\" autocomplete=\"off\" autocorrect=\"off\" onkeypress=\"{4}\" onkeydown=\"{5}\" onfocus=\"{6}\" onblur=\"{7}\" class=\"ms-textSmall {8}\"/>", new object[]
                {
                    HttpUtility.HtmlAttributeEncode((text != null) ? text : ""),
                    HttpUtility.HtmlAttributeEncode((string)scGetLocResourceStringP.Invoke(typeSearchCommon, new object[] { Enum.Parse(typeLocStringIdP, "ResultMgmt_ToggleAdvControls_AccessKey") })),
                    HttpUtility.HtmlAttributeEncode(locResourceString),
                    HttpUtility.HtmlAttributeEncode(text4),
                    string.Concat(new string[]
                    {
                        "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {if (Srch.U.isEnterKey(String.fromCharCode(event.keyCode))) {$find('",
                        SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId),
                        "').search($get('",
                        SPHttpUtility.EcmaScriptStringLiteralEncode(text4),
                        "').value);return Srch.U.cancelEvent(event);}})"
                    }),
                    "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {var ctl = $find('" + SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId) + "');ctl.activateDefaultQuerySuggestionBehavior();})",
                    "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {var ctl = $find('" + SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId) + "');ctl.hidePrompt();ctl.setBorder(true);})",
                    "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {var ctl = $find('" + SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId) + "'); if (ctl){ ctl.showPrompt(); ctl.setBorder(false);}})",
                    HttpUtility.HtmlAttributeEncode(text2)
                });
                string text9 = null;
                if (web != null)
                {
                    text9 = SPUtility.GetThemedImageUrl(SPUtility.ConcatUrls("/", SPUtility.ConcatUrls(SPUtility.ContextLayoutsFolder, "images/searchresultui.png")), "searchresultui");
                }
                if (flag)
                {
                    output.Write("<a title=\"{0}\" id=\"{1}\" onclick=\"{2}\" href=\"{3}\" class=\"ms-srch-sb-navLink\" >", new object[]
                    {
                        HttpUtility.HtmlAttributeEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_NavigationButtonToolTip_Text") })),
                        HttpUtility.HtmlAttributeEncode(text5),
                        "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {$find('" + SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId) + "').activateDefaultNavigationBehavior();return Srch.U.cancelEvent(event);})",
                        "javascript: {}"
                    });
                    if (!string.IsNullOrEmpty(text9))
                    {
                        output.Write("<img src=\"{0}\" class=\"ms-srch-sb-navImg\" id=\"navImg\" alt=\"{1}\" />", HttpUtility.HtmlAttributeEncode(text9), HttpUtility.HtmlAttributeEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_NavigationButtonToolTip_Text") })));
                    }
                    output.Write("</a>");
                }
                output.Write("<a title=\"{0}\" class=\"ms-srch-sb-searchLink\" id=\"{1}\" onclick=\"{2}\" href=\"{3}\" >", new object[]
                {
                    HttpUtility.HtmlAttributeEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_SearchButtonToolTip_Text") })),
                    HttpUtility.HtmlAttributeEncode(text8),
                    string.Concat(new string[]
                    {
                        "EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function() {$find('",
                        SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId),
                        "').search($get('",
                        SPHttpUtility.EcmaScriptStringLiteralEncode(text4),
                        "').value);})"
                    }),
                    "javascript: {}"
                });
                if (!string.IsNullOrEmpty(text9))
                {
                    output.Write("<img src=\"{0}\" class=\"ms-srch-sb-searchImg\" id=\"searchImg\" alt=\"{1}\" />", HttpUtility.HtmlAttributeEncode(text9), HttpUtility.HtmlAttributeEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_SearchButtonToolTip_Text") })));
                }
                output.Write("</a>");
                if (this.ShowQuerySuggestions)
                {
                    output.Write("<div class=\"ms-qSuggest-container ms-shadow\" id=\"AutoCompContainer\">");
                    output.Write("<div id=\"{0}\"></div>", HttpUtility.HtmlAttributeEncode(text6));
                    output.Write("</div>");
                }
                if (flag)
                {
                    output.Write("<div class=\"ms-qSuggest-container ms-shadow\" id=\"NavDropdownListContainer\">");
                    output.Write("<div id=\"{0}\"></div>", HttpUtility.HtmlAttributeEncode(text7));
                    output.Write("</div>");
                }
                output.Write("</div>");
                if (this.ShowAdvancedLink && !string.IsNullOrEmpty(this.AdvancedSearchPageAddress))
                {
                    output.Write("<div class='ms-srch-sb-link'><a id='AdvancedLink' href='{0}'>{1}</a></div>", SPHttpUtility.HtmlUrlAttributeEncode(this.AdvancedSearchPageAddress), SPHttpUtility.HtmlEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_AdvancedSearchText") })));
                }
                if (this.ShowPreferencesLink)
                {
                    string text10 = string.Empty;
                    if (web != null)
                    {
                        text10 = SPUtility.ConcatUrls(SPUtility.ContextLayoutsFolder, "EditUserPref.aspx?Source=" + SPHttpUtility.UrlKeyValueEncode(SPAlternateUrl.ContextUri.OriginalString));
                        text10 = SPUtility.ConcatUrls(web.ServerRelativeUrl, text10);
                    }
                    if (!string.IsNullOrEmpty(text10))
                    {
                        output.Write("<div class='ms-srch-sb-link'><a id='PreferencesLink' href='{0}'>{1}</a></div>", SPHttpUtility.HtmlUrlAttributeEncode(text10), SPHttpUtility.HtmlEncode((string)wppgetLocResourceString.Invoke(instanceWebPartPlatform, new object[] { Enum.Parse(typeLocStringIdO, "SearchBox_PreferencesText") })));
                    }
                }
                output.Write("</div>");
                output.Write("</div>");

                Type swpsbd = typeof(OriginalScriptApplicationManager).Assembly.GetType("Microsoft.Office.Server.Search.WebControls.ScriptWebPartScriptBehaviorDescriptor");
                var  scriptWebPartScriptBehaviorDescriptor = Activator.CreateInstance(swpsbd, this.ClientControlType, base.CsrContainerId);
                typeof(ScriptObjectBuilder).GetMethod("DescribeSimpleComponent", BindingFlags.NonPublic | BindingFlags.Static).Invoke(typeof(ScriptObjectBuilder), new object[] { this, scriptWebPartScriptBehaviorDescriptor });
                string behaviorScript = (string)swpsbd.GetMethod("GetBehaviorScript", BindingFlags.Instance | BindingFlags.Public).Invoke(scriptWebPartScriptBehaviorDescriptor, new object[] { });
                this.OnAfterSerializeToClient(new ScriptWebPart.AfterSerializeToClientEventArgs(this));
                string text11 = string.Concat(new string[]
                {
                    "\r\n                    ExecuteOrDelayUntilScriptLoaded(\r\n                        function() \r\n                        {\r\n                            if ($isNull($find('",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(base.CsrContainerId),
                    "')))\r\n                            {\r\n                                var sb = ",
                    behaviorScript,
                    "\r\n                                sb.activate('",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(locResourceString),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text4),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text3),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text5),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text6),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text7),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text8),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(scriptLiteralToEncode),
                    "', '",
                    SPHttpUtility.EcmaScriptStringLiteralEncode(text2),
                    "');\r\n                            }\r\n                        }, 'Search.ClientControls.js');"
                });

                if (this.SetFocusOnPageLoad)
                {
                    Guid   guid   = Guid.NewGuid();
                    string text12 = text11;
                    text11 = string.Concat(new string[]
                    {
                        text12,
                        "\r\n                        function initSearchBox",
                        guid.ToString("N"),
                        "() {\r\n                            $get('",
                        SPHttpUtility.EcmaScriptStringLiteralEncode(text4),
                        "').focus();\r\n                        }\r\n                        _spBodyOnLoadFunctionNames.push('initSearchBox",
                        guid.ToString("N"),
                        "');"
                    });
                }

                if (!SPPageContentManager.IsStartupScriptRegistered(this.Page, base.GetType(), "SearchBoxScriptWebPart" + text4))
                {
                    SPPageContentManager.RegisterStartupScript(this.Page, base.GetType(), "SearchBoxScriptWebPart" + text4, text11);
                }
            }

            typeof(ScriptWebPart).GetMethod("RenderWebPart", BindingFlags.Instance | BindingFlags.NonPublic).InvokeNotOverride(this, output);
        }