using System; using System.Runtime.InteropServices; using System.IO; using System.Collections.Generic; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Security; using System.Security.Permissions; using System.Globalization; using Microsoft.Win32; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Microsoft.SharePoint.WebPartPages; using Microsoft.SharePoint.Security; using System.Web.Util; namespace SPWorks.Toolkit.Common { public class SPWSiteCleanup { StringBuilder _errors = new StringBuilder(""); public Boolean CleanUpWeb(SPWeb spworksweb,String provisionFile) { if (spworksweb != null) { ArrayList retAr = GetAllFiles(spworksweb); Hashtable listRepHT = this.GetReplaceList(spworksweb, provisionFile); if (listRepHT.Count > 0) { for (int i = 0; i < retAr.Count; i++) { try { this.RestoreDataViewOutZone(spworksweb, (String)retAr[i], listRepHT); } catch (Exception cex) { throw new ApplicationException("CleanUpWeb:RestoreDataViewOutZone:File:" + (String)retAr[i] + cex.Message); } try { this.RestoreDataViewInZone(spworksweb, (String)retAr[i], listRepHT); } catch (Exception cex) { _errors.AppendLine ("CleanUpWeb:RestoreDataViewInZone:File:" + (String)retAr[i] + cex.Message); } } } this.RestoreWebProperties(spworksweb, provisionFile); this.RestoreCss(spworksweb, provisionFile); String fullErrMessage = _errors.ToString(); return true; } return false; } private ArrayList GetAllFiles(SPWeb web) { ArrayList al = new ArrayList(); EnumFiles(web.Files, ref al); EnumFolders(web.Folders, ref al); return al; } private void EnumFolders(SPFolderCollection fc, ref ArrayList al) { foreach (SPFolder fd in fc) { if (!(fd.Url.ToLower().Contains("_catalogs") && fd.Url.ToLower().Contains("forms")) && !fd.Url.ToLower().Contains("_cts") && !fd.Url.ToLower().Contains("private")) { EnumFiles(fd.Files, ref al); EnumFolders(fd.SubFolders, ref al); } } } private void EnumFiles(SPFileCollection fc, ref ArrayList al) { foreach (SPFile fl in fc) { if (fl.Url.ToLower().EndsWith(".aspx") || fl.Url.ToLower().EndsWith(".master")) al.Add(fl.Url); } } private void RestoreWebProperties(SPWeb web, string filePath) { if (!File.Exists(filePath) || web == null) { return; } XmlDocument doc = new XmlDocument(); try { doc.Load(filePath); } catch (XmlException) { return; } XmlNode xWebProperties = doc.DocumentElement.SelectSingleNode("WebProperties"); if (xWebProperties == null) { return; } foreach (XmlNode xWebProperty in xWebProperties.ChildNodes) { if (xWebProperty.Attributes["Key"] != null && xWebProperty.Attributes["Value"] != null) { string key = xWebProperty.Attributes["Key"].Value; string value = xWebProperty.Attributes["Value"].Value; if (web.Properties.ContainsKey(key)) { web.Properties[key] = value; } else { web.Properties.Add(key, value); } } } web.Properties.Update(); } private void RestoreCss(SPWeb web, string filePath) { if (!File.Exists(filePath) || web == null) { return; } XmlDocument doc = new XmlDocument(); try { doc.Load(filePath); } catch (XmlException) { return; } XmlNode xCustomizedCssFiles = doc.DocumentElement.SelectSingleNode("CustomizedCssFiles"); if (xCustomizedCssFiles == null) { return; } List customizedCssFiles = new List(); foreach (XmlNode xCustomizedCssFile in xCustomizedCssFiles.ChildNodes) { XmlAttribute xName = xCustomizedCssFile.Attributes["Name"]; if (xName == null) { continue; } customizedCssFiles.Add(xName.Value); } SPFolder rootFolder = web.RootFolder; SPFolder cssFolder = null; string targetFolder = "_styles"; foreach (SPFolder subFolder in rootFolder.SubFolders) { if (subFolder.Name.ToLower(CultureInfo.InvariantCulture) == targetFolder) { cssFolder = subFolder; break; } } if (cssFolder == null) { return; } foreach (SPFile file in cssFolder.Files) { if (customizedCssFiles.Contains(file.Name)) { web.CustomizeCss(file.Name); web.Update(); } } } private Boolean RestoreDataViewInZone(SPWeb web, string filePath, Hashtable repHT) { SPFile file = null; try { file = web.GetFile(filePath); if (file == null) { _errors.Append(filePath + "not found"); return false; } } catch (Exception ex) { _errors.Append("Exception:File:" + filePath + ":" + ex.Message ); return false; } SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); SPLimitedWebPartCollection pageWebParts = manager.WebParts; if (pageWebParts == null) { return true; } foreach (WebPart webPart in pageWebParts) { String newString = ""; if (!typeof(DataFormWebPart).IsInstanceOfType(webPart)) continue; DataFormWebPart dataForm = (DataFormWebPart)webPart; if (dataForm == null) { continue; } try { newString = SubstituteGuid(dataForm.ParameterBindings, repHT); dataForm.ParameterBindings = newString; } catch (Exception ex) { _errors.AppendLine("Exception:dataForm.ParameterBindings:" + filePath + ":" + ex.Message + ":" + newString); return false; } try { newString = SubstituteGuid(dataForm.DataSourcesString, repHT); dataForm.DataSourcesString = newString; } catch (Exception ex) { _errors.AppendLine("Exception:dataForm.DataSourcesString:" + filePath + ":" + ex.Message + ":" + newString); return false; } try { newString = SubstituteGuid(dataForm.Xsl, repHT); dataForm.Xsl = newString; } catch (Exception ex) { _errors.AppendLine("Exception:dataForm.Xsl:" + filePath + ":" + ex.Message + ":" + newString); return false; } try { manager.SaveChanges(dataForm); } catch (Exception ex) { _errors.AppendLine("Exception:dataForm.manager.SaveChanges:" + filePath + ":" + ex.Message + ":" + newString); return false; } } return true; } private Hashtable GetReplaceList(SPWeb web, String filePath) { Hashtable ht = new Hashtable(); XmlDocument doc = new XmlDocument(); try { doc.Load(filePath); } catch (XmlException) { return ht; } XmlNode xListInstances = doc.DocumentElement.SelectSingleNode("ListInstances"); if (xListInstances == null) { return ht; } foreach (XmlNode xListInstance in xListInstances.ChildNodes) { if (xListInstance.Attributes["Id"] == null || xListInstance.Attributes["Title"] == null) { continue; } string oldId = xListInstance.Attributes["Id"].Value; string title = xListInstance.Attributes["Title"].Value; SPList list = null; try { list = web.Lists[title]; } catch (ArgumentException) { continue; } if (list == null) { continue; } string newId = list.ID.ToString(); ht[newId] = oldId; } return ht; } private Hashtable GetReplaceList2(SPWeb web, String filePath) { Hashtable ht = new Hashtable(); XmlDocument doc = new XmlDocument(); try { doc.Load(filePath); } catch (XmlException) { return ht; } XmlNode xListInstances = doc.DocumentElement.SelectSingleNode("ListInstances"); if (xListInstances == null) { return ht; } foreach (XmlNode xListInstance in xListInstances.ChildNodes) { if (xListInstance.Attributes["Id"] == null || xListInstance.Attributes["Title"] == null) { continue; } string oldId = xListInstance.Attributes["Id"].Value; string title = xListInstance.Attributes["Title"].Value; SPList list = null; try { list = web.Lists[title]; } catch (ArgumentException) { continue; } if (list == null) { continue; } string newId = list.ID.ToString(); ht[newId] = oldId; } return ht; } private Boolean RestoreDataViewOutZone(SPWeb web, string filePath, Hashtable repHT) { SPFile file = web.GetFile(filePath); if (file == null) { return false; } string fileName = file.Name; string content = String.Empty; using (StreamReader reader = new StreamReader(file.OpenBinaryStream())) { content = reader.ReadToEnd(); content = SubstituteGuid(content, repHT); } UTF8Encoding encoder = new UTF8Encoding(); byte[] contentAsBytes = encoder.GetBytes(content); file.SaveBinary(contentAsBytes); return true; } private Boolean RestoreDataViewOutZone2(SPWeb web, string filePath, Hashtable repHT) { SPFile file = web.GetFile(filePath); if (file == null) { return false; } string fileName = file.Name; string content = String.Empty; using (StreamReader reader = new StreamReader(file.OpenBinaryStream())) { content = reader.ReadToEnd(); content = SubstituteGuid(content, repHT); } UTF8Encoding encoder = new UTF8Encoding(); byte[] contentAsBytes = encoder.GetBytes(content); // store to temporary file SPFile temp = web.Files.Add("temp.aspx", contentAsBytes); SPLimitedWebPartManager sourceManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); SPLimitedWebPartCollection sourceWebParts = sourceManager.WebParts; SPLimitedWebPartManager targetManager = temp.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in sourceWebParts) { string zoneId = sourceManager.GetZoneID(webPart); targetManager.AddWebPart(webPart, zoneId, webPart.ZoneIndex); } foreach (SPWebPartConnection connection in sourceManager.SPWebPartConnections) { targetManager.SPConnectWebParts(connection.Provider, connection.ProviderConnectionPoint, connection.Consumer, connection.ConsumerConnectionPoint, connection.Transformer); } file.Delete(); temp.CopyTo(filePath); temp.Delete(); web.Update(); return true; } public string SubstituteGuid(string content, Hashtable repHT) { foreach (DictionaryEntry di in repHT) { String oldId = (String)di.Value; String newId = (String)di.Key; content = Regex.Replace(content, oldId, newId, RegexOptions.IgnoreCase); } return content; } } }