private void ImportSolutionInD365CE(byte[] fileBytes, string deploymentFolderName)
 {
     WorkAsync(new WorkAsyncInfo
     {
         Message = "Importing solution package to CDS",
         Work    = (worker, args) =>
         {
             ImportSolutionRequest impSolReq = new ImportSolutionRequest()
             {
                 CustomizationFile = fileBytes
             };
             args.Result = Service.Execute(impSolReq);
         },
         PostWorkCallBack = (args) =>
         {
             if (args.Error != null)
             {
                 MessageBox.Show(args.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
                 var result = args.Result as OrganizationResponse;
                 if (result != null)
                 {
                     PublishAll(deploymentFolderName);
                 }
             }
         }
     });
 }
Example #2
0
        public static bool ImportSolution(CrmServiceClient client, string path)
        {
            var solutionBytes = FileSystem.GetFileBytes(path);

            if (solutionBytes == null)
            {
                return(false);
            }

            try
            {
                var request = new ImportSolutionRequest
                {
                    CustomizationFile = solutionBytes,
                    OverwriteUnmanagedCustomizations = true,
                    PublishWorkflows = true,
                    ImportJobId      = Guid.NewGuid()
                };

                client.Execute(request);

                ExLogger.LogToFile(Logger, $"{Resource.Message_ImportedSolution}: {path}", LogLevel.Info);
                OutputLogger.WriteToOutputWindow($"{Resource.Message_ImportedSolution}: {path}", MessageType.Info);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorImportingSolution, ex);

                return(false);
            }
        }
Example #3
0
        public virtual ImportSolutionResponse ImportSolution(Guid importJobId, byte[] content, bool holdingSolution, bool overwriteUnmanagedCustomizations, bool publishWorkflows, bool skipProductUpdateDependencies)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (Guid.Empty.Equals(importJobId))
            {
                throw new ArgumentNullException(nameof(importJobId));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            ImportSolutionRequest req = new ImportSolutionRequest()
            {
                CustomizationFile = content,
                HoldingSolution   = holdingSolution,
                ImportJobId       = importJobId,
                OverwriteUnmanagedCustomizations = overwriteUnmanagedCustomizations,
                PublishWorkflows = publishWorkflows,
                SkipProductUpdateDependencies = skipProductUpdateDependencies
            };
            ImportSolutionResponse res = (ImportSolutionResponse)OrganizationService.Execute(req);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            return(res);
        }
Example #4
0
        private ImportSolutionRequest PrepareImportRequest(ConnectionDetail detail, Entity solution)
        {
            var request = new ImportSolutionRequest
            {
                ConvertToManaged = Settings.Instance.ConvertToManaged,
                OverwriteUnmanagedCustomizations = Settings.Instance.OverwriteUnmanagedCustomizations,
                PublishWorkflows = Settings.Instance.PublishWorkflows,
                ImportJobId      = Guid.NewGuid()
            };

            if (ConnectionDetail.OrganizationMajorVersion >= 8)
            {
                request.HoldingSolution = Settings.Instance.HoldingSolution;
                request.SkipProductUpdateDependencies = Settings.Instance.SkipProductUpdateDependencies;
            }

            var pi = new ProgressItem
            {
                Type     = Enumerations.RequestType.Import,
                Detail   = detail,
                Solution = solution.GetAttributeValue <string>("friendlyname"),
                Request  = request
            };

            pi.LogFileRequested += Pi_LogFileRequested;
            progressItems.Add(request, pi);

            return(request);
        }
Example #5
0
        private void ImportSolution()
        {
            var solutionFilePath = $@"{_solutionSettings.SolutionExportDirectory}{_solutionSettings.SolutionName}.zip";

            var data     = File.ReadAllBytes(solutionFilePath);
            var importId = Guid.NewGuid();

            Console.WriteLine("Importing unmanged solution {0} to environment {1}.",
                              _solutionSettings.SolutionName,
                              CdsClient.ConnectedOrgFriendlyName);

            var importSolutionRequest = new ImportSolutionRequest
            {
                CustomizationFile = data,
                ImportJobId       = importId,
                PublishWorkflows  = true,
                OverwriteUnmanagedCustomizations = true,
                ConvertToManaged = false,
                SkipProductUpdateDependencies = false
            };

            void Starter() => ProgressReport(importId);

            var t = new Thread(Starter);

            t.Start();

            CdsClient.Execute(importSolutionRequest);
            Console.WriteLine("Solution {0} successfully imported into {1}",
                              solutionFilePath,
                              CdsClient.ConnectedOrgFriendlyName);
        }
Example #6
0
        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);
        }
Example #7
0
        public void Run(ServerConnection.Configuration serverConfig, string solutionPath)
        {
            try
            {
                using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    byte[] data = File.ReadAllBytes(solutionPath);
                    Guid importId = Guid.NewGuid();

                    Console.WriteLine("\n Importing solution {0} into Server {1}.", solutionPath, serverConfig.OrganizationUri);

                    _serviceProxy.EnableProxyTypes();
                    ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest()
                    {
                        CustomizationFile = data,
                        ImportJobId = importId
                    };

                    ThreadStart starter = () =>ProgressReport(serverConfig, importId);
                    Thread t = new Thread(starter);
                    t.Start();

                    _serviceProxy.Execute(importSolutionRequest);
                    Console.Write("Solution {0} successfully imported into {1}", solutionPath, serverConfig.OrganizationUri);
                }
            }
            catch (Exception ex)
            {

            }
        }
Example #8
0
        public static bool ImportSolution(CrmServiceClient client, string path)
        {
            byte[] solutionBytes = CrmDeveloperExtensions2.Core.FileSystem.GetFileBytes(path);
            if (solutionBytes == null)
            {
                return(false);
            }

            try
            {
                ImportSolutionRequest request = new ImportSolutionRequest
                {
                    //TODO: make configurable
                    CustomizationFile = solutionBytes,
                    OverwriteUnmanagedCustomizations = true,
                    PublishWorkflows = true,
                    ImportJobId      = Guid.NewGuid()
                };

                ImportSolutionResponse response = (ImportSolutionResponse)client.Execute(request);

                return(true);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                OutputLogger.WriteToOutputWindow("Error Importing Solution To CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error);
                return(false);
            }
            catch (Exception ex)
            {
                OutputLogger.WriteToOutputWindow("Error Importing Solution To CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error);
                return(false);
            }
        }
Example #9
0
        public void ImportSolution(OrganizationServiceProxy _serviceProxy)
        {
            string hostName = _serviceProxy.ServiceManagement.CurrentServiceEndpoint.ListenUri.Host;

            _serviceProxy.Timeout = TimeSpan.MaxValue;
            foreach (string solution in this.Settings.SolutionsToBeImport)
            {
                Console.WriteLine($"importing {solution} into {hostName} at {DateTime.Now.ToLongTimeString()}");
                byte[] fileBytes = ReadSolutionFile(solution);
                ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                {
                    CustomizationFile = fileBytes,
                    PublishWorkflows  = true
                };
                _serviceProxy.Execute(impSolReq);
                Console.WriteLine($"{solution} has been imported into {hostName}  at  {DateTime.Now.ToLongTimeString()}");
            }

            if (this.Settings.PublishAllCustomizationAfterImported)
            {
                Console.WriteLine("Publishing all customizations " + DateTime.Now.ToLongTimeString());
                PublishAllXmlRequest pubReq = new PublishAllXmlRequest();
                _serviceProxy.Execute(pubReq);
                _serviceProxy.Dispose();
                Console.WriteLine("All customizations have been published!");
            }
        }
        public static bool ImportSolution(CrmServiceClient client, string path)
        {
            byte[] solutionBytes = FileSystem.GetFileBytes(path);
            if (solutionBytes == null)
            {
                return(false);
            }

            try
            {
                ImportSolutionRequest request = new ImportSolutionRequest
                {
                    CustomizationFile = solutionBytes,
                    OverwriteUnmanagedCustomizations = true,
                    PublishWorkflows = true,
                    ImportJobId      = Guid.NewGuid()
                };

                client.Execute(request);

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorImportingSolution, ex);

                return(false);
            }
        }
Example #11
0
 public SyncImportHandler(
     ILogger logger,
     IOrganizationService organizationService,
     ImportSolutionRequest importRequest)
     : base(logger, organizationService)
 {
     ImportRequest = importRequest;
 }
Example #12
0
        private void ImportSolutionInDestination(byte[] solutionContent)
        {
            var importSolutionRequest = new ImportSolutionRequest
            {
                CustomizationFile = solutionContent,
                PublishWorkflows  = true
            };

            destinationSystem.Execute(importSolutionRequest);
        }
Example #13
0
        public static void TransferSolutionFromFile(string filePath, CrmOrganization targetOrg)
        {
            byte[] exportXml = File.ReadAllBytes(filePath);

            ImportSolutionRequest impSolReq = new ImportSolutionRequest()
            {
                CustomizationFile = exportXml
            };

            targetOrg.Service.Execute(impSolReq);
        }
Example #14
0
        public void ImportSolutions(IEnumerable <string> solutionFiles, LogController controller, XrmService xrmService)
        {
            var countToDo            = solutionFiles.Count();
            var countRecordsImported = 0;

            foreach (var solutionFile in solutionFiles)
            {
                try
                {
                    controller.UpdateProgress(++countRecordsImported, countToDo + 1,
                                              "Importing Solution " + solutionFile);
                    var importId = Guid.NewGuid();
                    var req      = new ImportSolutionRequest();
                    req.ImportJobId       = importId;
                    req.CustomizationFile = File.ReadAllBytes(solutionFile);
                    req.PublishWorkflows  = true;
                    req.OverwriteUnmanagedCustomizations = true;

                    var finished               = new Processor();
                    var extraService           = new XrmService(xrmService.XrmConfiguration);
                    var monitoreProgressThread = new Thread(() => DoProgress(importId, controller.GetLevel2Controller(), finished, extraService));
                    monitoreProgressThread.IsBackground = true;
                    monitoreProgressThread.Start();
                    try
                    {
                        xrmService.Execute(req);
                    }
                    finally
                    {
                        lock (_lockObject)
                            finished.Completed = true;
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    if (ex.Detail != null && ex.Detail.InnerFault != null && ex.Detail.InnerFault.InnerFault != null)
                    {
                        throw new Exception(string.Format("Error Importing Solution {0}\n{1}\n{2}", solutionFile, ex.Message, ex.Detail.InnerFault.InnerFault.Message), ex);
                    }
                    else
                    {
                        throw new Exception(
                                  string.Format("Error Importing Solution {0}\n{1}", solutionFile, ex.Message), ex);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Importing Solution {0}", solutionFile), ex);
                }
            }
            controller.TurnOffLevel2();
            controller.LogLiteral("Publishing Customisations");
            xrmService.Publish();
        }
Example #15
0
        public static void ImportSolutions(IOrganizationService service, byte[] data, bool overWriteUnmanagedCustomizations, bool migrateAsHold, bool publishWorkflows)
        {
            ImportSolutionRequest importRequest = new ImportSolutionRequest()
            {
                CustomizationFile = data,
                OverwriteUnmanagedCustomizations = overWriteUnmanagedCustomizations,
                HoldingSolution  = migrateAsHold,
                PublishWorkflows = publishWorkflows,
            };

            service.Execute(importRequest);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Importing Solution: {0}", SolutionFilePath));

            // TODO: I think this is not necessary because you will get back an Id if you overload Guid.Empty
            if (ImportJobId == Guid.Empty)
            {
                ImportJobId = Guid.NewGuid();
            }

            base.WriteVerbose(string.Format("ImportJobId {0}", ImportJobId));

            byte[] solutionBytes = File.ReadAllBytes(SolutionFilePath);

            var importSolutionRequest = new ImportSolutionRequest
            {
                CustomizationFile = solutionBytes,
                PublishWorkflows  = PublishWorkflows,
                ConvertToManaged  = ConvertToManaged,
                OverwriteUnmanagedCustomizations = OverwriteUnmanagedCustomizations,
                SkipProductUpdateDependencies    = SkipProductUpdateDependencies,
                ImportJobId     = ImportJobId,
                RequestId       = ImportJobId,
                HoldingSolution = HoldingSolution
            };

            if (ImportAsync)
            {
                var asyncRequest = new ExecuteAsyncRequest
                {
                    Request   = importSolutionRequest,
                    RequestId = ImportJobId
                };
                var asyncResponse = OrganizationService.Execute(asyncRequest) as ExecuteAsyncResponse;

                Guid asyncJobId = asyncResponse.AsyncJobId;

                WriteObject(asyncJobId);

                if (WaitForCompletion)
                {
                    AwaitCompletion(asyncJobId);
                }
            }
            else
            {
                OrganizationService.Execute(importSolutionRequest);
            }

            base.WriteVerbose(string.Format("{0} Imported Completed {1}", SolutionFilePath, ImportJobId));
        }
Example #17
0
        private void ImportSolution(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);

            if (!File.Exists(solutioneFile))
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The given Solution file for import does not exist. {0}", solutioneFile));
                return;
            }

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache)
                    {
                        cache.Mode = OrganizationServiceCacheMode.Disabled;
                    });

                    byte[] customizationFile = File.ReadAllBytes(solutioneFile);
                    var    request           = new ImportSolutionRequest
                    {
                        CustomizationFile = customizationFile,
                        OverwriteUnmanagedCustomizations = this.overwriteCustomizations,
                        PublishWorkflows = this.EnableSdkProcessingSteps
                    };

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing Solution {0}. Please wait...", this.Name));
                    serviceContext.Execute(request);
                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported Solution {0} to organization with Url {1}.", this.Name, this.OrganizationUrl));
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                     CultureInfo.CurrentCulture,
                                     "An error occurred while importing Solution {0} to Organization with Url {1}. [{2}]",
                                     this.Name,
                                     this.OrganizationUrl,
                                     exception.Message));
                }
            }
        }
        private void Import(string solutionPath, CDSConnection cdsConnection, Context context)
        {
            byte[] fileBytes = File.ReadAllBytes(solutionPath);

            ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
            {
                CustomizationFile = fileBytes,
                ImportJobId       = Guid.NewGuid()
            };

            Console.WriteLine($"Importing {solutionPath}");

            cdsConnection.Execute(impSolReqWithMonitoring);

            var job = cdsConnection.Retrieve("importjob",
                                             impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" }));

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(job["data"].ToString()); // check

            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("");

            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);
                }
            }
        }
Example #19
0
        private Guid ImportSolutionInTargetOrg(ITracingService tracingService, byte[] fileContent, EntityCollection credentials, string username, string password)
        {
            Guid asyncOperationId = Guid.Empty;
            IOrganizationService targetOrganizationService = null;

            //AliasedValue usernameAliasVal = credentials.Entities[0].GetAttributeValue<AliasedValue>("aa.devops_userid");
            //AliasedValue passwordAliasVal = credentials.Entities[0].GetAttributeValue<AliasedValue>("aa.devops_userpassword");
            AliasedValue orgSvcAliasVal = credentials.Entities[0].GetAttributeValue <AliasedValue>("aa.devops_orgserviceurl");

            //string userName = string.Empty;
            //string password = string.Empty;
            string orgSvcUrl = string.Empty;

            if (orgSvcAliasVal != null)
            {
                //userName = usernameAliasVal.Value.ToString();
                //password = passwordAliasVal.Value.ToString();
                orgSvcUrl = orgSvcAliasVal.Value.ToString();
            }

            ClientCredentials clientCredentials = new ClientCredentials();

            clientCredentials.UserName.UserName = username;
            clientCredentials.UserName.Password = password;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            tracingService.Trace($"Trying to create new OrganizationServiceProxy");
            targetOrganizationService = new OrganizationServiceProxy(new Uri(orgSvcUrl),
                                                                     null, clientCredentials, null);

            if (targetOrganizationService != null)
            {
                tracingService.Trace($"Starting import in target organization");
                var request = new ImportSolutionRequest()
                {
                    CustomizationFile = fileContent,
                    OverwriteUnmanagedCustomizations = OverWrite
                };
                var requestAsync = new ExecuteAsyncRequest
                {
                    Request = request
                };

                var asyncResp = (ExecuteAsyncResponse)targetOrganizationService.Execute(requestAsync);
                tracingService.Trace($"Executed the Import Request");

                asyncOperationId = asyncResp.AsyncJobId;
            }
            return(asyncOperationId);
        }
Example #20
0
        private Guid ImportSolution(byte[] solutionBodyBinary)
        {
            Guid importJobId = Guid.NewGuid();

            ImportSolutionRequest request = new ImportSolutionRequest()
            {
                CustomizationFile = solutionBodyBinary,
                OverwriteUnmanagedCustomizations = true,
                PublishWorkflows = true,
                ImportJobId      = importJobId,
            };

            var response = (ImportSolutionResponse)_service.Execute(request);

            return(importJobId);
        }
        private void ImportUnmanagedSolution(string solutionPath)
        {
            byte[] solutionBytes = File.ReadAllBytes(solutionPath);

            var request = new ImportSolutionRequest
            {
                OverwriteUnmanagedCustomizations = true,
                PublishWorkflows  = true,
                CustomizationFile = solutionBytes,
                ImportJobId       = Guid.NewGuid()
            };

            ExConsole.WriteLine("Importing solution...");

            ImportSolutionResponse response = (ImportSolutionResponse)_targetOrganizationService.Execute(request);

            ExConsole.WriteLineToRight("[Done]");
        }
 private void ImportSolution(byte[] compressedXml, Guid importJobId)
 {
     try
     {
         var importSolutionRequest = new ImportSolutionRequest
         {
             CustomizationFile = compressedXml,
             OverwriteUnmanagedCustomizations = true, PublishWorkflows = true,
             ImportJobId = importJobId,
         };
         OrganizationService.Execute(importSolutionRequest);
     }
     catch
     {
         MonitorCustomizations(importJobId);
         throw;
     }
 }
Example #23
0
        public static void Main(String managedSolutionLocation, String crmUrl, String organization)
        {
            Guid _importJobId = Guid.NewGuid();

            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;
                        }
                        byte[] fileBytes = File.ReadAllBytes(managedSolutionLocation);
                        ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                        {
                            CustomizationFile = fileBytes,
                            ImportJobId       = _importJobId,
                            OverwriteUnmanagedCustomizations = true,
                            SkipProductUpdateDependencies    = true,
                            PublishWorkflows = true,
                        };
                        ImportSolutionResponse impSolResp = new ImportSolutionResponse();
                        _client.Execute(impSolReq);
                        // On success escribe el customization file .xml
                        CreateFile(impSolReq.ImportJobId, managedSolutionLocation, ".xml");
                    }
                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        string _voidMessageDumpError = ex.Message;
                        //No hago nada con el error ya que el metodo create file lo busca en tabla ImportJob y escribe si hay error en el customization file
                        CreateFile(_importJobId, managedSolutionLocation, ".xml");
                    }
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                string message = ex.Message;
                throw;
            }
        }
Example #24
0
 /// <summary>
 /// Method to import a solution into Dynamics CRM.
 /// </summary>
 /// <param name="solutionFilePath">The path and file name of the file to import.</param>
 public void ImportSolution(string solutionFilePath)
 {
     try
     {
         byte[] fileBytes = File.ReadAllBytes(solutionFilePath);
         ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest()
         {
             CustomizationFile = fileBytes
         };
         using (XrmService service = new XrmService(XRMConnectionString))
         {
             service.Execute(importSolutionRequest);
         }
     }
     catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
     {
         throw;
     }
 }
Example #25
0
        private static ImportSolutionRequest ImportSolution(CrmServiceClient client)
        {
            string solutionName          = "Test_1_0_0_0.zip";
            Guid   importID              = Guid.NewGuid();
            string folderPath            = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
            var    solutionBytes         = File.ReadAllBytes(Path.Combine(folderPath, solutionName));
            var    importSolutionRequest = new ImportSolutionRequest
            {
                CustomizationFile = solutionBytes,
                PublishWorkflows  = true,
                ConvertToManaged  = false,
                OverwriteUnmanagedCustomizations = true,
                ImportJobId     = importID,
                HoldingSolution = false,
                SkipProductUpdateDependencies = true
            };

            return(importSolutionRequest);
        }
Example #26
0
        private void TransferPatch(Item item)
        {
            try
            {
                var stream = item.DownloadFile();
                var bytes  = StreamHelper.ReadToEnd(stream);

                ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                {
                    CustomizationFile = bytes
                };

                CrmOrg.Service.Execute(impSolReq);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Exception transfering Patch {item.ServerItem}, Message: {ex.Message}");
            }
        }
Example #27
0
        public bool ImportSolution()
        {
            bool   _isSucceed            = false;
            string SolutionDirectory     = @"C:\Solution";
            IOrganizationService service = CRMHelper.ConnectToMSCRM();

            ImportSolutionRequest SolutionRequest;

            byte[] Solution;

            string[] files = Directory.GetFiles(SolutionDirectory);
            foreach (string file in files)
            {
                Solution        = File.ReadAllBytes(file);
                SolutionRequest = new ImportSolutionRequest();
                SolutionRequest.CustomizationFile = Solution;
                SolutionRequest.ImportJobId       = Guid.NewGuid();
                SolutionRequest.ConvertToManaged  = false;

                try
                {
                    service.Execute(SolutionRequest);
                    Entity ImportJob = new Entity("importjob");
                    ImportJob = service.Retrieve(ImportJob.LogicalName, SolutionRequest.ImportJobId, new ColumnSet(true));
                    XDocument xdoc = XDocument.Parse(ImportJob["data"].ToString());

                    string ImportSolutionName = xdoc.Descendants("solutionManifest").Descendants("UniqueName").First().Value;

                    bool SolutionImportResult = xdoc.Descendants("solutionManifest").Descendants("result").First().FirstAttribute.Value == "success" ? true : false;

                    //Guid? Solutionid = GetSDol
                }

                catch (Exception ex)
                {
                    continue;
                }
            }



            return(_isSucceed);
        }
Example #28
0
        private static ImportSolutionResponse ImportSolution(byte[] solutionBytes, IOrganizationService organizationService)
        {
            var request = new ImportSolutionRequest
            {
                CustomizationFile = solutionBytes,
                ImportJobId       = Guid.NewGuid(),
                OverwriteUnmanagedCustomizations = false,
                PublishWorkflows = true
            };

            try
            {
                return((ImportSolutionResponse)organizationService.Execute(request));
            }
            catch (FaultException <OrganizationServiceFault> )
            {
                ExConsole.WriteLineColor("Could not import solution", ConsoleColor.Red);
                throw;
            }
        }
        private bool DoImportSolution(SolutionBlockImport import, string filename, Version version)
        {
            container.StartSection(MethodBase.GetCurrentMethod().Name);
            var       result       = false;
            var       activatecode = import.ActivateServersideCode;
            var       overwrite    = import.OverwriteCustomizations;
            Exception ex           = null;

            SendLine(container, "Importing solution: {0} Version: {1}", filename, version);
            var fileBytes = File.ReadAllBytes(filename);
            var impSolReq = new ImportSolutionRequest()
            {
                CustomizationFile = fileBytes,
                OverwriteUnmanagedCustomizations = overwrite,
                PublishWorkflows = activatecode,
                ImportJobId      = Guid.NewGuid()
            };

            if (/*crmsvc is CrmServiceProxy && */ container.GetCrmVersion().Major >= 6) //((CrmServiceProxy)crmsvc).CrmVersion.Major >= 6)
            {                                                                           // CRM 2013 or later, import async
                result = DoImportSolutionAsync(impSolReq, ref ex);
            }
            else
            {   // Pre CRM 2013, import sync
                result = DoImportSolutionSync(impSolReq, ref ex);
            }
            if (!result && stoponerror)
            {
                if (ex != null)
                {
                    throw ex;
                }
                else
                {
                    throw new Exception("Solution import failed");
                }
            }
            container.Log($"Returning: {result}");
            container.EndSection();
            return(result);
        }
Example #30
0
        /// <summary>
        /// Checks whether the ChangeTrackingSample solution is already installed.
        /// If it is not, the ChangeTrackingSample_1_0_0_0_managed.zip file is imported to install
        /// this solution.
        /// </summary>
        public void ImportChangeTrackingSolution()
        {
            try
            {
                Console.WriteLine("Checking whether the ChangeTrackingSample solution already exists.....");

                QueryByAttribute queryCheckForSampleSolution = new QueryByAttribute();
                queryCheckForSampleSolution.AddAttributeValue("uniquename", "ChangeTrackingSample");
                queryCheckForSampleSolution.EntityName = Solution.EntityLogicalName;

                EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution);
                Solution         SampleSolutionResults      = null;
                if (querySampleSolutionResults.Entities.Count > 0)
                {
                    Console.WriteLine("The {0} solution already exists....", "ChangeTrackingSample");
                    SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0];
                }
                else
                {
                    Console.WriteLine("The ChangeTrackingSample solution does not exist. Importing the solution....");
                    byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation);
                    ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes
                    };

                    _serviceProxy.Execute(impSolReq);

                    Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation);
                    Console.WriteLine("Waiting for the alternate key index to be created.......");
                    Thread.Sleep(50000);
                }
            }

            // 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;
            }
        }
        private bool DoImportSolution(XmlNode xImport, string filename, Version version)
        {
            log.StartSection(MethodBase.GetCurrentMethod().Name);
            var       result       = false;
            bool      activatecode = CintXML.GetBoolAttribute(xImport, "ActivateServersideCode", false);
            bool      overwrite    = CintXML.GetBoolAttribute(xImport, "OverwriteCustomizations", false);
            Exception ex           = null;

            SendLine("Importing solution: {0} Version: {1}", filename, version);
            byte[] fileBytes = File.ReadAllBytes(filename);
            ImportSolutionRequest impSolReq = new ImportSolutionRequest()
            {
                CustomizationFile = fileBytes,
                OverwriteUnmanagedCustomizations = overwrite,
                PublishWorkflows = activatecode,
                ImportJobId      = Guid.NewGuid()
            };

            if (crmsvc is CrmServiceProxy && ((CrmServiceProxy)crmsvc).CrmVersion.Major >= 6)
            {   // CRM 2013 or later, import async
                result = DoImportSolutionAsync(impSolReq, ref ex);
            }
            else
            {   // Pre CRM 2013, import sync
                result = DoImportSolutionSync(impSolReq, ref ex);
            }
            if (!result && stoponerror)
            {
                if (ex != null)
                {
                    throw ex;
                }
                else
                {
                    throw new Exception("Solution import failed");
                }
            }
            log.Log("Returning: {0}", result);
            log.EndSection();
            return(result);
        }
        private void writeLogFile(Guid ImportJobId, string solutionsToImportFolder, string solutionArchiveName)
        {
            Entity ImportJob = _serviceProxy.Retrieve("importjob", ImportJobId, new ColumnSet(true));
            //File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]);
            impSolReqWithMonitoring = null;

            RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest()
            {
                ImportJobId = ImportJobId
            };

            RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest);

            DateTime now = DateTime.Now;
            string timeNow = String.Format("{0:yyyyMMddHHmmss}", now);

            string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml";

            //Fix bad Status and Message export
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml((string)ImportJob["data"]);
            String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

            File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults);
        }
        private void ImportGUI(BackgroundWorker worker, DoWorkEventArgs e)
        {
            try
            {
                //Check if there is a solutions to import
                if (Directory.Exists(currentProfile.SolutionExportFolder))
                {
                    IOrderedEnumerable<string> subDirectories = Directory.GetDirectories(currentProfile.SolutionExportFolder).OrderByDescending(x => x);
                    if (subDirectories.Count<string>() == 0)
                    {
                        LogManager.WriteLog("There are no solutions for import.");
                        StatusMessage = "There are no solutions for import.";
                        return;
                    }

                    //Check which solutions to import: Newest, Oldest, specific exprot date solutions
                    string solutionsToImportFolder = "";
                    if (currentProfile.SolutionsToImport == "Newest")
                        solutionsToImportFolder = subDirectories.ElementAt(0);
                    else if (currentProfile.SolutionsToImport == "Oldest")
                        solutionsToImportFolder = subDirectories.ElementAt(subDirectories.Count<string>() - 1);
                    else
                        solutionsToImportFolder = subDirectories.First(s => s.EndsWith(currentProfile.SolutionsToImport));

                    if (solutionsToImportFolder == "")
                    {
                        LogManager.WriteLog("The specified solutions to import were not found.");
                        StatusMessage = "The specified solutions to import were not found.";
                        return;
                    }

                    //get all solutions archives
                    string[] solutionsArchivesNames = Directory.GetFiles(solutionsToImportFolder, "*.zip");
                    if (solutionsArchivesNames.Count<string>() == 0)
                    {
                        LogManager.WriteLog("There are no solutions for import.");
                        StatusMessage = "There are no solutions for import.";
                        return;
                    }

                    string[] pathList = solutionsToImportFolder.Split(new Char[] { '\\' });
                    string DirectoryName = pathList[pathList.Count<string>() - 1];
                    LogManager.WriteLog("Importing solutions from " + DirectoryName);

                    MSCRMConnection connection = currentProfile.getTargetConneciton();
                    _serviceProxy = cm.connect(connection);
                    LogManager.WriteLog("Start importing solutions in " + connection.ConnectionName);

                    int solutionsCpt = 0;

                    foreach (string solutionArchiveName in solutionsArchivesNames)
                    {
                        bool selectedsolutionfound = false;
                        foreach (string solutionname in currentProfile.SelectedSolutionsNames)
                        {
                            if (Path.GetFileName(solutionArchiveName).StartsWith(solutionname))
                                selectedsolutionfound = true;
                        }

                        if(!selectedsolutionfound)
                            continue;

                        solutionsCpt++;

                        //Import Solution
                        LogManager.WriteLog("Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName);
                        StatusMessage = "Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName;
                        //worker.ReportProgress(solutionsCpt * 100 / currentProfile.SelectedSolutionsNames.Count);

                        byte[] fileBytes = File.ReadAllBytes(solutionArchiveName);

                        Guid ImportJobId = Guid.NewGuid();

                        impSolReqWithMonitoring = new ImportSolutionRequest()
                        {
                            CustomizationFile = fileBytes,
                            OverwriteUnmanagedCustomizations = currentProfile.OverwriteUnmanagedCustomizations,
                            PublishWorkflows = currentProfile.PublishWorkflows,
                            ImportJobId = ImportJobId
                        };

                        if (bwSolutionImport.IsBusy != true)
                            bwSolutionImport.RunWorkerAsync();
                        solutionImportInProgress = true;

                        while (solutionImportInProgress)
                        {
                            if (transportStopped)
                              return;
                            int progress = GetImportProgress(ImportJobId, connection);
                            worker.ReportProgress(progress);
                            System.Threading.Thread.Sleep(5000);
                        }

                        //if (transportStopped)
                          //  return;

                        //Entity ImportJob = _serviceProxy.Retrieve("importjob", ImportJobId, new ColumnSet(true));
                        ////File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]);
                        //impSolReqWithMonitoring = null;

                        //RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest()
                        //{
                        //    ImportJobId = ImportJobId
                        //};

                        //RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest);

                        //DateTime now = DateTime.Now;
                        //string timeNow = String.Format("{0:yyyyMMddHHmmss}", now);

                        //string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml";

                        ////Fix bad Status and Message export
                        //System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        //doc.LoadXml((string)ImportJob["data"]);
                        //String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                        //File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults);
                        writeLogFile(ImportJobId, solutionsToImportFolder, solutionArchiveName);

                        importSourceFolder = solutionsToImportFolder;

                        LogManager.WriteLog("Solution " + Path.GetFileName(solutionArchiveName) + " was imported with success in " + connection.ConnectionName);
                    }

                    //Check if customizations are to be published
                    if (currentProfile.PublishAllCustomizationsTarget)
                    {
                        LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ...");
                        PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                        _serviceProxy.Execute(publishRequest);
                    }

                    LogManager.WriteLog("Solutions Import finished for Profile: " + currentProfile.ProfileName);
                }
                else
                {
                    LogManager.WriteLog("There are no solutions for import.");
                    return;
                }
            }
            catch(Exception ex)
            {
                transportStopped = true;
                LogManager.WriteLog("Error ! Detail : " + ex.Message);
                MessageBox.Show("Error ! Detail : " + ex.Message);
                toolStripStatusLabel1.Text = "Transport stopped.";
            }
        }
 /// <summary>
 /// Calls the Crm Service Execute method with an <c>importCompressedAllXmlRequest</c> using the contents of the ImportFile property as the the <c>Byte</c>
 /// array to use when creating the request
 /// </summary>
 internal void Import()
 {
     ImportSolutionRequest request = new ImportSolutionRequest() { CustomizationFile = this.ImportFile, OverwriteUnmanagedCustomizations = true, PublishWorkflows = true };
     lock (this.sync)
     {
         try
         {
             this.InstallAdapter.OrganizationService.Execute(request);
         }
         catch (Exception e)
         {
             if (!this.ThrowException(e).Handled)
             {
                 throw;
             }
         }
     }
 }
Example #35
0
        /// <summary>
        /// Ипортируем решение
        /// </summary>
        /// <param name="service"></param>
        public static void ImportSolution(IOrganizationService service)
        {
            byte[] fileBytes = File.ReadAllBytes(DirectoryHandler.ZipCustomizationPath);

            ImportSolutionRequest importSolution = new ImportSolutionRequest()
            {
                CustomizationFile = fileBytes
            };

            ImportSolutionResponse resp = (ImportSolutionResponse)service.Execute(importSolution);
        }
Example #36
0
        /// <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;
            }
        }
Example #37
0
        /// <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>
        /// Imports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void Import(MSCRMSolutionsTransportProfile profile)
        {
            //Check if there is a solutions to import
            if (Directory.Exists(profile.SolutionExportFolder))
            {
                IOrderedEnumerable<string> subDirectories = Directory.GetDirectories(profile.SolutionExportFolder).OrderByDescending(x => x);
                if (subDirectories.Count<string>() == 0)
                {
                    LogManager.WriteLog("There are no solutions for import.");
                    return;
                }

                //Check which solutions to import: Newest, Oldest, specific exprot date solutions
                string solutionsToImportFolder = "";
                if (profile.SolutionsToImport == "Newest")
                    solutionsToImportFolder = subDirectories.ElementAt(0);
                else if (profile.SolutionsToImport == "Oldest")
                    solutionsToImportFolder = subDirectories.ElementAt(subDirectories.Count<string>() - 1);
                else
                    solutionsToImportFolder = subDirectories.First(s => s.EndsWith(profile.SolutionsToImport));

                if (solutionsToImportFolder == "")
                {
                    LogManager.WriteLog("The specified solutions to import were not found.");
                    return;
                }

                //get all solutions archives
                string[] solutionsArchivesNames = Directory.GetFiles(solutionsToImportFolder, "*.zip");
                if (solutionsArchivesNames.Count<string>() == 0)
                {
                    LogManager.WriteLog("There are no solutions for import.");
                    return;
                }

                string[] pathList = solutionsToImportFolder.Split(new Char [] {'\\'});
                string DirectoryName = pathList[pathList.Count<string>() -1];
                LogManager.WriteLog("Importing solutions from " + DirectoryName);

                MSCRMConnection connection = profile.getTargetConneciton();
                _serviceProxy = cm.connect(connection);
                LogManager.WriteLog("Start importing solutions in " + connection.ConnectionName);

                foreach (string solutionArchiveName in solutionsArchivesNames)
                {
                    bool selectedsolutionfound = false;
                    foreach (string solutionname in profile.SelectedSolutionsNames)
                    {
                        if (Path.GetFileName(solutionArchiveName).StartsWith(solutionname))
                            selectedsolutionfound = true;
                    }

                    if (!selectedsolutionfound)
                        continue;

                    //Import Solution
                    LogManager.WriteLog("Importing solution archive " + Path.GetFileName(solutionArchiveName) + " into " + connection.ConnectionName);

                    byte[] fileBytes = File.ReadAllBytes(solutionArchiveName);

                    Guid ImportJobId = Guid.NewGuid();

                    ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes,
                        OverwriteUnmanagedCustomizations = profile.OverwriteUnmanagedCustomizations,
                        PublishWorkflows = profile.PublishWorkflows,
                        ImportJobId = ImportJobId
                    };

                    _serviceProxy.Execute(impSolReqWithMonitoring);

                    Entity ImportJob = _serviceProxy.Retrieve("importjob", impSolReqWithMonitoring.ImportJobId, new ColumnSet(true));
                    //File.WriteAllText(solutionsToImportFolder + "\\importlog_ORIGINAL_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + ".xml", (string)ImportJob["data"]);

                    RetrieveFormattedImportJobResultsRequest importLogRequest = new RetrieveFormattedImportJobResultsRequest()
                    {
                        ImportJobId = ImportJobId
                    };
                    RetrieveFormattedImportJobResultsResponse importLogResponse = (RetrieveFormattedImportJobResultsResponse)_serviceProxy.Execute(importLogRequest);

                    DateTime now = DateTime.Now;
                    string timeNow = String.Format("{0:yyyyMMddHHmmss}", now);

                    string exportedSolutionFileName = solutionsToImportFolder + "\\importlog_" + Path.GetFileNameWithoutExtension(solutionArchiveName) + "_" + timeNow + ".xml";

                    //Fix bad Status and Message export
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml((string)ImportJob["data"]);
                    String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                    File.WriteAllText(exportedSolutionFileName, importLogResponse.FormattedResults);

                    LogManager.WriteLog("Solution " + Path.GetFileName(solutionArchiveName) + " was imported with success in " + connection.ConnectionName);
                }

                //Check if customizations are to be published
                if (profile.PublishAllCustomizationsTarget)
                {
                    LogManager.WriteLog("Publishing all Customizations on " + connection.ConnectionName + " ...");
                    PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
                    _serviceProxy.Execute(publishRequest);
                }

                LogManager.WriteLog("Solutions Import finished for Profile: " + profile.ProfileName);
            }
            else
            {
                LogManager.WriteLog("There are no solutions for import.");
                return;
            }
        }
        /// <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);
        }
Example #40
0
        public void ImportSolutionArchive(string archivePath, ImportSettings settings)
        {
            try
            {
                importPath = archivePath; //sets the global variable for the import path

                var request = new ImportSolutionRequest
                                  {
                                      ConvertToManaged = settings.ConvertToManaged,
                                      CustomizationFile = File.ReadAllBytes(archivePath),
                                      OverwriteUnmanagedCustomizations = settings.OverwriteUnmanagedCustomizations,
                                      PublishWorkflows = settings.Activate,
                                      ImportJobId = settings.ImportId
                                  };

                if (settings.MajorVersion >= 6)
                {
                    var requestAsync = new ExecuteAsyncRequest
                    {
                        Request = request
                    };

                    innerService.Execute(requestAsync);

                    bool isfinished = false;
                    do
                    {
                        try
                        {
                            var job = innerService.Retrieve("importjob", settings.ImportId, new ColumnSet(true));

                            if (job.Contains("completedon"))
                            {
                                isfinished = true;
                            }
                        }
                        catch
                        {
                        }

                        Thread.Sleep(2000);
                    } while (isfinished == false);
                }
                else
                {
                    innerService.Execute(request);
                }
            }
            catch (FaultException<OrganizationServiceFault> error)
            {
                throw new Exception("An error while importing archive: " + error.Message);
            }
            finally
            {
                if (settings.DownloadLog)
                {
                    string filePath = DownloadLogFile(importPath, settings);

                    if (MessageBox.Show("Do you want to open the log file now?\r\n\r\nThe file will also be available on disk: " + filePath, "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Process.Start("Excel.exe", "\"" + filePath + "\"");
                    }
                }
            }
        }
        private void ImportSolution(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);
            if (!File.Exists(solutioneFile))
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The given Solution file for import does not exist. {0}", solutioneFile));
                return;
            }

            using (var serviceContext = new CrmOrganizationServiceContext(connection))
            {
                try
                {
                    serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache)
                    {
                        cache.Mode = OrganizationServiceCacheMode.Disabled;
                    });

                    byte[] customizationFile = File.ReadAllBytes(solutioneFile);
                    var request = new ImportSolutionRequest
                    {
                        CustomizationFile = customizationFile,
                        OverwriteUnmanagedCustomizations = this.overwriteCustomizations,
                        PublishWorkflows = this.EnableSdkProcessingSteps
                    };

                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing Solution {0}. Please wait...", this.Name));
                    serviceContext.Execute(request);
                    Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported Solution {0} to organization with Url {1}.", this.Name, this.OrganizationUrl));
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format(
                                    CultureInfo.CurrentCulture,
                                    "An error occurred while importing Solution {0} to Organization with Url {1}. [{2}]",
                                    this.Name, 
                                    this.OrganizationUrl,
                                    exception.Message));
                }
            }
        }