using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebPartPages;
using System.IO;
using System.Xml;
using System.Web;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
namespace ConsoleApplication1
{
class Program
{
[SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
static void Main(string[] args)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://siteurlofsharepoint"))
{
using (SPWeb web = site.OpenWeb())
{
try
{
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request,
new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
string dwp = "";
XmlReader xmlReader = null;
SPQuery query = new SPQuery();
query.Query = String.Format("{0} ", "Recent_Discussions_.dwp");
SPList webPartGalary = null;
if (web.ParentWeb == null)
{
webPartGalary = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
using (SPWeb parentWeb = web.ParentWeb)
{
webPartGalary = parentWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}
}
SPListItemCollection webparts = webPartGalary.GetItems(query);
if (webparts != null && webparts.Count != 0)
{
Stream xmlStream = webparts[0].File.OpenBinaryStream();
StreamReader sReader = new StreamReader(xmlStream);
StringReader strReader = new StringReader(sReader.ReadToEnd());
xmlReader = XmlReader.Create(strReader);
//dwp = strReader.ToString();
}
//SPWebPartCollection collection = web.GetWebPartCollection("/PageLib/Default.aspx", Storage.Shared);
//collection.Add(dwp);
SPFile file = web.GetFile("http://dub-dev0001:11000/PageLib/Default.aspx");
//file.GetWebPartCollection(Storage.Shared);
SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
//SPLimitedWebPartManager manager = web.GetLimitedWebPartManager("Default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
string errMsg = string.Empty;
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request,
new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
System.Web.UI.WebControls.WebParts.WebPart wp = (System.Web.UI.WebControls.WebParts.WebPart)manager.ImportWebPart(xmlReader, out errMsg);
manager.AddWebPart(wp, "Left", 1);
manager.SaveChanges(wp);
web.Update();
}
catch (Exception ex)
{ }
}
}
});
}
}
}