using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Crm.SdkTypeProxy; using System.IO; using System.IO.Compression; public class CrmCustomizations { private CrmService _service = null; public CrmCustomizations(CrmService service) { _service = service; } public bool Backup(string filePath) { bool backedup = false; if (_service != null) { // grab all the customizations first ExportAllXmlRequest request = new ExportAllXmlRequest(); ExportAllXmlResponse response = _service.Execute(request) as ExportAllXmlResponse; byte[] data = Encoding.ASCII.GetBytes(response.ExportXml); // prepare the backup file if (File.Exists(filePath)) { File.Delete(filePath); } FileStream fs = File.Create(filePath); // check if we need to create a zip file bool createZip = Path.GetExtension(filePath).ToLower().Equals(".zip"); if (createZip) { GZipStream gzs = new GZipStream(fs, CompressionMode.Compress, true); gzs.Write(data, 0, data.Length); gzs.Close(); } else { fs.Write(data, 0, data.Length); } fs.Close(); backedup = true; } return backedup; } public bool Restore(string filePath) { bool restored = false; if (_service != null && File.Exists(filePath)) { string customizationXml = ReadData(filePath); if (!string.IsNullOrEmpty(customizationXml)) { ImportAllXmlRequest request = new ImportAllXmlRequest { CustomizationXml = customizationXml }; //_service.Execute(request); restored = true; } } return restored; } public bool Publish() { bool published = false; if (_service != null) { PublishAllXmlRequest request = new PublishAllXmlRequest(); _service.Execute(request); published = true; } return published; } private string ReadData(string filePath) { FileStream fs = File.Open(filePath, FileMode.Open); byte[] data = new byte[fs.Length]; bool isZip = Path.GetExtension(filePath).ToLower().Equals(".zip"); if (isZip) { GZipStream gzs = new GZipStream(fs, CompressionMode.Decompress, true); // decompress MemoryStream stream = new MemoryStream(); byte[] b = new byte[4096]; while (true) { int n = gzs.Read(b, 0, b.Length); if (n > 0) { stream.Write(b, 0, n); } else { break; } } data = stream.ToArray(); stream.Close(); gzs.Close(); } else { fs.Read(data, 0, data.Length); } fs.Close(); return Encoding.ASCII.GetString(data); } }