在创建的时候注意你要有权限。还有如果要使用请注意合理释放资源,因为我是随便写的 就没有去考虑资合理问题。

首先来写怎么去通过代码创建SPweb,SPWeb与Spsite类似所以我就不详细信息注视了

CreateWeb

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;

namespace TestWF
{
    public partial class CreateWeb : Form
    {
        public Form2 ParentForm { get; set; }
        public CreateWeb()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Farm场
        /// </summary>
        public SPFarm Farm
        {
            get { return SPFarm.Local; }
        }
        /// <summary>
        /// 服务
        /// </summary>
        public SPWebService SPWebService {
            get { return  Farm.Services.GetValue<SPWebService>(""); }
        }
    
        private void CreateApp_Load(object sender, EventArgs e)
        {
            #region 加载应用程序
            List<ComboBoxModel> list = new List<ComboBoxModel>();
            list.Add(new ComboBoxModel() { ID = "1", Name = "--请选择--" });
            foreach (SPWebApplication webApp in SPWebService.WebApplications)
            {
                list.Add(new ComboBoxModel() { ID = webApp.Id.ToString(), Name = webApp.Name });
            }
            this.cbbApp.DataSource = list;
            this.cbbApp.DisplayMember = "Name";
            this.cbbApp.ValueMember = "Id";
            this.cbbApp.SelectedValueChanged += cbbApp_SelectedValueChanged; 
            #endregion
       
            #region 加载模板选择
            //填写管理中心地址
            SPSite site = new SPSite("http://jason-pc:5901/");
            SPWeb web = site.OpenWeb();
            //获取所有模版
            SPWebTemplateCollection templates = web.GetAvailableWebTemplates(2052);
            TreeNode node = new TreeNode();
            node.Text = "协作";
            BindTemplateTree(node, templates);
            this.tvTemp.Nodes.Add(node);

            node = new TreeNode();
            node.Text = "会议";
            BindTemplateTree(node, templates);
            this.tvTemp.Nodes.Add(node);


            node = new TreeNode();
            node.Text = "企业";
            BindTemplateTree(node, templates);
            this.tvTemp.Nodes.Add(node);

            node = new TreeNode();
            node.Text = "发布";
            BindTemplateTree(node, templates);
            this.tvTemp.Nodes.Add(node);

            node = new TreeNode();
            node.Text = "自定义";
            BindTemplateTree(node, templates);
            this.tvTemp.Nodes.Add(node);
            web.Close();
            site.Close();
            #endregion
 
        }
        /// <summary>
        /// 更改URL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbbApp_SelectedValueChanged(object sender, EventArgs e)
        {
      
            if (this.cbbApp.SelectedValue != null&&this.cbbApp.SelectedValue!="1")
            {
              SPWebApplication webApp = SPWebService.WebApplications[new Guid(this.cbbApp.SelectedValue.ToString())];
              #region 加载站点集
                List<ComboBoxModel> sites = new List<ComboBoxModel>();
                sites.Add(new ComboBoxModel() { ID = "1", Name = "--请选择--" });
                foreach (SPSite site in webApp.Sites)
                {
                    sites.Add(new ComboBoxModel() { ID = site.ID.ToString(), Name = site.Url });
               
                }

                this.cbSites.DataSource = sites;
                this.cbSites.DisplayMember = "Name";
                this.cbSites.ValueMember = "Id";
                this.cbSites.SelectedValueChanged += cbSites_SelectedValueChanged;
                #endregion
 
            }
        }
        void cbSites_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox cm = sender  as ComboBox;
            if (cm.SelectedValue != null&&cm.SelectedValue!="1")
            {
                using (SPSite site = new SPSite(new Guid(cm.SelectedValue.ToString())))
                {
                    cm.Tag = site;
                }
            }
           
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.lbtemp.Tag == null)
            {
                MessageBox.Show("你未选择模版!");
            }
            if (this.cbSites.Tag == null)
            {
                MessageBox.Show("你未选择站点集!");
            }
            try
            {
                SPWebTemplate t = this.lbtemp.Tag as SPWebTemplate;
                SPSite site = this.cbSites.Tag as SPSite;
                SPWeb web = site.AllWebs.Add(this.tbUrl.Text.Trim(), this.tbTitel.Text.Trim(), this.tbDesc.Text.Trim(), 2052,t, false, false);
                web.Close();
                site.Close();
            }
            catch (Exception ex)
            {

                MessageBox.Show("创建站点失败:" + ex.Message);
            }
            this.Cursor = Cursors.Default;
            ParentForm.BindTree();
        }
        void BindTemplateTree(TreeNode node,SPWebTemplateCollection temp)
        {
          
            foreach (SPWebTemplate t in temp)
            {
                  if(node.Text==t.DisplayCategory)
                  {
                         node.Nodes.Add(new TreeNode() { Text = t.Title, Tag = t });
                  }
            }    
        }
        private void tvTemp_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.lbtemp.Text="你已经选中:"+e.Node.Text;
            this.lbtemp.Tag = e.Node.Tag;
            if (e.Node.Tag != null)
            {
                SPWebTemplate t = e.Node.Tag as SPWebTemplate;
                lbDesc.Text = t.Description;
            }
        }
    }
}
后面写怎么去页面上添加与删除WebPart:
CreateWebPartdeleteWebPart
如上图一个添加WebPart一个删除已经有的WebPart,这里需要注意的是我目前是把页面的地址写死了
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using System.Xml;

namespace TestWF
{
    public partial class AddWebPart : Form
    {
        public Form2 ParentForm { get; set; }
        public AddWebPart()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Farm场
        /// </summary>
        public SPFarm Farm
        {
            get { return SPFarm.Local; }
        }
        /// <summary>
        /// 服务
        /// </summary>
        public SPWebService SPWebService {
            get { return  Farm.Services.GetValue<SPWebService>(""); }
        } 
        private void CreateApp_Load(object sender, EventArgs e)
        {
            #region 加载应用程序
            List<ComboBoxModel> list = new List<ComboBoxModel>();
            list.Add(new ComboBoxModel() { ID = "1", Name = "--请选择--" });
            foreach (SPWebApplication webApp in SPWebService.WebApplications)
            {
                list.Add(new ComboBoxModel() { ID = webApp.Id.ToString(), Name = webApp.Name });
            }
            this.cbbApp.DataSource = list;
            this.cbbApp.DisplayMember = "Name";
            this.cbbApp.ValueMember = "Id";
            this.cbbApp.SelectedValueChanged += cbbApp_SelectedValueChanged; 
            #endregion
 
        }
        /// <summary>
        /// 加载站点集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbbApp_SelectedValueChanged(object sender, EventArgs e)
        {
            if (this.cbbApp.SelectedValue != null&&this.cbbApp.SelectedValue!="1")
            {
                SPWebApplication webApp = SPWebService.WebApplications[new Guid(this.cbbApp.SelectedValue.ToString())];
               #region 加载站点集
                List<ComboBoxModel> sites = new List<ComboBoxModel>();
                sites.Add(new ComboBoxModel() { ID = "1", Name = "--请选择--" });
                foreach (SPSite site in webApp.Sites)
                {
                    sites.Add(new ComboBoxModel() { ID = site.ID.ToString(), Name = site.Url });
               
                }

                this.cbSites.DataSource = sites;
                this.cbSites.DisplayMember = "Name";
                this.cbSites.ValueMember = "Id";
                this.cbSites.SelectedValueChanged += cbSites_SelectedValueChanged;
                #endregion
            }
        }
        /// <summary>
        /// 加载站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbSites_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox cm = sender  as ComboBox;
            if (cm.SelectedValue != null&&cm.SelectedValue!="1")
            {
                using (SPSite site = new SPSite(new Guid(cm.SelectedValue.ToString())))
                {
                    cm.Tag = site;
                    #region 加载站点
                    List<ComboBoxModel> webs = new List<ComboBoxModel>();
                    webs.Add(new ComboBoxModel() { ID = "1", Name = "--请选择--" });
                    foreach (SPWeb web in site.AllWebs)
                    {
                        webs.Add(new ComboBoxModel() { ID = web.ID.ToString(), Name = web.Title });

                    }

                    this.cbbWeb.DataSource = webs;
                    this.cbbWeb.DisplayMember = "Name";
                    this.cbbWeb.ValueMember = "Id";
                    this.cbbWeb.SelectedValueChanged += cbbWeb_SelectedValueChanged;
                    #endregion
                } 
            } 
        } 
        /// <summary>
        /// 选择站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbbWeb_SelectedValueChanged(object sender, EventArgs e)
        {
              ComboBox cm = sender  as ComboBox;
              if (cm.SelectedValue != null && cm.SelectedValue != "1"&& this.cbSites.Tag!=null)
              {
                  using (SPSite site = new SPSite(new Guid(this.cbSites.SelectedValue.ToString())))
                  {
                      SPWeb web=site.AllWebs[new Guid(cm.SelectedValue.ToString())];
                      //本来在这里想继续加载站点中的所有页面的,由于暂时没找到怎么获取所有页面所以写死了
                      this.cbbPage.SelectedValueChanged += cbbPage_SelectedValueChanged;
                     
                      cm.Tag = web;

                      this.Cursor = Cursors.WaitCursor;
                      try
                      {
                          this.tvTemp.Nodes.Clear();
                          //根据站点获取所有WebPart并且加入树中
                          SPLimitedWebPartManager manger = web.GetLimitedWebPartManager("SitePages/Home.aspx", PersonalizationScope.Shared);
                          for (int i = 0; i < manger.WebParts.Count; i++)
                          {
                              TreeNode node = new TreeNode();
                              node.Text = manger.WebParts[i].Title;

                              node.Tag = manger.WebParts[0].ID;
                              this.tvTemp.Nodes.Add(node);
                          }
                      }
                      catch (Exception ex)
                      {
                          MessageBox.Show("错误:"+ex.Message);
                      } 
                      this.Cursor = Cursors.Default;
                  }

              }
        }
        /// <summary>
        /// 本来在这里想继续加载站点中的所有页面的,由于暂时没找到怎么获取所有页面所以写死了
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbbPage_SelectedValueChanged(object sender, EventArgs e)
        {
            ComboBox cm = sender  as ComboBox;
            if (cm.SelectedValue != null && cm.SelectedValue != "1" && this.cbbWeb.Tag != null)
            {
                SPWeb web = this.cbbWeb.Tag as SPWeb;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.tvTemp.Tag == null)
            {
                MessageBox.Show("你未选择WebPart!");
                return;

            }

            if (this.cbbWeb.Tag == null)
            {
                MessageBox.Show("你未选择站点集!");
                return;
            }
            try
            {
                string ID= this.tvTemp.Tag.ToString();
                SPWeb web = this.cbbWeb.Tag as SPWeb;

                try
                {
                    ///删除选中的一个WebPart
                    SPLimitedWebPartManager manger = web.GetLimitedWebPartManager("SitePages/Home.aspx", PersonalizationScope.Shared);
                    for (int i = 0; i < manger.WebParts.Count; i++)
                    {
                        if (manger.WebParts[i].ID == ID)
                        {
                            
                            manger.DeleteWebPart(manger.WebParts[i]);

                        }
                    }

                    MessageBox.Show("删除WebPart成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                } 
               
            }
            catch (Exception ex)
            {

                MessageBox.Show("失败:" + ex.Message);
            }
            this.Cursor = Cursors.Default;
            ParentForm.BindTree();
        }
        private void tvTemp_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.tvTemp.Tag = null;
            if (e.Node.Tag != null)
            {
                this.tvTemp.Tag =  e.Node.Tag;
                this.lbPart.Text = "你已经选中了:" + e.Node.Text;
               
                
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.tvTemp.Tag == null)
            {
                MessageBox.Show("你未选择WebPart!");
                return;

            }
            if (this.cbbWeb.Tag == null)
            {
                MessageBox.Show("你未选择站点集!");
                return;
            }
            try
            {
                //获取选中的WebPart列表中的其中一个SPFile
                SPFile file =this.tvTemp.Tag as  SPFile  ;
                SPWeb web = this.cbbWeb.Tag as SPWeb;
                 try
                {
                    //获取一个SPLimitedWebPartManager管理类
                 SPLimitedWebPartManager manger = web.GetLimitedWebPartManager("SitePages/Home.aspx", PersonalizationScope.Shared);

                 //创建一个WebPart 部件
                 XmlReader xmlReader = new XmlTextReader(file.OpenBinaryStream());
                 string errorMessage;
                 System.Web.UI.WebControls.WebParts.WebPart webPart = manger.ImportWebPart(xmlReader, out errorMessage);
                 
                 //将WebPart加载到页面上 其中后两个参数是设置页面位置的
                 manger.AddWebPart(webPart,"Left",2);
                  
                 MessageBox.Show("添加WebPart成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("错误:" + ex.Message);
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show("失败:" + ex.Message);
            }
            this.Cursor = Cursors.Default;
            ParentForm.BindTree();

        }
         /// <summary>
        /// 加载页面已经有的WebPart列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            this.tvTemp.Nodes.Clear();
            ComboBox cm = this.cbbWeb as  ComboBox;
            if (cm.SelectedValue != null && cm.SelectedValue != "1" && this.cbSites.Tag != null)
            {
                using (SPSite site = new SPSite(new Guid(this.cbSites.SelectedValue.ToString())))
                {
                    SPWeb web = site.AllWebs[new Guid(cm.SelectedValue.ToString())];

                    this.cbbPage.SelectedValueChanged += cbbPage_SelectedValueChanged;
                    cm.Tag = web;

                    this.Cursor = Cursors.WaitCursor;
                    try
                    {
                        //根据站点获取所有WebPart并且加入树中
                        SPLimitedWebPartManager manger = web.GetLimitedWebPartManager("SitePages/Home.aspx", PersonalizationScope.Shared);
                        for (int i = 0; i < manger.WebParts.Count; i++)
                        {
                            TreeNode node = new TreeNode();
                            node.Text = manger.WebParts[i].Title;
                      
                            node.Tag = manger.WebParts[0].ID;
                            this.tvTemp.Nodes.Add(node);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("错误:" + ex.Message);
                    } 
                   
                    this.Cursor = Cursors.Default;
                }

            }
        }

        /// <summary>
        /// 加载WebPart列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {

            if (this.cbbWeb.Tag != null  && this.cbSites.Tag != null)
            {
                this.Cursor = Cursors.WaitCursor;
                using (SPSite site = new SPSite(new Guid(this.cbSites.SelectedValue.ToString())))
                {
                    SPWeb web = site.AllWebs[new Guid(cbbWeb.SelectedValue.ToString())];

                    //获取所有的WebPart的SPList列表 注意这里返回的还是不是WebPart
                    SPList list = web.GetCatalog(SPListTemplateType.WebPartCatalog);
                    for (int i = 0; i < list.ItemCount; i++)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = list.Items[i].File.Title;
                        node.Tag = list.Items[i].File;
                        this.tvTemp.Nodes.Add(node);
                    }
                  

                }
                this.Cursor = Cursors.Default;
            }
        }
 
    }
 
}

以上就是怎么去删除和添加WebPart ,至于移动WebPart也差不多我就没写。

如果有更高的方法请大家告诉我。

posted on 2013-05-10 10:28  胖子哥哥  阅读(404)  评论(0编辑  收藏  举报