Following code snippet can be used to add a media web part in an existing SharePoint website:
private void AddMediaWebPart()
{
const int zoneIndex = 0;
const string zoneId = "VideoRightZone";
var webPartGalleryAccessor = new WebPartGalleryAccessor();
var mediaWebPart = new MediaWebPart
{
MediaSource = "/sites/testsite/Documents/Video1.mp4",
AutoPlay = false,
Height = 220,
Width = 370,
Title = "Bicycle",
BackImageUrl = "/sites/testsite/PublishingImages/BicycleVideoImage.png",
ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal,
ChromeType =System.Web.UI.WebControls.WebParts.PartChromeType.None
};
webPartGalleryAccessor.AddMediaWebPartToSitePage(_rootSiteUrl, _subSiteUrl, _pageUrl, mediaWebPart, zoneId, zoneIndex);
}
{
const int zoneIndex = 0;
const string zoneId = "VideoRightZone";
var webPartGalleryAccessor = new WebPartGalleryAccessor();
var mediaWebPart = new MediaWebPart
{
MediaSource = "/sites/testsite/Documents/Video1.mp4",
AutoPlay = false,
Height = 220,
Width = 370,
Title = "Bicycle",
BackImageUrl = "/sites/testsite/PublishingImages/BicycleVideoImage.png",
ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal,
ChromeType =System.Web.UI.WebControls.WebParts.PartChromeType.None
};
webPartGalleryAccessor.AddMediaWebPartToSitePage(_rootSiteUrl, _subSiteUrl, _pageUrl, mediaWebPart, zoneId, zoneIndex);
}
WebPartGalleryAccessor Class:
public void AddMediaWebPartToSitePage(string rootSiteUrl, string subSiteUrl, string pageUrl, MediaWebPart webPart, string zoneId, int zoneIndex)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (var pageLoadSite = new SPSite(rootSiteUrl))
{
pageLoadSite.AllowUnsafeUpdates = true;
//using (var pageLoadWeb = pageLoadSite.OpenWeb(subSiteUrl))
using (var pageLoadWeb = pageLoadSite.OpenWeb())
{
pageLoadWeb.AllowUnsafeUpdates = true;
AddMediaWebPartToPage(pageLoadWeb, pageUrl, webPart, zoneId, zoneIndex);
pageLoadWeb.AllowUnsafeUpdates = false;
}
pageLoadSite.AllowUnsafeUpdates = false;
}
});
}
catch (Exception exception)
{
//throw new Exception("Unable to Add WebPart To Site Page: " + pageUrl + " Webpart title: " + webPart.Title + "Error: " + exception.Message);
}
}
private string AddMediaWebPartToPage(SPWeb web, string pageUrl, MediaWebPart webPart, string zoneId, int zoneIndex)
{
try
{
SPFile file = web.GetFile(pageUrl);
if (file.CheckOutType == SPFile.SPCheckOutType.None)
{
file.CheckOut();
}
using (SPLimitedWebPartManager manager = file.GetLimitedWebPartManager((PersonalizationScope)Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared))
{
manager.AddWebPart(webPart, zoneId, zoneIndex);
file.CheckIn("Webpart Added.");
return webPart.ID;
}
}
catch (Exception exception)
{
throw new Exception("Unable to Add WebPart To Page: " + pageUrl + " Webpart title: " + webPart.Title + "Error: " + exception.Message);
}
}