MOSS 直接动态安装webPart到页面
感觉是不是很神奇?其实也很简单,主要用到SPLimitedWebPartManager这个类就OK拉
其实这个要注意的就是下面的WebPartXml 他就是 站点的webpart gallery描述,可能一个dll文件中存在多个webpart
在实际的开发中做一个Setup连部署人员都可以不用拉。。。HOHo。。。
string gallery = "";
gallery = gallery + "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
gallery = gallery + "<webParts>";
gallery = gallery + "<webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3/">";
gallery = gallery + "<metaData>";
gallery = gallery + "<type name=\"" + t.AssemblyQualifiedName + "\"/>";
gallery = gallery + "<importErrorMessage>Cannot import this web part.</importErrorMessage>";
gallery = gallery + "</metaData>";
gallery = gallery + "<data>";
gallery = gallery + "<properties>";
gallery = gallery + "<property name=\"Title\" type=\"string\">" + webpartTitle + "</property>";
gallery = gallery + "<property name=\"Description\" type=\"string\">" + webpartDesc + "</property>";
gallery = gallery + "</properties>";
gallery = gallery + "</data>";
gallery = gallery + "</webPart>";
gallery = gallery + "</webParts>";
private bool AddWebpartToPage(string TargetSiteUrl, string webPartXml, string ZoneID, int ZoneIndex,string Title,out string err)
{
bool flag = false;
SPLimitedWebPartManager manager = null;
if (TargetSiteUrl == "" || webPartXml == "" || ZoneID == "")
{
err = "001";
return false;
}
try
{
//重新启动IIS
Process p = new Process();
p.StartInfo.FileName = "iisreset.exe";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.WaitForExit();
SPSite sites = new SPSite(TargetSiteUrl);
SPWeb web = sites.RootWeb;
manager = web.GetLimitedWebPartManager(TargetSiteUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
StringReader input = new StringReader(webPartXml);
XmlTextReader reader2 = new XmlTextReader(input);
System.Web.UI.WebControls.WebParts.WebPart webpart = manager.ImportWebPart(reader2, out err);
webpart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
manager.AddWebPart(webpart, ZoneID, ZoneIndex);
web.Close();
this.SetTip("\"" + Title + "\"" + "安装完成");
flag = true;
}
catch (Exception exception)
{
err = exception.Message;
flag = false;
}
finally
{
if (manager != null)
{
manager.Dispose();
}
}
return flag;
}
大家看看是不是很简单。。。