I'm trying to add a webpart to a publishing page after the page is created, so I've created an Event Receiver, the problem is, if I make the Event Receiver Synchronous (As it should be) the code executes successfully but the webparts are not added to the page, the only way I have found that works is making the event receiver async and do a Thread.Sleep before making the changes.
This is the code:
public override void ItemAdded(SPItemEventProperties properties){
base.ItemAdded(properties);
try
{
this.EventFiringEnabled = false;//Disable any other events while our event is beeing executed
//Thread.Sleep(2000);
var fileUrl = properties.ListItem.File.Url;
var webUrl = properties.Web.Url;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (var site = new SPSite(webUrl))
{
using (var web = site.OpenWeb())
{
bool unsafeUpdates = web.AllowUnsafeUpdates;
web.AllowUnsafeUpdates = true;
var file = web.GetFile(fileUrl);
var wpManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
if (wpManager.WebParts.Count == 0)
{
var idx = 0;
...add webparts
file.Update(); //I've also tried with web.Update()
}
web.AllowUnsafeUpdates = unsafeUpdates;
}
}
});
}
catch (Exception ex)
{
//Exception occurred
properties.Cancel = true;//We cancel the event
properties.Status = SPEventReceiverStatus.CancelWithError;//Set appropriate status
properties.ErrorMessage = ex.Message;//Set the error message
}
finally
{
this.EventFiringEnabled = true;//Regardless if the exception occurred or not, we have to enable earlier disabled events
}
}
Is there something wrong? how can I make the event receiver to work synchronously?