MOSS Webpart--查询站点及其子站点中所有列表项

代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

using System.ComponentModel;
using System.Xml.Serialization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;


namespace MySearch
{
    [DefaultProperty(
"Text"),
    ToolboxData(
"<{0}:MySearchPart runat=server></{0}:MySearchPart>"),
       XmlRoot(Namespace 
= "MySearch")]
    
public class MySearch : Microsoft.SharePoint.WebPartPages.WebPart, IDisposable
    {
        
private Button serarchBtn;
        
private DropDownList ddlYear;
        
private DropDownList ddlFlag;
        
private TextBox txtNum;
        
private TextBox txtType;
        
private TextBox txtKey;
        
private Table tblResult;

        
private string _webUrl = string.Empty;
        
private string _count = "30";
        
//标题,
        private string fieldFWWH = "_x6587__x53f7_";
        
private string fieldSSSJ = "_x4e8b__x4ef6__x65e5__x671f_";
        
private string fieldFGLX = "_x7c7b__x578b__x002F__x72b6__x60";
        
private string _viewField = "Attachments,LinkTitle,_x6587__x53f7_,_x4e8b__x4ef6__x65e5__x671f_,_x7c7b__x578b__x002F__x72b6__x60";
        
private string img = "<img src='/_layouts/images/TH/at.jpg' title='附件' />";

        
private string styleTable = "width:100%;";
        
private string styleHeade = "background: url('/_layouts/images/TH/line_orange.jpg') repeat-x bottom; line-height:23px;font-weight:bold; color:#336bbd; border:0px;";
        
private string styleRow = "line-height:25px;";
        
private string styleRowTwo = "line-height:25px;background:#f9f9f9";
        
private string styleDiv = "color:#336bbd;";

        
#region constructor
        
public MySearch()
        {}
        
#endregion

        
private void Inita()
        {
            
try
            {
                txtKey 
= new TextBox();
                txtNum 
= new TextBox();
                txtType 
= new TextBox();
                ddlFlag 
= new DropDownList();
                ddlYear 
= new DropDownList();
                serarchBtn 
= new Button();
                tblResult 
= new Table();
                tblResult.BorderWidth 
= Unit.Pixel(0);
                tblResult.Attributes.Add(
"style", styleTable);

                
this.Controls.Add(new LiteralControl(string.Format("<div style='{0}'><b>请设置查询条件</b> <span color='red'>[每次查询最大记录{1}条]</span></div>",styleDiv, RecordCount)));
                
this.Controls.Add(new LiteralControl("<br/>标题 包含 "));
                
this.Controls.Add(txtKey);
                
this.Controls.Add(new LiteralControl("    **** 等于 "));
                
this.Controls.Add(txtNum);
                
this.Controls.Add(new LiteralControl("<br/><br/>#### 等于 "));
                
this.Controls.Add(txtType);
                
//this.Controls.Add(new LiteralControl("    @@@@ "));
                
//this.Controls.Add(ddlFlag);
                
//this.Controls.Add(new LiteralControl(" "));
                
//this.Controls.Add(ddlYear);
                
//this.Controls.Add(new LiteralControl("<br/><br/>"));
                this.Controls.Add(new LiteralControl("    "));
                
this.Controls.Add(serarchBtn);
                
this.Controls.Add(new LiteralControl("<br/><br/>"));
                
this.Controls.Add(tblResult);

                serarchBtn.Text 
= "开始查询";
                serarchBtn.Click 
+= new EventHandler(serarchBtn_Click);
                
int nowYear = DateTime.Now.Year;
                
int sYear = nowYear - 30;
                ListItem item 
= null;
                
//年度下拉
                for (int i = nowYear; i >= sYear; i--)
                {
                    item 
= new ListItem(i.ToString(), i.ToString());
                    ddlYear.Items.Add(item);
                }
                ddlYear.Items.Insert(
0new ListItem(""""));
                
//操作符
                ddlFlag.Items.Add(new ListItem("包含""Contains"));
                ddlFlag.Items.Add(
new ListItem("大于等于""Geq"));
                ddlFlag.Items.Add(
new ListItem("大于""Gt"));
                ddlFlag.Items.Add(
new ListItem("小于等于""Leq"));
                ddlFlag.Items.Add(
new ListItem("小于""Lt"));
            }
            
catch
            { }
        }

        
protected override void CreateChildControls()
        {
            
this.Inita();
            
base.CreateChildControls ();
        }

        
//执行查询事件
        private void serarchBtn_Click(object sender, EventArgs e)
        {
            
try
            {
                
if (string.IsNullOrEmpty(_webUrl))
                {
                    
return;
                }

                
string siteUrl = SPContext.Current.Site.Url;
                SPSecurity.RunWithElevatedPrivileges(
delegate
                {
                    
using (SPSite spsite = new SPSite(siteUrl))
                    {
                        SPQuery spquery 
= this.CreatQuery();
                        List
<SPListItem> listItemColl = new List<SPListItem>();
                        List
<string> listUrl = new List<string>();
                        
this.GetSearchItems(spsite.OpenWeb(_webUrl), spquery, listItemColl, listUrl);
                        
this.ShowList(spsite.OpenWeb(_webUrl), listItemColl, listUrl);
                    }
                });
            }
            
catch
            { }
        }

        
//显示结果
        private void ShowList(SPWeb spweb, List<SPListItem> listItemColl, List<string> listUrl)
        {
            
this.CreatHeader();
            
this.CreatBody(spweb, listItemColl, listUrl);
        }

        
//构造表头
        private void CreatHeader()
        {
            TableRow row 
= new TableRow();
            row.Attributes.Add(
"style", styleHeade);
            TableCell cell 
= null;
            cell 
= new TableCell();
            cell.Controls.Add(
new LiteralControl(img));
            cell.Width 
= Unit.Parse("3%");
            row.Cells.Add(cell);

            cell 
= new TableCell();
            cell.Text 
= "标题";
            cell.Width 
= Unit.Parse("40%");
            row.Cells.Add(cell);

            cell 
= new TableCell();
            cell.Text 
= "****";
            cell.Width 
= Unit.Parse("20%");
            row.Cells.Add(cell);

            cell 
= new TableCell();
            cell.Text 
= "@@@@";
            cell.Width 
= Unit.Parse("15%");
            row.Cells.Add(cell);

            cell 
= new TableCell();
            cell.Text 
= "####";
            cell.Width 
= Unit.Parse("22%");
            row.Cells.Add(cell);

            
this.tblResult.Rows.Add(row);
        }

        
//构造结果数据项
        private void CreatBody(SPWeb spweb, List<SPListItem> items, List<string> listUrl)
        {
            
string[] fields = this.ViewField.Split(',');
            
string cellTitle = "<a href='{0}' >{1}</a>";
            
string link = "{0}/{1}/DispForm.aspx?ID={2}";
            
string tempLink = string.Empty;
            TableRow row 
= null;
            TableCell cell 
= null;

            
for (int i = 0; i < items.Count;i++ )
            {
                row 
= new TableRow();
                row.Attributes.Add(
"style", i % 2 == 0 ? styleRow : styleRowTwo);
                tempLink 
= string.Format(link, listUrl[i], items[i].Url.Substring(0,items[i].Url.LastIndexOf("/")) , items[i].ID);
                
foreach (string field in fields)
                {
                    cell 
= new TableCell();
                    
//附件判断
                    if (field.ToLower().Equals("attachments"))
                    {
                        
if (items[i].Attachments.Count > 0)
                        {
                            cell.Controls.Add(
new LiteralControl(img));
                        }
                        
else
                        {
                            cell.Text 
= string.Empty;
                        }
                    }
                    
else if (field.ToLower().Equals("linktitle"))
                    {
                        cell.Controls.Add(
new LiteralControl(string.Format(cellTitle, tempLink, items[i].DisplayName)));
                    }
                    
else if (field.ToLower().Equals(this.fieldSSSJ)) //实施时间
                    {
                        cell.Text 
= items[i][field] != null ? DateTime.Parse(items[i][field].ToString()).ToString("yyyy-MM-dd") : string.Empty;
                    }
                    
else
                    {
                        cell.Text 
= items[i][field] != null ? items[i][field].ToString() : string.Empty;
                    }
                    row.Cells.Add(cell);
                }
                
this.tblResult.Rows.Add(row);
            }
        }

        
//递归查找各个站点中的列表
        private void GetSearchItems(SPWeb spWeb, SPQuery spquery, List<SPListItem> listItemColl, List<string> listUrl)
        {
            SPListItemCollection listItems 
= null;
            
foreach (SPWeb web in spWeb.Webs)
            {
                
if (listItemColl.Count >= int.Parse(_count))
                {
                    
break;
                }
                
foreach (SPList splist in web.Lists)
                {
                    
try
                    {
                        
if (string.IsNullOrEmpty(splist.Description) && splist.Title.Contains("List"))
                        {
                            listItems 
= splist.GetItems(spquery);
                            
foreach (SPListItem item in listItems)
                            {
                                
if (listItemColl.Count >= int.Parse(_count))
                                {
                                    
break;
                                }
                                listItemColl.Add(item);
                                listUrl.Add(web.Url);
                            }
                        }
                    }
                    
catch
                    {
                        
continue;
                    }
                }
                
this.GetSearchItems(web, spquery, listItemColl, listUrl);
            }
        }

        
//构造SPQuery语句
        private SPQuery CreatQuery()
        {
            
string q1 = "<Where>{0}</Where>";
            
string q2 = "<Where><And>{0}{1}</And></Where>";
            
string q3 = "<Where><And>{0}<And>{1}{2}</And></And></Where>";
            
string q4 = "<Where><And>{0}<And>{1}<And>{2}{3}</And></And></And></Where>";
            
string by = string.Format("<OrderBy><FieldRef Name='{0}' Ascending='False' /></OrderBy>", fieldSSSJ);

            
int t = 0;
            
string strKey = txtKey.Text.Trim();
            
string strNum = txtNum.Text.Trim();
            
string strType = txtType.Text.Trim();
            
string strFlag = this.ddlFlag.SelectedValue;
            
string strYear = this.ddlYear.SelectedValue;
            
string spKey = string.Empty;
            
string spNum = string.Empty;
            
string spType = string.Empty;
            
string spYear = string.Empty;
            StringBuilder sbStr 
= new StringBuilder();

            
if (!string.IsNullOrEmpty(strKey))
            {
                spKey 
= string.Format("<Contains><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Contains>", strKey);
                t
++;
                sbStr.Append(spKey).Append(
"|");
            }
            
if (!string.IsNullOrEmpty(strNum))
            {
                spNum 
= string.Format("<Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq>"this.fieldFWWH, strNum);
                t
++;
                sbStr.Append(spNum).Append(
"|");
            }
            
if (!string.IsNullOrEmpty(strType))
            {
                spType 
= string.Format("<Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq>"this.fieldFGLX, strType);
                t
++;
                sbStr.Append(spType).Append(
"|");
            }
            
if (!string.IsNullOrEmpty(strYear))
            {
                spYear 
= string.Format("<{0}><FieldRef Name='{2}' /><Value IncludeTimeValue='TRUE' Type='DateTime'>{1}</Value></{0}>", strFlag, strYear, this.fieldSSSJ);
                t
++;
                sbStr.Append(spYear).Append(
"|");
            }

            
string[] arr = sbStr.ToString().Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            SPQuery spquery 
= new SPQuery();
            
switch (t)
            {
                
case 1:
                    spquery.Query 
= string.Format(q1, arr);
                    
break;
                
case 2:
                    spquery.Query 
= string.Format(q2, arr);
                    
break;
                
case 3:
                    spquery.Query 
= string.Format(q3, arr);
                    
break;
                
case 4:
                    spquery.Query 
= string.Format(q4, arr);
                    
break;
                
default:
                    spquery.Query 
= "";
                    
break;
            }
            spquery.Query 
+= by;
            
return spquery;
        }

        
#region properties

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
          Description(
"搜索开始网站URL"), FriendlyName("当前网站URL。例:web1/web11")]
        
public string WebURL
        {
            
get { return _webUrl; }
            
set { _webUrl = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
          Description(
"最大查询记录数"), FriendlyName("每次查询的最大返回记录数")]
        
public string RecordCount
        {
            
get { return _count; }
            
set { _count = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
         Description(
"视图字段,用逗号,相隔"), FriendlyName("视图字段")]
        
public string ViewField
        {
            
get { return _viewField; }
            
set { _viewField = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
        Description(
"****"), FriendlyName("")]
        
public string FieldFWWH
        {
            
get { return this.fieldFWWH; }
            
set { this.fieldFWWH = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
       Description(
""), FriendlyName("")]
        
public string FieldSSSJ
        {
            
get { return this.fieldSSSJ; }
            
set { this.fieldSSSJ = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
       Description(
""), FriendlyName("")]
        
public string FieldFGLX
        {
            
get { return this.fieldFGLX; }
            
set { this.fieldFGLX = value; }
        }

        [Browsable(
true), Category("Miscellaneous"), WebPartStorage(Storage.Personal),
        Description(
"标题行样式"), FriendlyName("标题行样式")]
        
public string StyleHeader
        {
            
get { return styleHeade; }
            
set { styleHeade = value; }
        }
        
#endregion
    }
}

 

显示效果:

posted @ 2009-12-10 15:59  边缘凉风  阅读(332)  评论(0编辑  收藏  举报