Alerts not moved when moving sites

A friend on mine recently came to me asking for a solution. They had an old site which was being used by a lot of people, then they decided to move it. As they did not had any kind of custom solutions or any other kind of customizations, STSADM export and import seemed to the straight forward way and that’s what they did.

But what happened? They lost the alert settings that everyone had for themselves over those hundreds of lists in the site and their sub-sites !! That too it was noticed after a day or so when some content has already been changed in the the sites.

I pointed him directly to the Technet article which tells about the issues that could happen with STSADM export and import and what is not saved. But he never read it and moved everything.

Now they wanted the alerts back but do not want to do their last days work again, which rules out a restore option from a day old backup. Finally, we settled that we will restore backup to a different sub-site in a farm and then write the code to copy over the alert information to the new site.

But where is the code?? Well, it is given below !!  Just provide 2 SPWeb objects, giving the source and destination and it will copy over your alert information.

    1: public void Copy(SPWeb sourceWeb, SPWeb destinationWeb)
    2: {
    3:     SPAlertCollection alerts = sourceWeb.Alerts;
    4:     foreach (SPAlert alert in alerts)
    5:     {
    6:         SPList list = destinationWeb.Lists[alert.List.Title];
    7:         Guid guid = destinationWeb.Alerts.Add(list, alert.EventType,
    8:         alert.AlertFrequency);
    9:         SPAlert newAlert = destinationWeb.Alerts[guid];
   10:         SPAlertTemplate template = new SPAlertTemplate();
   11:         template = alert.AlertTemplate;
   12:         template.Name = alert.AlertTemplate.Name;
   13:         newAlert.AlertTemplate = template;
   14:         newAlert.AlwaysNotify = alert.AlwaysNotify;
   15:         newAlert.DynamicRecipient = alert.DynamicRecipient;
   16:         newAlert.EventTypeBitmask = alert.EventTypeBitmask;
   17:         newAlert.Filter = alert.Filter;
   18:         newAlert.Title = alert.Title;
   19:         newAlert.Status = alert.Status;
   20:         newAlert.User = alert.User;
   21:         newAlert.Update();
   22:     }
   23: }

 

As always, Happy Coding image