按受众筛选 SharePoint 列表

Posted

技术标签:

【中文标题】按受众筛选 SharePoint 列表【英文标题】:Filter a SharePoint list by audience 【发布时间】:2011-06-14 20:05:07 【问题描述】:

我对 Sharepoint 开发非常陌生。我有以下代码需要按目标受众显示列表项。我知道我想添加这样的东西

   AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
   foreach (SPListItem listItem in list.Items)
   
      // get roles the list item is targeted to
     string audienceFieldValue = (string)listItem[k_AudienceColumn];

      // quickly check if the user belongs to any of those roles
     if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader,
        audienceFieldValue,
        false))

但我不知道在下面的代码中放置它的位置。如果您有任何建议,我将不胜感激。

 using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.htmlControls;

namespace PersonalAnnouncements.PersonalAnnouncements


    [ToolboxItem(false)]
    public class PersonalAnnouncements : Microsoft.SharePoint.WebPartPages.WebPart
    
        // Fields
        private string _exceptions = "";
        private AddInsEnum DE = AddInsEnum.HyperLink;
        private const AddInsEnum DefaultAddInsEnum = AddInsEnum.HyperLink;
        private const TheDateFormat DefaultDateFormat = TheDateFormat.MonthDayYear;
        private const PeriodEnum DefaultPeriod = PeriodEnum.Five;
        private const string defaultText = "Your text here";
        private const string DefaultURL = "DispForm.aspx";
        private TheDateFormat DF = TheDateFormat.MonthDayYear;
        private string endField = "Image URL";
        private const string imgTURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
        private const string imgURL = "/_layouts/NewsViewer/banner1.jpg";
        protected Label lblError;
        private const string listText = "";
        private string listViewFields = "";
        private PeriodEnum Period = PeriodEnum.Five;
        private string sImageURL = "/_layouts/NewsViewer/banner1.jpg";
        private string siteURLtext = "Your Site here";
        private string startField = "Body";
        private string sTImageURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
        private string sTimeField = "/_layouts/NewsViewer/style_smaller.css";
        private string sYAxisTitle = "15";
        private string text = "Your text here";
        private string ThumbImageField = "";
        private const string timer = "/_layouts/NewsViewer/style_smaller.css";
        private string titleField = "";
        private string urltocalendar = "DispForm.aspx";
        private const string yaxistit = "15";


        // Methods
        protected override void CreateChildControls()
        
            HtmlTable table;
            HtmlTableRow row;
            HtmlTableCell cell;
            bool controlsAdded = false;
            try
            


                base.CreateChildControls();
                SPWeb theWeb = new SPSite(this.SiteURL).OpenWeb();
                SPSecurity.RunWithElevatedPrivileges(delegate
                
                    using (SPSite site = new SPSite(theWeb.Url))
                    
                        using (SPWeb web = site.OpenWeb())
                        
                            SPList list = web.Lists[this.Text];
                            if (list.BaseTemplate == SPListTemplateType.GenericList)
                            
                                this.lblError = new Label();
                                this.lblError.Text = "Error:";
                                this.lblError.Visible = true;
                                HtmlTable child = new HtmlTable();
                                row = new HtmlTableRow();
                                cell = new HtmlTableCell();
                                string str = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.CSSField + "\" /><script type=\"text/javascript\" src=\"/_layouts/NewsViewer/jquery-1.3.2.min.js\"></script><script type=\"text/javascript\">var X = jQuery.noConflict();X(document).ready(function() \t X(\".main_image .desc\").show(); X(\".main_image .block\").animate( opacity: 0.85 , 1 ); X(\".image_thumb ul li:first\").addClass('active'); X(\".image_thumb ul li\").click(function()   var imgAlt = X(this).find('img').attr(\"alt\");   var imgTitle = X(this).find('a').attr(\"href\");   var imgDesc = X(this).find('.block').html(); \t var imgDescHeight = X(\".main_image\").find('.block').height();\t\t  if (X(this).is(\".active\"))         return false;    else        X(\".main_image .block\").animate( opacity: 0, marginBottom: -imgDescHeight , 250 , function()           X(\".main_image .block\").html(imgDesc).animate( opacity: 0.85,\tmarginBottom: \"0\" , 250 );          X(\".main_image img\").attr( src: imgTitle , alt: imgAlt);      );    X(\".image_thumb ul li\").removeClass('active');   X(this).addClass('active');    return false;) .hover(function() X(this).addClass('hover'); , function()  X(this).removeClass('hover');); X(\"a.collapse\").click(function()   X(\".main_image .block\").slideToggle();   X(\"a.collapse\").toggleClass(\"show\"); );); </script><div id=\"main\" class=\"container\">";
                                string sideNav = this.GetSideNav();
                                string mainContent = this.GetMainContent();
                                cell.InnerHtml = str + mainContent + sideNav + "</div></div>";
                                row.Cells.Add(cell);
                                child.Rows.Add(row);
                                this.Controls.Add(child);
                                controlsAdded = true;
                            
                        
                    
                );
            
            catch (Exception exception)
            
                if (controlsAdded)
                
                    this._exceptions = this._exceptions + "CreateChildControls_Exception: " + exception.Message;
                
                table = new HtmlTable();
                row = new HtmlTableRow();
                cell = new HtmlTableCell();
                if (!this.Text.Contains("Your text here"))
                
                    cell.InnerHtml = "Error: " + exception.Message;
                    row.Cells.Add(cell);
                    table.Rows.Add(row);
                    this.Controls.Add(table);
                    this.Controls.Add(this.lblError);
                
            
            if (!controlsAdded)
            
                table = new HtmlTable();
                row = new HtmlTableRow();
                cell = new HtmlTableCell();
                if (!this.Text.Contains("Your text here"))
                
                    cell.InnerHtml = "Please choose the Personal Announcement list: " + this.Text + " - Site:" + this.SiteURL;
                    row.Cells.Add(cell);
                    table.Rows.Add(row);
                    this.Controls.Add(table);
                    this.Controls.Add(this.lblError);
                
                else
                
                    cell.InnerHtml = "Please setup Personal Announcement by clicking Modify Shared WebPart";
                    row.Cells.Add(cell);
                    table.Rows.Add(row);
                    this.Controls.Add(table);
                
            
        

        private string FirstWords(string input, int numberWords)
        
            try
            
                int num = numberWords;
                for (int i = 0; i < input.Length; i++)
                
                    if (input[i] == ' ')
                    
                        num--;
                    
                    if (num == 0)
                    
                        return input.Substring(0, i);
                    
                
            
            catch (Exception)
            
            
            return string.Empty;
        


        private string GetMainContent()
        
            string str = "";
            this.lblError.Text = this.lblError.Text + " -> GetMainContent()";
            SPSite site = new SPSite(this.SiteURL);
            SPWeb web = site.OpenWeb();
            SPUserToken userToken = site.SystemAccount.UserToken;
            using (SPSite site2 = new SPSite(web.Url, userToken))
            
                using (SPWeb web2 = site2.OpenWeb())
                
                    SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
                    view.RowLimit = 1;
                    SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
                    int num = 0;
                    int num2 = this.getNumber(this.NumEvents.ToString());
                    string str2 = "";
                    if (items.Count > 0)
                    

                        foreach (SPListItem item in items)
                        
                            if (num == 0)
                            
                                object obj2;
                                string imageURL = "";
                                string format = "";
                                if (this.DateFormat.ToString() == "DayMonthYear")
                                
                                    format = "d/M/yyyy HH:mm tt";
                                
                                else
                                
                                    format = "M/d/yyyy HH:mm tt";
                                
                                if (item[this.ImageURLField] != null)
                                
                                    if (this.TheColumnType.ToString() != "HyperLink")
                                    
                                        if (item[this.ImageURLField].ToString().Trim() != string.Empty)
                                        
                                            imageURL = item[this.ImageURLField].ToString();
                                        
                                        else
                                        
                                            imageURL = this.ImageURL;
                                        
                                    
                                    else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
                                    
                                        imageURL = item[this.ImageURLField].ToString().Split(new char[]  ',' )[0];
                                    
                                    else
                                    
                                        imageURL = this.ImageURL;
                                    
                                
                                else
                                
                                    imageURL = this.ImageURL;
                                
                                str2 = str2 + "<div class=\"main_image\">";
                                str2 = str2 + "<img src=\"" + imageURL + "\" alt=\"BNNewsbanner\" />";
                                str2 = str2 + "<div class=\"desc\" ><a href=\"#\" class=\"collapse\">Close Me!</a>";

                                if (item[this.TitleField] != null)
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" );
                                
                                else
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No Title Text Found</a></h2>" );
                                
                                str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
                                if (item[this.BodyField] != null)
                                
                                    obj2 = str2;
                               //  str2 = string.Concat(new object[]  obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" );
                                 str2 = string.Concat(new object[]  obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" );

                                
                                else
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" );
                                
                            
                            num++;
                        
                    
                    str = str + str2;
                
            
            return str;
        

        public int getNumber(string number)
        
            switch (number)
            
                case "One":
                    return 1;

                case "Two":
                    return 2;

                case "Three":
                    return 3;

                case "Four":
                    return 4;

                case "Five":
                    return 5;

                case "Six":
                    return 6;

                case "Seven":
                    return 7;

                case "Eight":
                    return 8;

                case "Nine":
                    return 9;

                case "Ten":
                    return 10;
            
            return 0;
        

        private string GetSideNav()
        
            this.lblError.Text = this.lblError.Text + " -> GetSideNav()";
            string str = "<div class=\"image_thumb\"><ul>";
            SPSite site = new SPSite(this.SiteURL);
            SPWeb web = site.OpenWeb();
            SPUserToken userToken = site.SystemAccount.UserToken;
            using (SPSite site2 = new SPSite(web.Url, userToken))
            
                using (SPWeb web2 = site2.OpenWeb())
                
                    SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
                    SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
                    int num = 0;
                    int num2 = this.getNumber(this.NumEvents.ToString());
                    string str2 = "";
                    if (items.Count > 0)
                    
                        foreach (SPListItem item in items)
                        
                            if (num < num2)
                            
                                object obj2;
                                string imageThumbURL = "";
                                string imageURL = "";
                                string format = "";
                                if (this.DateFormat.ToString() == "DayMonthYear")
                                
                                    format = "d/M/yyyy HH:mm tt";
                                
                                else
                                
                                    format = "M/d/yyyy HH:mm tt";
                                
                                if (item[this.ImageURLField] != null)
                                
                                    if (this.TheColumnType.ToString() != "HyperLink")
                                    
                                        if (item[this.ImageURLField].ToString().Trim() != string.Empty)
                                        
                                            imageURL = item[this.ImageURLField].ToString();
                                        
                                        else
                                        
                                            imageURL = this.ImageURL;
                                        
                                    
                                    else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
                                    
                                        imageURL = item[this.ImageURLField].ToString().Split(new char[]  ',' )[0];
                                    
                                    else
                                    
                                        imageURL = this.ImageURL;
                                    
                                
                                else
                                
                                    imageURL = this.ImageURL;
                                
                                if (item[this.ThumbImageURLField] != null)
                                
                                    if (this.TheColumnType.ToString() != "HyperLink")
                                    
                                        if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
                                        
                                            imageThumbURL = item[this.ThumbImageURLField].ToString();
                                        
                                        else
                                        
                                            imageThumbURL = this.ImageThumbURL;
                                        
                                    
                                    else if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
                                    
                                        imageThumbURL = item[this.ThumbImageURLField].ToString().Split(new char[]  ',' )[0];
                                    
                                    else
                                    
                                        imageThumbURL = this.ImageThumbURL;
                                    
                                
                                else
                                
                                    imageThumbURL = this.ImageThumbURL;
                                
                                str2 = str2 + "<li><a href=\"" + imageURL + "\">";
                                str2 = str2 + "<img src=\"" + imageThumbURL + "\" alt=\"\" /></a>";
                                if (item[this.TitleField] != null)
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" );
                                
                                else
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No List Title Found</a></h2>" );
                                
                                str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
                                if (item[this.BodyField] != null)
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" );
                                
                                else
                                
                                    obj2 = str2;
                                    str2 = string.Concat(new object[]  obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" );
                                
                            
                            num++;
                        
                    
                    str = str + str2;
                
            
            return (str + "</ul>");
        

        public override ToolPart[] GetToolParts()
        
            ToolPart[] partArray = new ToolPart[3];
            WebPartToolPart part = new WebPartToolPart();
            CustomPropertyToolPart part2 = new CustomPropertyToolPart();
            partArray[0] = part2;
            partArray[1] = part;
            partArray[2] = new CustomToolPart();
            return partArray;
        

        protected override void RenderContents(HtmlTextWriter writer)
        
            try
            
                base.RenderContents(writer);
            
            catch (Exception exception)
            
                this._exceptions = this._exceptions + "RenderContents_Exception: " + exception.Message;
            
            finally
            
                if (this._exceptions.Length > 0)
                
                    writer.WriteLine(this._exceptions);
                
            
        

        private string StripTagsCharArray(string source)
        
            char[] chArray = new char[source.Length];
            int index = 0;
            bool flag = false;
            for (int i = 0; i < source.Length; i++)
            
                char ch = source[i];
                if (ch == '<')
                
                    flag = true;
                
                else if (ch == '>')
                
                    flag = false;
                
                else if (!flag)
                
                    chArray[index] = ch;
                    index++;
                
            
            return new string(chArray, 0, index);
        

        // Properties
        public string BodyField
        
            get
            
                return this.startField;
            
            set
            
                this.startField = value;
            
        

        [WebDisplayName("Style Sheet URL"), WebDescription("Specifies the path to the css file"), SPWebCategoryName("General Settings"), Personalizable(true), WebBrowsable(true)]
        public string CSSField
        
            get
            
                return this.sTimeField;
            
            set
            
                this.sTimeField = value;
            
        

        [WebBrowsable(true), Personalizable(true), WebDisplayName("Date Format"), WebDescription("Date Format of your News Items"), SPWebCategoryName("General Settings")]
        public TheDateFormat DateFormat
        
            get
            
                return this.DF;
            
            set
            
                this.DF = value;
            
        

        [WebBrowsable(true), WebDescription("Thumb Image URL to use when no image is found"), SPWebCategoryName("General Settings"), Personalizable(true), WebDisplayName("No Thumb Image URL")]
        public string ImageThumbURL
        
            get
            
                return this.sTImageURL;
            
            set
            
                this.sTImageURL = value;
            
        

        [Personalizable(true), SPWebCategoryName("General Settings"), WebBrowsable(true), WebDisplayName("No Image URL"), WebDescription("Image URL to use when no image is found")]
        public string ImageURL
        
            get
            
                return this.sImageURL;
            
            set
            
                this.sImageURL = value;
            
        

        public string ImageURLField
        
            get
            
                return this.endField;
            
            set
            
                this.endField = value;
            
        

        public string ListViewFields
        
            get
            
                return this.listViewFields;
            
            set
            
                this.listViewFields = value;
            
        

        [WebDescription("Number of news items to show"), WebDisplayName("Number of news items to show"), WebBrowsable(true), SPWebCategoryName("General Settings"), Personalizable(true)]
        public PeriodEnum NumEvents
        
            get
            
                return this.Period;
            
            set
            
                this.Period = value;
            
        

        [WebDisplayName("Number of words to show from the Body"), Personalizable(true), SPWebCategoryName("General Settings"), WebDescription("Specifies the number of words to show from the body in the main webpart, under the Title"), WebBrowsable(true)]
        public string NumWords
        
            get
            
                return this.sYAxisTitle;
            
            set
            
                this.sYAxisTitle = value;
            
        

        public string SiteURL
        
            get
            
                return this.siteURLtext;
            
            set
            
                this.siteURLtext = value;
            
        

        public string Text
        
            get
            
                return this.text;
            
            set
            
                this.text = value;
            
        

        [Personalizable(true), SPWebCategoryName("General Settings"), WebDisplayName("Image Column Type")

【问题讨论】:

【参考方案1】:

您可以将代码放在CreateChildControls() 方法中。

【讨论】:

嗨,Madhur,我对此很陌生,可以提供代码 sn-p 吗?我尝试将它插入 createchildcontrols() 方法并出错。 哎呀,有很多代码要通读...我假设您可能需要针对您获取主要内容的受众群体:GetMainContent

以上是关于按受众筛选 SharePoint 列表的主要内容,如果未能解决你的问题,请参考以下文章

如何筛选使用Microsoft Graph查询的Sharepoint列表项

更新多个 SharePoint 列表项

Sharepoint:使用“兼容”用户界面显示非 Sharepoint 内容列表的最佳方式?

SharePoint 列表/Excel 到 Ms Access 在分隔符处拆分

sharepoint 列表和登录用户问题

如何检索 SharePoint 列表项的目标安全组?