I have an publishing site collection using the enterprise wiki site collection template inside my sharepoint server 2013. And inside the root site of my site collection i added a custom list named "customers", and i added an event receiver which will get fired when a new item is added inside the customers list. the event receiver will create 2 wiki pages as follow:-
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
if (properties.List.Title.ToLower() == "customers")
{
PublishingSite pSite = new PublishingSite(properties.Site);
SPContentType ctype = pSite.ContentTypes["Enterprise Wiki Page"];
PageLayoutCollection pageLayouts = pSite.GetPageLayouts(ctype, true);
PageLayout pageLayout = pageLayouts["EnterpriseWiki.aspx"];
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(properties.Web);
///First page
PublishingPageCollection pPages = pWeb.GetPublishingPages();
PublishingPage pPage1 = pPages.Add(properties.ListItem.Title + " - About Customer.aspx", pageLayout);
SPListItem newpage1 = pPage1.ListItem;
newpage1["Title"] = properties.ListItem.Title+" - About Customer.aspx";//"Page added programmatically";
newpage1["PublishingPageContent"] = "<a href='/kb/CustomerServiceKB/Pages/" + properties.ListItem.Title + " - Main.aspx" + @"'>Back To Main Page</a> ";
///second Page
PublishingPage pPage = pPages.Add(properties.ListItem.Title + " - Main.aspx", pageLayout);
SPListItem newpage = pPage.ListItem;
newpage["Title"] = properties.ListItem.Title + " - Main.aspx";//"Page added programmatically";
newpage["PublishingPageContent"] =
@"<table class='ms-rteTable-default' cellspacing='0' style='width: 65%; height: 803px; text-align: left;'> //code goes here";
newpage.Update();
newpage1.Update();
}
}
}
}
now currently i test the above event receiver and it is working well. but as i know that based on MSDN recommendation it is not recommended to create new instances of SPSite
& SPWeb
inside event receiver https://msdn.microsoft.com/en-us/library/office/ee724407(v=office.14).aspx .
now in my above event receiver i am not sure about these 2 points:-
1) inside these 2 lines of code, am i violating the MSDN recommendations?? :-
PublishingSite pSite = new PublishingSite(properties.Site);
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(properties.Web);
since i am creating new instances of the PublishingSite
& PublishingWeb
?
2) now i try to do something as follow, to try to reference the current PublishingSite
directly from the SPItemEventProperties
:-
PublishingSite pSite = properties.Site;
instead of
PublishingSite pSite = new PublishingSite(properties.Site);
but i got this error:-
Cannot implicitly convert type 'Microsoft.SharePoint.SPSite' to 'Microsoft.SharePoint.Publishing.PublishingSite'
so can anyone adivce on my above two points,, so i can make my event receiver compatible with the MSDN recommendation of not creating new instances of SPSite
& SPWeb
inside the event receivers??
Thanks