private ExportSolutionRequest ExportSolutionMapping(DataGridViewRow dataGridRow) { string targetVersionItem = comboBox1.SelectedItem.ToString(); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.SolutionName = (string)dataGridRow.Cells["Solution"].Value; if (!targetVersionItem.Contains("9.")) { exportSolutionRequest.TargetVersion = targetVersionItem; } if (checkedListBox1.CheckedItems.Count == 0) { return(exportSolutionRequest); } for (var x = 0; x <= checkedListBox1.CheckedItems.Count - 1; x++) { var checkedItem = checkedListBox1.CheckedItems[x].ToString(); exportSolutionRequest.ExportAutoNumberingSettings = this.checkedListBox1.Items[0].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportCalendarSettings = this.checkedListBox1.Items[1].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportCustomizationSettings = this.checkedListBox1.Items[2].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportEmailTrackingSettings = this.checkedListBox1.Items[3].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportGeneralSettings = this.checkedListBox1.Items[4].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportIsvConfig = this.checkedListBox1.Items[5].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportMarketingSettings = this.checkedListBox1.Items[6].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportOutlookSynchronizationSettings = this.checkedListBox1.Items[7].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportRelationshipRoles = this.checkedListBox1.Items[8].Equals(checkedItem) ? true : false; exportSolutionRequest.ExportSales = this.checkedListBox1.Items[9].Equals(checkedItem) ? true : false; } return(exportSolutionRequest); }
private void ExportUnmanagedSolution(SolutionPackageConfig config, string filePath) { var request = new ExportSolutionRequest { SolutionName = config.solution_uniquename, ExportAutoNumberingSettings = false, ExportCalendarSettings = false, ExportCustomizationSettings = false, ExportEmailTrackingSettings = false, ExportExternalApplications = false, ExportGeneralSettings = false, ExportIsvConfig = false, ExportMarketingSettings = false, ExportOutlookSynchronizationSettings = false, ExportRelationshipRoles = false, ExportSales = false, Managed = false }; var response = (ExportSolutionResponse)_service.Execute(request); // Save solution using (var fs = File.Create(filePath)) { fs.Write(response.ExportSolutionFile, 0, response.ExportSolutionFile.Length); } }
protected override void ProcessRecord() { base.ProcessRecord(); base.WriteVerbose(string.Format("Exporting Solution: {0}", UniqueSolutionName)); var solutionFile = new StringBuilder(); Solution solution; using (var context = new CIContext(OrganizationService)) { var query = from s in context.SolutionSet where s.UniqueName == UniqueSolutionName select s; solution = query.FirstOrDefault(); } if (solution == null) { throw new Exception(string.Format("Solution {0} could not be found", UniqueSolutionName)); } solutionFile.Append(UniqueSolutionName); if (IncludeVersionInName) { solutionFile.Append("_"); solutionFile.Append(solution.Version.Replace(".", "_")); } if (Managed) { solutionFile.Append("_managed"); } solutionFile.Append(".zip"); var exportSolutionRequest = new ExportSolutionRequest { Managed = Managed, SolutionName = UniqueSolutionName, ExportAutoNumberingSettings = ExportAutoNumberingSettings, ExportCalendarSettings = ExportCalendarSettings, ExportCustomizationSettings = ExportCustomizationSettings, ExportEmailTrackingSettings = ExportEmailTrackingSettings, ExportGeneralSettings = ExportGeneralSettings, ExportIsvConfig = ExportIsvConfig, ExportMarketingSettings = ExportMarketingSettings, ExportOutlookSynchronizationSettings = ExportOutlookSynchronizationSettings, ExportRelationshipRoles = ExportRelationshipRoles }; var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse; string solutionFilePath = Path.Combine(OutputFolder, solutionFile.ToString()); File.WriteAllBytes(solutionFilePath, exportSolutionResponse.ExportSolutionFile); base.WriteObject(solutionFile.ToString()); }
//Start of Main static public void Main(string[] args) { Console.WriteLine("The process has started \nTrying to Export Solution"); //Create new user and gets credentials to login and capture desired solution Session loginUser = new Session(); ClientCredentials credentials = GetCredentials(loginUser); using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(loginUser.OrganizationUri, null, credentials, GetDeviceCredentials())) { string outputDir = @"C:\temp\"; //Creates the Export Request ExportSolutionRequest exportRequest = new ExportSolutionRequest(); exportRequest.Managed = true; exportRequest.SolutionName = loginUser.SolutionName; ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest); //Handles the response byte[] exportXml = exportResponse.ExportSolutionFile; string filename = loginUser.SolutionName + "_" + DateToString() + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution Successfully Exported to {0}", outputDir + filename); } }
private ExportSolutionRequest PrepareExportRequest(Entity solution) { var request = new ExportSolutionRequest { Managed = Settings.Instance.Managed, SolutionName = solution.GetAttributeValue <string>("uniquename"), ExportAutoNumberingSettings = Settings.Instance.ExportAutoNumberingSettings, ExportCalendarSettings = Settings.Instance.ExportCalendarSettings, ExportCustomizationSettings = Settings.Instance.ExportCustomizationSettings, ExportEmailTrackingSettings = Settings.Instance.ExportEmailTrackingSettings, ExportGeneralSettings = Settings.Instance.ExportGeneralSettings, ExportIsvConfig = Settings.Instance.ExportIsvConfig, ExportMarketingSettings = Settings.Instance.ExportMarketingSettings, ExportOutlookSynchronizationSettings = Settings.Instance.ExportOutlookSynchronizationSettings, ExportRelationshipRoles = Settings.Instance.ExportRelationshipRoles, ExportSales = Settings.Instance.ExportSales }; if (ConnectionDetail.OrganizationMajorVersion >= 8) { request.ExportExternalApplications = Settings.Instance.ExportExternalApplications; } progressItems.Add(request, new ProgressItem { Type = Enumerations.RequestType.Export, Detail = sourceDetail, Solution = solution.GetAttributeValue <string>("friendlyname"), Request = request }); return(request); }
private string UnPackSolution(SolutionPackageConfig solutionPackagerConfig, string targetFolder) { // Extract solution var request = new ExportSolutionRequest { SolutionName = solutionPackagerConfig.solution_uniquename, ExportAutoNumberingSettings = false, ExportCalendarSettings = false, ExportCustomizationSettings = false, ExportEmailTrackingSettings = false, ExportExternalApplications = false, ExportGeneralSettings = false, ExportIsvConfig = false, ExportMarketingSettings = false, ExportOutlookSynchronizationSettings = false, ExportRelationshipRoles = false, ExportSales = false, Managed = solutionPackagerConfig.packagetype == PackageType.managed }; var response = (ExportSolutionResponse)_service.Execute(request); // Save solution var solutionZipPath = Path.GetTempFileName(); File.WriteAllBytes(solutionZipPath, response.ExportSolutionFile); UnpackSolutionZip(solutionPackagerConfig, targetFolder, solutionZipPath); return(targetFolder); }
//Start of Main public static void Main(string[] args) { Console.WriteLine("The process has started \nTrying to Export Solution"); //Create new user and gets credentials to login and capture desired solution Session loginUser = new Session(); ClientCredentials credentials = GetCredentials(loginUser); using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(loginUser.OrganizationUri,null, credentials, GetDeviceCredentials())) { string outputDir = @"C:\temp\"; //Creates the Export Request ExportSolutionRequest exportRequest = new ExportSolutionRequest(); exportRequest.Managed = true; exportRequest.SolutionName = loginUser.SolutionName; ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest); //Handles the response byte[] exportXml = exportResponse.ExportSolutionFile; string filename = loginUser.SolutionName + "_" + DateToString() + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution Successfully Exported to {0}", outputDir + filename); } }
/// <summary> /// Экспортируем решение /// </summary> /// <param name="uniquename"></param> /// <param name="service"></param> /// <param name="enviroment"></param> public static void ExportSolution(string uniquename, IOrganizationService service, string enviroment) { ExportSolutionRequest request = new ExportSolutionRequest { Managed = false, SolutionName = uniquename }; ExportSolutionResponse response = (ExportSolutionResponse)service.Execute(request); byte[] exportXml = response.ExportSolutionFile; string filename = string.Empty; switch (enviroment) { case "Customization": filename = uniquename + ".zip"; break; case "Import": filename = uniquename + enviroment + ".zip"; break; } DirectoryHandler.SetZipPath(DirectoryHandler.TempPath + "\\" + filename, enviroment); File.WriteAllBytes(DirectoryHandler.CurrentBackupPath + "\\" + filename, exportXml); File.WriteAllBytes(DirectoryHandler.TempPath + "\\" + filename, exportXml); }
public static void TransferSolution(CrmOrganization sourceOrg, CrmOrganization targetOrg, string solutionUniqueName, Guid?importJobId = null) { Log.Text($"Transfering solution {solutionUniqueName}..."); if (importJobId == null) { importJobId = Guid.NewGuid(); } ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solutionUniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)sourceOrg.Service.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = exportXml, ImportJobId = (Guid)importJobId }; targetOrg.Service.Execute(impSolReq); }
public static string[] DownloadSolutionFile(CrmOrganization org, string uniqueName) { var qa = new QueryByAttribute("solution"); qa.AddAttributeValue("uniquename", uniqueName); qa.ColumnSet = new ColumnSet("version"); var entities = org.Service.RetrieveMultiple(qa).Entities; if (entities.Count != 0) { var version = entities[0].GetAttributeValue <string>("version"); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = uniqueName; ExportSolutionResponse resp = (ExportSolutionResponse)org.Service.Execute(exportSolutionRequest); byte[] exportXml = resp.ExportSolutionFile; string filename = $"{uniqueName}_{version.Replace(".","_")}.zip"; string filePath = Path.Combine("c:/temp", filename); File.WriteAllBytes(filePath, exportXml); return(new string[] { filePath, version }); } return(null); }
private SolutionFileInfo ExportSolution(OrganizationServiceProxy serviceProxy, string solutionUnqiueName, string owner, string message) { string filename; ExportSolutionRequest exportRequest = new ExportSolutionRequest(); exportRequest.Managed = true; exportRequest.SolutionName = solutionUnqiueName; Console.WriteLine("Downloading Solutions"); ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest); //Handles the response byte[] downloadedSolutionFile = exportResponse.ExportSolutionFile; filename = solutionUnqiueName + "_" + ".zip"; File.WriteAllBytes(RepositoryLocalFolder + filename, downloadedSolutionFile); SolutionFileInfo solutionFile = new SolutionFileInfo(); solutionFile.SolutionFilePath = RepositoryLocalFolder + filename; solutionFile.OwnerName = owner; solutionFile.Message = message; solutionFile.SolutionUniqueName = solutionUnqiueName; Console.WriteLine("Solution Successfully Exported to {0}", filename); return(solutionFile); }
public string[] ExportSolution(string solutionUniqueName) { string folder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "solutions"); if (!System.IO.Directory.Exists(folder)) { System.IO.Directory.CreateDirectory(folder); } int lastFileVersionNumber = GetLastVersionNumber(solutionUniqueName, folder); string[] result = new string[2]; ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solutionUniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmSvc.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; if (lastFileVersionNumber != 0) { result[0] = folder + "/" + solutionUniqueName + lastFileVersionNumber.ToString() + ".zip"; } lastFileVersionNumber++; result[1] = folder + "/" + solutionUniqueName + lastFileVersionNumber.ToString() + ".zip"; System.IO.File.WriteAllBytes(result[1], exportXml); return(result); }
/// <summary> /// Method to export a solution from Dynamics CRM. /// </summary> /// <param name="outputDir">The path in which the exported solution file should be placed.</param> /// <param name="solutionUniqueName">The unique name of the solution to export.</param> /// <param name="managed">Should the solution being exported generate a managed or unmanaged solution file.</param> /// <returns>The file name as a string (not the path as that was an input parameter).</returns> public string ExportSolution(string outputDir, string solutionUniqueName, bool managed) { try { if (!string.IsNullOrEmpty(outputDir) && !outputDir.EndsWith(@"\", false, CultureInfo.CurrentCulture)) { outputDir += @"\"; } string ManagedStatus; if (managed) { ManagedStatus = "Managed"; } else { ManagedStatus = "UnManaged"; } ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = managed; exportSolutionRequest.SolutionName = solutionUniqueName; ExportSolutionResponse exportSolutionResponse; using (XrmService service = new XrmService(XRMConnectionString)) { exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest); } byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solutionUniqueName + "_" + ManagedStatus + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); return(filename); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
private void DownloadSolution(BackgroundWorker worker, DoWorkEventArgs args) { var @params = args.Argument as DownloadSolutionParams ?? throw new ArgumentNullException(nameof(args.Argument)); ExportSolutionRequest request = new ExportSolutionRequest() { SolutionName = @params.Solution.UniqueName, Managed = @params.Managed, ExportAutoNumberingSettings = @params.ExportAutoNumberingSettings, ExportCalendarSettings = @params.ExportCalendarSettings, ExportCustomizationSettings = @params.ExportCustomizationSettings, ExportEmailTrackingSettings = @params.ExportEmailTrackingSettings, ExportExternalApplications = @params.ExportExternalApplications, ExportGeneralSettings = @params.ExportGeneralSettings, ExportIsvConfig = @params.ExportIsvConfig, ExportMarketingSettings = @params.ExportMarketingSettings, ExportOutlookSynchronizationSettings = @params.ExportOutlookSynchronizationSettings, ExportRelationshipRoles = @params.ExportRelationshipRoles, ExportSales = @params.ExportSales }; var response = solutionPackagerControl.Service.Execute(request) as ExportSolutionResponse; string filePath = Path.Combine(@params.ZipDirectory, $"{@params.Solution.UniqueName}_{@params.Solution.Version.ToString().Replace(".", "_")}.zip"); using (FileStream writer = File.Create(filePath)) { writer.Write(response.ExportSolutionFile, 0, response.ExportSolutionFile.Length); } @params.SolutionPackagerParameters.ZipFile = new FileInfo(filePath).FullName; args.Result = @params.SolutionPackagerParameters; }
/// <summary> /// Method exports solution /// </summary> /// <param name="serviceProxy">organization service proxy</param> /// <param name="solutionFile">solution file info</param> /// <param name="solutionName">solution name</param> /// <param name="message">message to be printed on console</param> /// <param name="isManaged">Managed Property</param> private void ExportSolution(IOrganizationService serviceProxy, SolutionFileInfo solutionFile, string solutionName, string message, bool isManaged) { try { ExportSolutionRequest exportRequest = new ExportSolutionRequest { Managed = isManaged, SolutionName = solutionName }; Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + message + solutionName + "<br>"); ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest); // Handles the response byte[] downloadedSolutionFile = exportResponse.ExportSolutionFile; if (isManaged) { solutionFile.SolutionFilePathManaged = Path.GetTempFileName(); File.WriteAllBytes(solutionFile.SolutionFilePathManaged, downloadedSolutionFile); } else { solutionFile.SolutionFilePath = Path.GetTempFileName(); File.WriteAllBytes(solutionFile.SolutionFilePath, downloadedSolutionFile); } string solutionExport = string.Format("Solution Successfully Exported to {0}", solutionName); Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + solutionExport + "<br>"); } catch (Exception ex) { Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + ex.Message + "<br>"); throw ex; } }
/// <summary> /// Downloads the CRM Solution /// </summary> /// <param name="crmServiceClient">CRM Service Client</param> /// <param name="crmSolutionName">CRM Solution Name</param> /// <param name="filePath">File Path</param> /// <param name="isManaged">Defines if the Solution should be downloaded Managed</param> public void DownloadSolution(CrmServiceClient crmServiceClient, string crmSolutionName, string filePath, bool isManaged = false) { ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest { Managed = isManaged, SolutionName = crmSolutionName }; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmServiceClient.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename; if (isManaged) { filename = Path.Combine(filePath, crmSolutionName + "_managed.zip"); } else { filename = Path.Combine(filePath, crmSolutionName + ".zip"); } File.WriteAllBytes(filename, exportXml); }
private SolutionPackagerCaller.Parameters DownloadSolutionInner(Parameters @params) { foreach (var managed in @params.Managed) { ExportSolutionRequest request = new ExportSolutionRequest() { SolutionName = @params.Solution.UniqueName, Managed = managed, ExportAutoNumberingSettings = @params.ExportAutoNumberingSettings, ExportCalendarSettings = @params.ExportCalendarSettings, ExportCustomizationSettings = @params.ExportCustomizationSettings, ExportEmailTrackingSettings = @params.ExportEmailTrackingSettings, ExportExternalApplications = @params.ExportExternalApplications, ExportGeneralSettings = @params.ExportGeneralSettings, ExportIsvConfig = @params.ExportIsvConfig, ExportMarketingSettings = @params.ExportMarketingSettings, ExportOutlookSynchronizationSettings = @params.ExportOutlookSynchronizationSettings, ExportRelationshipRoles = @params.ExportRelationshipRoles, ExportSales = @params.ExportSales }; var response = solutionPackagerControl.Service.Execute(request) as ExportSolutionResponse; string filePath = Path.Combine(@params.ZipDirectory, $"{@params.Solution.UniqueName}_{@params.Solution.Version.ToString().Replace(".", "_")}{(managed ? "_managed" : "")}.zip"); using (FileStream writer = File.Create(filePath)) { writer.Write(response.ExportSolutionFile, 0, response.ExportSolutionFile.Length); } @params.SolutionPackagerParameters.ZipFile = new FileInfo(filePath).FullName; } return(@params.SolutionPackagerParameters); }
public string ExportSolution( string outputFolder, SolutionExportOptions options) { Logger.LogVerbose("Exporting Solution: {0}", options.SolutionName); var solutionFile = new StringBuilder(); Solution solution = GetSolution(options.SolutionName, new ColumnSet("version")); solutionFile.Append(options.SolutionName); if (options.IncludeVersionInName) { solutionFile.Append("_"); solutionFile.Append(solution.Version.Replace(".", "_")); } if (options.Managed) { solutionFile.Append("_managed"); } solutionFile.Append(".zip"); var exportSolutionRequest = new ExportSolutionRequest { Managed = options.Managed, SolutionName = options.SolutionName, ExportAutoNumberingSettings = options.ExportAutoNumberingSettings, ExportCalendarSettings = options.ExportCalendarSettings, ExportCustomizationSettings = options.ExportCustomizationSettings, ExportEmailTrackingSettings = options.ExportEmailTrackingSettings, ExportGeneralSettings = options.ExportGeneralSettings, ExportIsvConfig = options.ExportIsvConfig, ExportMarketingSettings = options.ExportMarketingSettings, ExportOutlookSynchronizationSettings = options.ExportOutlookSynchronizationSettings, ExportRelationshipRoles = options.ExportRelationshipRoles, ExportSales = options.ExportSales, TargetVersion = options.TargetVersion, }; //keep seperate to allow compatibility with crm2015 if (options.ExportExternalApplications) { exportSolutionRequest.ExportExternalApplications = options.ExportExternalApplications; } var exportSolutionResponse = OrganizationService.Execute(exportSolutionRequest) as ExportSolutionResponse; string solutionFilePath = Path.Combine(outputFolder, solutionFile.ToString()); File.WriteAllBytes(solutionFilePath, exportSolutionResponse.ExportSolutionFile); Logger.LogInformation("Solution Zip Size: {0}", FileUtilities.GetFileSize(solutionFilePath)); return(solutionFilePath); }
public static void ExportSolution(IOrganizationService service, string uniqueName, string path, bool managed) { ExportSolutionRequest req = new ExportSolutionRequest() { Managed = managed, SolutionName = uniqueName, }; var response = (ExportSolutionResponse)service.Execute(req); File.WriteAllBytes(path, response.ExportSolutionFile); }
private byte[] ExportSolutionAndGetBodyBinary(string solutionUniqueName) { ExportSolutionRequest request = new ExportSolutionRequest() { SolutionName = solutionUniqueName, Managed = false, }; var response = (ExportSolutionResponse)_service.Execute(request); return(response.ExportSolutionFile); }
private static byte[] ExportSolution(string solutionName, IOrganizationService service, bool exportSolutionType) { var exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = exportSolutionType; exportSolutionRequest.SolutionName = solutionName; var exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; return(exportXml); }
private byte[] ExportSolution(IOrganizationService service) { var exportSolutionRequest = new ExportSolutionRequest { Managed = false, SolutionName = SolutionName }; var result = (ExportSolutionResponse)service.Execute(exportSolutionRequest); return(result.ExportSolutionFile); }
private byte[] GetSolutionFile() { var req = new ExportSolutionRequest() { Managed = false, SolutionName = SolutionUniqueName }; var resp = (ExportSolutionResponse)Crm.Service.Execute(req); return(resp.ExportSolutionFile); }
public static void ExportSolution(this OrganizationService crm, string solutionName, string exportFileName, SolutionExportType exportType) { crm.Execute(new PublishAllXmlRequest()); var export = new ExportSolutionRequest() { SolutionName = solutionName, Managed = (exportType == SolutionExportType.Managed) }; var response = (ExportSolutionResponse)crm.Execute(export); File.WriteAllBytes(exportFileName, response.ExportSolutionFile); }
public static void Main(String SolutionCreatePath, String SolutionToExport, bool ManagedSolution, String CrmUrl, String Organization) { try { using (_client = new CrmServiceClient("Url=" + CrmUrl + Organization + "; authtype=AD; RequireNewInstance=True;")) { try { Console.WriteLine("----------------------------------------------------------------------"); if (_client.IsReady == false) { Console.WriteLine("No se pudo establecer la conexion verifique la fuente"); return; } string solutionName = ""; string outputDir = SolutionCreatePath; XmlTextReader xmlReader = new XmlTextReader(SolutionToExport); while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Text: solutionName = xmlReader.Value; Console.WriteLine("Generando solucion..." + Environment.NewLine); ExportSolutionRequest exportedSolution = new ExportSolutionRequest(); exportedSolution.Managed = ManagedSolution; exportedSolution.SolutionName = solutionName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_client.Execute(exportedSolution); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = exportedSolution.SolutionName + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solucion exportada {0}.", outputDir + filename + Environment.NewLine); break; } } } catch (FaultException <OrganizationServiceFault> ex) { Console.WriteLine("Ocurrio un error: " + ex.Message); } } } catch (FaultException <OrganizationServiceFault> ex) { string message = ex.Message; throw; } }
/// <summary> /// Exports solution as unmanaged /// </summary> /// <param name="orgService"></param> /// <returns></returns> public static byte[] ExportSolution(IOrganizationService orgService, string solutionName) { ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solutionName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)orgService.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; return(exportXml); }
private string GetSolutionFromCrm() { if (json.type.ToLower().Trim() == "Extract".ToLower()) { var timer = Stopwatch.StartNew(); var fileName = Utility.FormatSolutionVersionString(json.solution, System.Version.Parse(CrmVersion), json.solutiontype); var solutionFile = Path.Combine(currentDirectory, json.folder, "Solutions-Extract", fileName); CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, "Export ", CliLog.ColorCyan, json.solutiontype, CliLog.ColorGreen, " solution: ", CliLog.ColorCyan, json.solution, CliLog.ColorGreen, " to: ", CliLog.ColorCyan, solutionFile); CliLog.WriteLine(CliLog.ColorWhite, "|"); var request = new ExportSolutionRequest { Managed = json.solutiontype == "Managed", SolutionName = json.solution }; try { var wait = new Thread(ThreadWork.SolutionPackagerDots); wait.Start(); var response = (ExportSolutionResponse)crmServiceClient.Execute(request); wait.Abort(); CliLog.WriteLine(); var tempFile = Utility.WriteTempFile(fileName, response.ExportSolutionFile); var dir = Path.GetDirectoryName(solutionFile); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Copy(tempFile, solutionFile, true); CliLog.WriteLine(CliLog.ColorWhite, "|"); CliLog.WriteLine(CliLog.ColorWhite, "|", CliLog.ColorGreen, $"Solution exported in {timer.Elapsed:c}"); CliLog.WriteLine(CliLog.ColorWhite, "|"); return(solutionFile); } catch (TimeoutException te) { CliLog.WriteLine(CliLog.ColorWhite, "|"); CliLog.WriteLine(CliLog.ColorWhite, "|"); CliLog.WriteLine(ConsoleColor.White, te.Message); CliLog.WriteLine(CliLog.ColorWhite, "|"); CliLog.WriteLine(CliLog.ColorWhite, "|"); CliLog.WriteLine(ConsoleColor.Red, "!!! [SOLUTION-PACKAGER] FAILED !!!"); throw; } } else { var fileName = Utility.FormatSolutionVersionString(json.solution, System.Version.Parse(CrmVersion), json.solutiontype); var solutionFile = Path.Combine(currentDirectory, json.folder, "Solutions-Pack", fileName); return(solutionFile); } }
private void ExportSolution(AnalysisArgs analysisargs, Solution solution) { if (LastExportTry == solution) { ShowError($"Failed to export {solution}"); return; } LastExportTry = solution; Enable(false); var solname = solution.UniqueName; WorkAsync(new WorkAsyncInfo { Message = $"Exporting {solname}", AsyncArgument = solname, Work = (worker, args) => { var sol = args.Argument as string; var req = new ExportSolutionRequest { SolutionName = sol, Managed = false }; args.Result = Service.Execute(req) as ExportSolutionResponse; }, PostWorkCallBack = (args) => { if (args.Error != null) { ShowError(args.Error); } else if (args.Result is ExportSolutionResponse resp) { var exportXml = resp.ExportSolutionFile; var filepath = WorkingFolder; var filename = $"{solname} {solution.Version}"; var fullpath = Path.Combine(filepath, filename + ".zip"); int i = 0; while (File.Exists(fullpath)) { fullpath = Path.Combine(filepath, $"{filename} ({++i}).zip"); } File.WriteAllBytes(fullpath, exportXml); solution.LocalFilePath = fullpath; } Enable(true); SendAnalysis(analysisargs); } });
private void ExportSolution(CrmConnection connection) { if (string.IsNullOrWhiteSpace(this.Extension)) { Log.LogError("Required parameter missing: Extension"); return; } string directoryPath = string.IsNullOrEmpty(this.Path) ? System.IO.Path.GetDirectoryName(this.BuildEngine.ProjectFileOfTaskNode) : this.Path; // ReSharper disable once AssignNullToNotNullAttribute string solutioneFile = string.Format(CultureInfo.CurrentCulture, "{0}.{1}", System.IO.Path.Combine(directoryPath, this.Name), this.Extension); using (var serviceContext = new CrmOrganizationServiceContext(connection)) { try { var exportSolutionRequest = new ExportSolutionRequest { SolutionName = this.Name, Managed = this.ExportAsManagedSolution }; Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Exporting Solution {0}. Please wait...", this.Name)); var response = serviceContext.Execute(exportSolutionRequest) as ExportSolutionResponse; if (response == null) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred in in exporting Solution {0} from organization with Url {1}.", this.Name, this.OrganizationUrl)); } else { byte[] exportSolutionFileContentsBytes = response.ExportSolutionFile; File.WriteAllBytes(solutioneFile, exportSolutionFileContentsBytes); Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully exported Solution {0} from organization with Url {1}.", this.Name, this.OrganizationUrl)); } } catch (Exception exception) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "An error occurred while exporting Solution {0} from Organization with Url {1}. [{2}]", this.Name, this.OrganizationUrl, exception.Message)); } } }
public void ExportSolution(string solutionName, string folder, bool managed) { ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = managed; exportSolutionRequest.SolutionName = solutionName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)Service.Execute(exportSolutionRequest); System.IO.Directory.CreateDirectory(folder); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solutionName + ".zip"; System.IO.File.WriteAllBytes(System.IO.Path.Combine(folder, filename), exportXml); }
public static void ExportSolution(IOrganizationService service, bool managed, string uniqueName, string path) { ExportSolutionRequest req = new ExportSolutionRequest() { Managed = managed, SolutionName = uniqueName, }; var response = (ExportSolutionResponse)service.Execute(req); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.WriteAllBytes(path, response.ExportSolutionFile); }
public byte[] ExportSolution(string solutionName, bool exportManaged) { var exportSolutionRequest = new ExportSolutionRequest { Managed = exportManaged, SolutionName = solutionName }; var exportSolutionResponse = (ExportSolutionResponse)OrganizationService.Execute(exportSolutionRequest); var exportXml = exportSolutionResponse.ExportSolutionFile; return(exportXml); }
public void Export(Guid solutionid, ExportSettings settings) { Entity sol = CrmService.Retrieve("solution", solutionid, new ColumnSet(true)); ExportSolutionRequest request = new ExportSolutionRequest(); request.ExportAutoNumberingSettings = settings.ExportAutoNumberingSettings; request.ExportCalendarSettings = settings.ExportCalendarSettings; request.ExportCustomizationSettings = settings.ExportCustomizationSettings; request.ExportEmailTrackingSettings = settings.ExportEmailTrackingSettings; request.ExportGeneralSettings = settings.ExportGeneralSettings; request.ExportIsvConfig = settings.ExportIsvConfig; request.ExportMarketingSettings = settings.ExportMarketingSettings; request.ExportOutlookSynchronizationSettings = settings.ExportOutlookSynchronizationSettings; request.ExportRelationshipRoles = settings.ExportRelationshipRoles; request.Managed = settings.IsManaged; request.SolutionName = sol["uniquename"] as string; ExportSolutionResponse response = (ExportSolutionResponse)CrmService.Execute(request); File.WriteAllBytes(settings.Path+"\\"+request.SolutionName+"_"+(sol["version"] as string).Replace(".","_")+"_"+((settings.IsManaged)?"managed":"unmanaged")+".zip", response.ExportSolutionFile); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a publisher /// Create a new solution, "Primary" /// Create a Global Option Set in solution "Primary" /// Export the "Primary" solution, setting it to Protected /// Delete the option set and solution /// Import the "Primary" solution, creating a managed solution in CRM. /// Create a new solution, "Secondary" /// Create an attribute in "Secondary" that references the Global Option Set /// </summary> public void CreateRequiredRecords() { //Create the publisher that will "own" the two solutions //<snippetGetSolutionDependencies6> Publisher publisher = new Publisher { UniqueName = "examplepublisher", FriendlyName = "An Example Publisher", Description = "This is an example publisher", CustomizationPrefix = _prefix }; _publisherId = _serviceProxy.Create(publisher); //</snippetGetSolutionDependencies6> //Create the primary solution - note that we are not creating it //as a managed solution as that can only be done when exporting the solution. //<snippetGetSolutionDependencies2> Solution primarySolution = new Solution { Version = "1.0", FriendlyName = "Primary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = _primarySolutionName }; _primarySolutionId = _serviceProxy.Create(primarySolution); //</snippetGetSolutionDependencies2> //Now, create the Global Option Set and associate it to the solution. //<snippetGetSolutionDependencies3> OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option 1", _languageCode), 1), new OptionMetadata(new Label("Option 2", _languageCode), 2) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata }; createOptionSetRequest.SolutionUniqueName = _primarySolutionName; _serviceProxy.Execute(createOptionSetRequest); //</snippetGetSolutionDependencies3> //Export the solution as managed so that we can later import it. //<snippetGetSolutionDependencies4> ExportSolutionRequest exportRequest = new ExportSolutionRequest { Managed = true, SolutionName = _primarySolutionName }; ExportSolutionResponse exportResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportRequest); //</snippetGetSolutionDependencies4> // Delete the option set previous created, so it can be imported under the // managed solution. //<snippetGetSolutionDependencies5> DeleteOptionSetRequest deleteOptionSetRequest = new DeleteOptionSetRequest { Name = _globalOptionSetName }; _serviceProxy.Execute(deleteOptionSetRequest); //</snippetGetSolutionDependencies5> // Delete the previous primary solution, so it can be imported as managed. _serviceProxy.Delete(Solution.EntityLogicalName, _primarySolutionId); _primarySolutionId = Guid.Empty; // Re-import the solution as managed. ImportSolutionRequest importRequest = new ImportSolutionRequest { CustomizationFile = exportResponse.ExportSolutionFile }; _serviceProxy.Execute(importRequest); // Retrieve the solution from CRM in order to get the new id. QueryByAttribute primarySolutionQuery = new QueryByAttribute { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet("solutionid"), Attributes = { "uniquename" }, Values = { _primarySolutionName } }; _primarySolutionId = _serviceProxy.RetrieveMultiple(primarySolutionQuery).Entities .Cast<Solution>().FirstOrDefault().SolutionId.GetValueOrDefault(); // Create a secondary solution. Solution secondarySolution = new Solution { Version = "1.0", FriendlyName = "Secondary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = "SecondarySolution" }; _secondarySolutionId = _serviceProxy.Create(secondarySolution); // Create a Picklist attribute in the secondary solution linked to the option set in the // primary - see WorkWithOptionSets.cs for more on option sets. PicklistAttributeMetadata picklistMetadata = new PicklistAttributeMetadata { SchemaName = _picklistName, LogicalName = _picklistName, DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = picklistMetadata }; createAttributeRequest["SolutionUniqueName"] = secondarySolution.UniqueName; _serviceProxy.Execute(createAttributeRequest); }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a managed solution for the Install or upgrade a solution sample Guid _tempPublisherId = new Guid(); System.String _tempCustomizationPrefix = "new"; Guid _tempSolutionsSampleSolutionId = new Guid(); System.String _TempGlobalOptionSetName = "_TempSampleGlobalOptionSetName"; Boolean _publisherCreated = false; Boolean _solutionCreated = false; //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "Microsoft CRM SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _tempPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _tempCustomizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _tempPublisherId = _serviceProxy.Create(_crmSdkPublisher); _tempCustomizationPrefix = _crmSdkPublisher.CustomizationPrefix; _publisherCreated = true; } //Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolutionforImport", FriendlyName = "Sample Solution for Import", PublisherId = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(querySampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _tempSolutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _tempSolutionsSampleSolutionId = _serviceProxy.Create(solution); _solutionCreated = true; } // Add a solution Component OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _tempCustomizationPrefix + _TempGlobalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option A", _languageCode), null), new OptionMetadata(new Label("Option B", _languageCode), null ) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(createOptionSetRequest); //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = true; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; System.IO.Directory.CreateDirectory(outputDir); File.WriteAllBytes(ManagedSolutionLocation, exportXml); // Delete the solution and the components so it can be installed. DeleteOptionSetRequest delOptSetReq = new DeleteOptionSetRequest { Name = (_tempCustomizationPrefix + _TempGlobalOptionSetName).ToLower() }; _serviceProxy.Execute(delOptSetReq); if (_solutionCreated) { _serviceProxy.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId); } if (_publisherCreated) { _serviceProxy.Delete(Publisher.EntityLogicalName, _tempPublisherId); } Console.WriteLine("Managed Solution created and copied to {0}", ManagedSolutionLocation); }
/// <summary> /// Shows how to perform the following tasks with solutions: /// - Create a Publisher /// - Retrieve the Default Publisher /// - Create a Solution /// - Retrieve a Solution /// - Add an existing Solution Component /// - Remove a Solution Component /// - Export or Package a Solution /// - Install or Upgrade a solution /// - Delete a Solution /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetWorkWithSolutions1> //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "Microsoft CRM SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _crmSdkPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _customizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher); Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName)); _customizationPrefix = _crmSdkPublisher.CustomizationPrefix; } //</snippetWorkWithSolutions1> //<snippetWorkWithSolutions2> // Retrieve the Default Publisher //The default publisher has a constant GUID value; Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}"); Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] {"friendlyname" })); EntityReference DefaultPublisherReference = new EntityReference { Id = DefaultPublisher.Id, LogicalName = Publisher.EntityLogicalName, Name = DefaultPublisher.FriendlyName }; Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name); //</snippetWorkWithSolutions2> //<snippetWorkWithSolutions3> // Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolution", FriendlyName = "Sample Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression queryCheckForSampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; queryCheckForSampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); //Create the solution if it does not already exist. EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _solutionsSampleSolutionId = _serviceProxy.Create(solution); } //</snippetWorkWithSolutions3> //<snippetWorkWithSolutions4> // Retrieve a solution String solutionUniqueName = "samplesolution"; QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "publisherid", "installedon", "version", "versionnumber", "friendlyname" }), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionUniqueName); Solution SampleSolution = (Solution)_serviceProxy.RetrieveMultiple(querySampleSolution).Entities[0]; //</snippetWorkWithSolutions4> //<snippetWorkWithSolutions5> // Add an existing Solution Component //Add the Account entity to the solution RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForAddAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForAddAccountRequest); AddSolutionComponentRequest addReq = new AddSolutionComponentRequest() { ComponentType = (int)componenttype.Entity, ComponentId = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(addReq); //</snippetWorkWithSolutions5> //<snippetWorkWithSolutions6> // Remove a Solution Component //Remove the Account entity from the solution RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForRemoveAccountRequest); RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest() { ComponentId = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId, ComponentType = (int)componenttype.Entity, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(removeReq); //</snippetWorkWithSolutions6> //<snippetWorkWithSolutions7> // Export or package a solution //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solution.UniqueName + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution exported to {0}.", outputDir + filename); //</snippetWorkWithSolutions7> //<snippetWorkWithSolutions8> // Install or Upgrade a Solution byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = fileBytes }; _serviceProxy.Execute(impSolReq); Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation); //</snippetWorkWithSolutions8> //<snippetWorkWithSolutions9> // Monitor import success byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest() { CustomizationFile = fileBytes, ImportJobId = Guid.NewGuid() }; _serviceProxy.Execute(impSolReqWithMonitoring); Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation); ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" })); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(job.Data); String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText; String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value; Console.WriteLine("Report from the ImportJob data"); Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName); Console.WriteLine("Solution Import Result: {0}", SolutionImportResult); Console.WriteLine(""); // This code displays the results for Global Option sets installed as part of a solution. System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet"); foreach (System.Xml.XmlNode node in optionSets) { string OptionSetName = node.Attributes["LocalizedName"].Value; string result = node.FirstChild.Attributes["result"].Value; if (result == "success") { Console.WriteLine("{0} result: {1}",OptionSetName, result); } else { string errorCode = node.FirstChild.Attributes["errorcode"].Value; string errorText = node.FirstChild.Attributes["errortext"].Value; Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText); } } //</snippetWorkWithSolutions9> //<snippetWorkWithSolutions10> // Delete a solution QueryExpression queryImportedSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "solutionid", "friendlyname" }), Criteria = new FilterExpression() }; queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, ImportedSolutionName); Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0]; _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId); Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName); //</snippetWorkWithSolutions10> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Exports the XRM solution. /// </summary> /// <param name="context">The context.</param> public override void ExecuteProcess(XrmActivityContext context) { foreach (SolutionElement solution in context.Configuration.Solutions) { if (!solution.IsEnabled) continue; var uniqueName = solution.Name.ToUniqueName(); var exportSolutionRequest = new ExportSolutionRequest { Managed = solution.IsManaged, ExportAutoNumberingSettings = true, ExportCalendarSettings = true, ExportCustomizationSettings = true, ExportEmailTrackingSettings = true, ExportGeneralSettings = true, ExportIsvConfig = true, ExportMarketingSettings = true, ExportOutlookSynchronizationSettings = true, SolutionName = uniqueName }; var exportSolutionResponse = (ExportSolutionResponse)context.Source.Execute(exportSolutionRequest); "export of the solution {0} completed.".Trace(uniqueName); var exportedXmlFromSource = exportSolutionResponse.ExportSolutionFile; if (!string.IsNullOrEmpty(solution.ExportDirectory)) { try { if (!Directory.Exists(solution.ExportDirectory)) Directory.CreateDirectory(solution.ExportDirectory); var fileName = uniqueName + "_" + (Convert.ToDouble(solution.Version)).ToString(CultureInfo.InvariantCulture).ToUniqueName() + ((solution.IsManaged) ? "_managed.zip" : "_unmanaged.zip"); using ( var fileStream = new FileStream(Path.Combine(solution.ExportDirectory, fileName), FileMode.Create)) { fileStream.Write(exportedXmlFromSource, 0, exportedXmlFromSource.Length); "{0} exported succesfully to path {1}".Trace(uniqueName, solution.ExportDirectory); } } catch (IOException ioex) { ioex.Message.TraceError(ioex); } } try { if (!solution.Publish) continue; var impSolReq = new ImportSolutionRequest() { CustomizationFile = exportedXmlFromSource, OverwriteUnmanagedCustomizations = true, PublishWorkflows = false }; "import solution {0} to destination".Trace(uniqueName); context.Destination.Execute(impSolReq); "solution import completed without issue.".Trace(); "publishing solution {0}".Trace(uniqueName); if (!solution.IsManaged) context.Destination.Execute(new PublishAllXmlRequest()); "the solution {0} has been published successfully.".Trace(uniqueName); } catch (FaultException<OrganizationServiceFault> orgException) { orgException.Message.TraceError(orgException); } } }
/// <summary> /// Exports the specified profile. /// </summary> /// <param name="profile">The profile.</param> private void Export(MSCRMSolutionsTransportProfile profile) { try { //Set Data export folder if (!Directory.Exists(profile.SolutionExportFolder)) Directory.CreateDirectory(profile.SolutionExportFolder); MSCRMConnection connection = profile.getSourceConneciton(); _serviceProxy = cm.connect(connection); //Download fresh list of solutions for versions update List<MSCRMSolution> solutions = DownloadSolutions(connection); DateTime now = DateTime.Now; string folderName = String.Format("{0:yyyyMMddHHmmss}", now); if (!Directory.Exists(profile.SolutionExportFolder + "\\" + folderName)) Directory.CreateDirectory(profile.SolutionExportFolder + "\\" + folderName); foreach (string SolutionName in profile.SelectedSolutionsNames) { //Check if customizations are to be published if (profile.PublishAllCustomizationsSource) { LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ..."); PublishAllXmlRequest publishRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(publishRequest); } LogManager.WriteLog("Exporting Solution " + SolutionName + " from " + connection.ConnectionName); ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = profile.ExportAsManaged; exportSolutionRequest.SolutionName = SolutionName; exportSolutionRequest.ExportAutoNumberingSettings = profile.ExportAutoNumberingSettings; exportSolutionRequest.ExportCalendarSettings = profile.ExportCalendarSettings; exportSolutionRequest.ExportCustomizationSettings = profile.ExportCustomizationSettings; exportSolutionRequest.ExportEmailTrackingSettings = profile.ExportEmailTrackingSettings; exportSolutionRequest.ExportGeneralSettings = profile.ExportGeneralSettings; exportSolutionRequest.ExportIsvConfig = profile.ExportIsvConfig; exportSolutionRequest.ExportMarketingSettings = profile.ExportMarketingSettings; exportSolutionRequest.ExportOutlookSynchronizationSettings = profile.ExportOutlookSynchronizationSettings; exportSolutionRequest.ExportRelationshipRoles = profile.ExportRelationshipRoles; string managed = ""; if (profile.ExportAsManaged) managed = "managed"; MSCRMSolution selectedSolution = solutions.Find(s => s.UniqueName == SolutionName); string selectedSolutionVersion = selectedSolution.Version.Replace(".","_"); ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = SolutionName + "_" + selectedSolutionVersion + "_" + managed + ".zip"; File.WriteAllBytes(profile.SolutionExportFolder + "\\" + folderName + "\\" + filename, exportXml); LogManager.WriteLog("Export finished for Solution: " + SolutionName + ". Exported file: " + filename); } LogManager.WriteLog("Export finished for Profile: " + profile.ProfileName); } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); throw; } catch (Exception ex) { if (ex.InnerException != null) LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); else LogManager.WriteLog("Error:" + ex.Message); throw; } }
private string GetSolutionFromCrm(string connString, CrmSolution selectedSolution, bool managed) { try { CrmConnection connection = CrmConnection.Parse(connString); // Hardcode connection timeout to one-hour to support large solutions. connection.Timeout = new TimeSpan(1, 0, 0); using (_orgService = new OrganizationService(connection)) { ExportSolutionRequest request = new ExportSolutionRequest { Managed = managed, SolutionName = selectedSolution.UniqueName }; ExportSolutionResponse response = (ExportSolutionResponse)_orgService.Execute(request); var tempFolder = Path.GetTempPath(); string fileName = Path.GetFileName(selectedSolution.UniqueName + "_" + FormatVersionString(selectedSolution.Version) + ((managed) ? "_managed" : String.Empty) + ".zip"); var tempFile = Path.Combine(tempFolder, fileName); if (File.Exists(tempFile)) File.Delete(tempFile); File.WriteAllBytes(tempFile, response.ExportSolutionFile); return tempFile; } } catch (FaultException<OrganizationServiceFault> crmEx) { _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, Logger.MessageType.Error); return null; } catch (Exception ex) { _logger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, Logger.MessageType.Error); return null; } }