Thursday 28 August 2008

Custom Web Service to remove site on SharePoint 2007

Like site creation, site deletion can only be done remotely or from the server holds Sharepoint 2007. Because of this, we need to create a way of removing the sites remotely, avoiding issues. The best approach of this techique is to create your own web service, where you can call the local dll that holds Sharepoint instrucctions.

To do this you will need to activate AllowUnsafeUpdates = true; in order to be able to avoid messages like " (0x8102006D): The security validation for this page is invalid ". In this procedure you will need to pass two parameters, one will be the seed website, and the other the path of the seed plus the site you want to remove, so if for example you want to remove http://sheep/clients/666 (where "sheep" is the server), you will pass DeleteSite("http://sheep/clients", "http://sheep/clients/666");

///
/// It removes a shrepoint site.
///
/// Parent site(ie: http://sheep/clients )
/// Site to be deleted., this will remove http://sheep/clients/666 (ie: clients/666 )
/// success/fail
public static bool DeleteSite(string _sParentSiteURL,string _sSiteToBeDeleleted)
{
bool _bResult = false;
System.Diagnostics.EventLog _eLog = new System.Diagnostics.EventLog();
_eLog.Log = "Application";
_eLog.Source = "Application";

try
{
SPSite mySite = new SPSite(_sParentSiteURL);//SPContext.Current.Site;
SPWebCollection sites = mySite.AllWebs;
SPWeb _spwSite = sites[_sSiteToBeDeleleted];
_spwSite.AllowUnsafeUpdates = true;

_spwSite.Delete();

_bResult = true;

}
catch (Exception ex)
{
_bResult = false;
_eLog.WriteEntry("DeleteSite(...):::->" + ex.ToString(),System.Diagnostics.EventLogEntryType.Error);
}
return _bResult;
}


For the web service we will create a simple wrapper:

[WebMethod]
public bool DeleteSite(string _sParentSiteURL,string _sSiteToBeDeleted)
{
bool _bResult = false;
System.Diagnostics.EventLog _eLog = new System.Diagnostics.EventLog();
_eLog.Log = "Application";
_eLog.Source = "Application";

try
{
_bResult = SiteManager.SiteManager.DeleteSite(_sParentSiteURL,_sSiteToBeDeleted);
_eLog.WriteEntry("DeleteSite(...):::->" + _bResult.ToString(), System.Diagnostics.EventLogEntryType.SuccessAudit);
}
catch (Exception ex)
{
_bResult = false;
_eLog.WriteEntry("DeleteSite(...):::->" + ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
}

return _bResult;
}