SharePoint 使用代码创建 SPWeb/SPSiite/SPWebApplication以及WebPart添加到页面与删除 (二)

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

首先来写怎么去通过代码创建SPWebApplication,详细介绍我就写进代码注视:

      void CreateApp()
        {
            this.Cursor = Cursors.WaitCursor;
            
            //获取服务器场
            SPFarm farm =SPWebService.AdministrationService.Farm;
            
            SPWebApplicationBuilder webAppBld =new SPWebApplicationBuilder(farm);
            //设置应用程序ID
            webAppBld.Id = Guid.NewGuid();
        
            int port=new Random().Next(1000, 30000);
            //设置端口
            webAppBld.Port = port;

            
            DirectoryInfo rootDirInfo = new DirectoryInfo(@"C:\Inetpub\wwwroot\wss\VirtualDirectories\"+port);
            webAppBld.RootDirectory = rootDirInfo;
            webAppBld.ApplicationPoolId ="SharePoint Pool - " + port.ToString();

            //实例一个密码
            SecureString appPoolPwd = new SecureString();
            appPoolPwd.AppendChar('2');
            appPoolPwd.AppendChar('3');
            appPoolPwd.AppendChar('5');
            appPoolPwd.AppendChar('4');
            appPoolPwd.AppendChar('1');
            appPoolPwd.AppendChar('2');
            appPoolPwd.AppendChar('4');
            appPoolPwd.AppendChar('2');
            appPoolPwd.MakeReadOnly();
            webAppBld.IdentityType = IdentityType.SpecificUser;

            //设置 用户和密码
            webAppBld.ApplicationPoolUsername = "name";
            webAppBld.ApplicationPoolPassword = appPoolPwd;

            // the default is false so that Kerberos auth. is supported. If 
            // you're not using Kerberos, set this to true
            webAppBld.UseNTLMExclusively = true;

            // default is false
            webAppBld.AllowAnonymousAccess = false;

            // the default is false so that SSL is not used in IIS.
            // set this to true if the IIS web site hosting this web application
            // should use SSL
            webAppBld.UseSecureSocketsLayer = false;
           //设置默认备用访问映射
            Uri defaultZone = new Uri("http://"+System.Windows.Forms.SystemInformation.ComputerName+":"+port);
            webAppBld.DefaultZoneUri = defaultZone;

            webAppBld.CreateNewDatabase = true;
            //服务器地址
            webAppBld.DatabaseServer = @"JASON-PC\SharePoint";
            webAppBld.DatabaseName = "SharePoint - "+port;
            //设置数据库用户名设置为空或空字符串,使用Windows集成验证
            //如果你想使用SQL身份验证则设置用户名和密码DatabasePassword
          
            webAppBld.DatabaseUsername = String.Empty;
            SPWebApplication webApp = webAppBld.Create();
            webApp.Update();
            #region MyRegion
            //SPServer server = new SPServer("OSSRTM");

            // sharepoint服务器搜索实例
            //SPSearchService srchService =
            //    SPFarm.Local.Services.GetValue<SPSearchService>("SPSearch");

            //SPSearchServiceInstance searchServiceInst =
            //    (SPSearchServiceInstance)srchService.Instances[Guid.NewGuid()];

            //设置搜索服务实例爬行web应用程序
            //webAppBld.SearchServiceInstance = searchServiceInst; 
            #endregion
            this.Cursor = Cursors.Default;
            MessageBox.Show("创建应用程序成功!");
        }

写来写怎么根据一个应用程序创建站点集,这里需要知道的怎么去获取模版,下面图片是我的窗体:

CreateSite

然后附上代码:

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 System.Configuration;

namespace TestWF
{
    public partial class CreateSite : Form
    {
        public Form2 ParentForm { get; set; }
        public CreateSite()
        {
            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 加载模板选择
            //填写管理中心地址
            string url = ConfigurationSettings.AppSettings["管理中心"].ToString();
            SPSite site = new SPSite(url);
            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
            #region 配额模板
            //获取配额模版集合
            SPQuotaTemplateCollection spqc = SPWebService.QuotaTemplates;
            List<ComboBoxModel> model = new List<ComboBoxModel>();
            model.Add(new ComboBoxModel() { ID = string.Empty, Name = "无配额" });
            foreach (SPQuotaTemplate temp in spqc)
            {
                model.Add(new ComboBoxModel() { ID=temp.Value , Name=temp.Name });
            }
            this.cbbTemp.DataSource = model;
            this.cbbTemp.DisplayMember = "Name";
            this.cbbTemp.ValueMember = "Id";
       
            #endregion
        }
        /// <summary>
        /// 更改URL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cbbApp_SelectedValueChanged(object sender, EventArgs e)
        {
            this.lbAppURL.Text = "";
           if (this.cbbApp.SelectedValue != null&&this.cbbApp.SelectedValue!="1")
            {
                //获取当前的应用程序的主机头(访问映射)
                SPWebApplication webApp = SPWebService.WebApplications[new Guid(this.cbbApp.SelectedValue.ToString())];
                this.cbbApp.Tag = webApp;
                foreach (var set in webApp.IisSettings)
                {
                    if (set.Key == SPUrlZone.Default)
                    {
                        string HostHeader=string.Empty;
                        SPServerBinding spsb=set.Value.ServerBindings[0];
                        HostHeader=spsb.HostHeader;
                        if(HostHeader=="")
                        {
                            HostHeader="http://"+System.Windows.Forms.SystemInformation.ComputerName;
                        }
                        this.lbAppURL.Text += HostHeader + ":" + spsb.Port.ToString();
                    }
                }
            }
        }

        /// <summary>
        /// 判断是否选择/sites/
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            if (this.checkBox1.Checked)
            {
                this.tbUrl.Text = "/sites/"+ this.tbUrl.Text;
            }
            else
            {
                this.tbUrl.Text = this.tbUrl.Text.Replace("/sites/", "");
            }
          
        }
        /// <summary>
        /// 创建Site
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.lbtemp.Tag == null)
            {
                MessageBox.Show("你未选择模版!");
                return;
            }
            if (this.cbbApp.Tag == null)
            {
                MessageBox.Show("你未选择应用程序!"); return;
            }
            //获取选中的模版
            SPWebTemplate t =this.lbtemp.Tag as SPWebTemplate;
            //获取选择的SPWebApplication
            SPWebApplication webApp = this.cbbApp.Tag as SPWebApplication;
            //创建Site
            SPSite site = webApp.Sites.Add(this.tbUrl.Text.Trim(), this.tbTitel.Text.Trim(), this.tbDesc.Text.Trim(),
               2052,t.Name , this.tbUserOne.Text.Trim(), this.tbName.Text.Trim(), this.tbMail.Text.Trim());
            site.Close();
            this.Cursor = Cursors.Default;
            this.Close();
            ParentForm.BindTree();
        }
        /// <summary>
        /// 绑定模版树
        /// </summary>
        /// <param name="node"></param>
        /// <param name="temp"></param>
        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;
            }
        }
 
    }
    public class ComboBoxModel
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }
}

这一篇先到这里。下一篇写SPWeb的创建以及WebPart的创建以及动态添加到页面上以及删除。

原文地址:https://www.cnblogs.com/StudyHard/p/3070542.html