Exemplo n.º 1
0
        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;
            }
        }
Exemplo n.º 2
0
        /// <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);
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        public void ExportSolution(OrganizationServiceProxy _serviceProxy)
        {
            //if (this.Settings.IsChangeWorkFlowName)
            //{
            //    ChangeWorkflowName(_serviceProxy);
            //}

            string hostName = _serviceProxy.ServiceManagement.CurrentServiceEndpoint.ListenUri.Host;

            _serviceProxy.Timeout = TimeSpan.MaxValue;
            _serviceProxy.EnableProxyTypes();

            if (Settings.PublishAllCustomizationBeforeExported)
            {
                Console.WriteLine($"{hostName} Publishing all customizations at " + DateTime.Now.ToLongTimeString());
                PublishAllXmlRequest pubReq = new PublishAllXmlRequest();
                _serviceProxy.Execute(pubReq);
            }

            foreach (string solution in this.Settings.SolutionsToBeExport)
            {
                QueryExpression qe = new QueryExpression("solution");
                qe.ColumnSet = new ColumnSet("version");
                qe.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution);
                qe.TopCount = 1;
                qe.NoLock   = true;
                Entity entSolution = _serviceProxy.RetrieveMultiple(qe).Entities.FirstOrDefault();
                if (entSolution != null)
                {
                    Console.WriteLine($"Export {solution} from {hostName} at {DateTime.Now.ToLongTimeString()}");
                    string monthDay   = DateTime.Today.ToString("MMdd");
                    string newVersion = entSolution.GetAttributeValue <string>("version") + monthDay;
                    entSolution.Attributes["version"] = newVersion;
                    _serviceProxy.Update(entSolution);
                    ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                    exportSolutionRequest.Managed      = false;
                    exportSolutionRequest.SolutionName = solution;
                    //exportSolutionRequest.TargetVersion = "8.2";
                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest);
                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;

                    string filename = string.Format("{0}_{1}.zip", solution, newVersion.Replace('.', '_'));

                    WriteSolutionFile(exportXml, filename);
                }
            }
            Console.WriteLine("solution has been exported at " + DateTime.Now.ToLongTimeString());
        }
Exemplo n.º 5
0
        private void ExportSolution(string uniqueName, bool packageType, string absoluteFilePath)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(uniqueName))
            {
                throw new ArgumentNullException(nameof(uniqueName));
            }

            Logger.Info(CultureInfo.InvariantCulture, "Downloading {0} solution {1}", packageType ? "managed" : "unmanaged", uniqueName);

            ExportSolutionResponse res = CrmService.ExportSolution(uniqueName, packageType);

            Logger.Info(CultureInfo.InvariantCulture, "Saving {0}.", absoluteFilePath);

            File.WriteAllBytes(absoluteFilePath, res.ExportSolutionFile);

            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.ExitingMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);
        }
        private string GetSolutionFromCrm(string connString, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                CrmServiceClient connection = new CrmServiceClient(connString);
                // Hardcode connection timeout to one-hour to support large solutions.
                //connection.Timeout = new TimeSpan(1, 0, 0);

                using (_orgService = connection.OrganizationServiceProxy)
                {
                    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);
            }
        }
Exemplo n.º 7
0
        public virtual ExportSolutionResponse ExportSolution(string uniqueName, bool packageType)
        {
            Logger.Trace(CultureInfo.InvariantCulture, TraceMessageHelper.EnteredMethod, SystemTypeName, MethodBase.GetCurrentMethod().Name);

            if (string.IsNullOrWhiteSpace(uniqueName))
            {
                throw new ArgumentNullException(nameof(uniqueName));
            }

            ExportSolutionRequest req = new ExportSolutionRequest
            {
                Managed      = packageType,
                SolutionName = uniqueName
            };
            ExportSolutionResponse res = (ExportSolutionResponse)OrganizationServiceContext.Execute(req);

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

            return(res);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Method exports solution
        /// </summary>
        /// <param name="serviceProxy">organization service proxy</param>
        /// <param name="solutionFile">solution file info</param>
        private void ExportSolution(OrganizationServiceProxy serviceProxy, SolutionFileInfo solutionFile)
        {
            if (solutionFile.SolutionsToBeMerged.Count > 0)
            {
                this.MergeSolutions(solutionFile, serviceProxy);
            }

            if (!solutionFile.CheckInSolution)
            {
                return;
            }

            solutionFile.Solution[Constants.SourceControlQueueAttributeNameForRepositoryUrl] = this.RepositoryUrl;
            solutionFile.Solution[Constants.SourceControlQueueAttributeNameForBranch]        = this.Branch;
            solutionFile.Solution[Constants.SourceControlQueueAttributeNameForStatus]        = Constants.SourceControlQueueExportStatus;
            solutionFile.Update();

            ExportSolutionRequest exportRequest = new ExportSolutionRequest
            {
                Managed      = false,
                SolutionName = solutionFile.SolutionUniqueName
            };

            Console.WriteLine("Downloading Solution " + solutionFile.SolutionUniqueName);
            ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest);

            // Handles the response
            byte[] downloadedSolutionFile = exportResponse.ExportSolutionFile;
            solutionFile.SolutionFilePath = Path.GetTempFileName();
            File.WriteAllBytes(solutionFile.SolutionFilePath, downloadedSolutionFile);

            string solutionExport = string.Format("Solution Successfully Exported to {0}", solutionFile.SolutionUniqueName);

            Console.WriteLine(solutionExport);

            solutionFile.Solution[Constants.SourceControlQueueAttributeNameForStatus] = Constants.SourceControlQueueExportSuccessful;
            solutionFile.Update();
            solutionFile.ProcessSolutionZipFile(this.SolutionPackagerPath);
        }
Exemplo n.º 9
0
        private byte[] ExportDefaultSolutionZip()
        {
            ExportSolutionRequest exportRequest = new ExportSolutionRequest();

            exportRequest.ExportAutoNumberingSettings          = true;
            exportRequest.ExportCalendarSettings               = true;
            exportRequest.ExportCustomizationSettings          = true;
            exportRequest.ExportEmailTrackingSettings          = true;
            exportRequest.ExportExternalApplications           = true;
            exportRequest.ExportGeneralSettings                = true;
            exportRequest.ExportIsvConfig                      = true;
            exportRequest.ExportMarketingSettings              = true;
            exportRequest.ExportOutlookSynchronizationSettings = true;
            exportRequest.ExportRelationshipRoles              = true;
            exportRequest.ExportSales  = true;
            exportRequest.SolutionName = "Default";

            ExportSolutionResponse exportResponse = (ExportSolutionResponse)_organizatioService.Execute(exportRequest);

            byte[] exportXml = exportResponse.ExportSolutionFile;
            return(exportXml);
        }
Exemplo n.º 10
0
        /// <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(OrganizationServiceProxy 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>");
                Console.WriteLine(message + solutionName);
                serviceProxy.Timeout = new TimeSpan(0, 10, 0);
                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>");
                Console.WriteLine(solutionExport);
            }
            catch (Exception ex)
            {
                Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + ex.Message + "<br>");
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
        public override void Execute(CancellationToken cancel, IProgress <ExecutionProgress> progress)
        {
            OnExecuting(new ExecutableEventArgs(this));
            string exportPath = GetExportPath();

            progress?.Report(new ExecutionProgress(NotificationType.Information, string.Format(Properties.Resources.Dynamics365ExportSolutionOperationExecute, Solution.FriendlyName, exportPath)));

            using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
            {
                ExportSolutionRequest request = new ExportSolutionRequest()
                {
                    Managed      = isManaged,
                    SolutionName = solution.UniqueName
                };

                ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)proxy.Execute(request);
                byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                File.WriteAllBytes(exportPath, exportXml);
            }

            //progress?.Report(new ExecutionProgress(NotificationType.Information, string.Format(Properties.Resources.Dynamics365ExportSolutionOperationExecuteSuccessful, Solution.FriendlyName, exportPath)));
            OnExecuted(new ExecutableEventArgs(this));
        }
Exemplo n.º 12
0
        public static string ExportSolution(IOrganizationService service, ConnectionDetail ConnectionDetail, ExportSolutionRequest exportSolutionRequest, string version, string outputDir)
        {
            outputDir = outputDir + @"\";
            try
            {
                if (ConnectionDetail != null)
                {
                    ConnectionDetail.Timeout = new TimeSpan(1, 0, 0);
                }
                //if (client.OrganizationWebProxyClient != null)
                //    ConnectionDetail.OperationTimeout = new TimeSpan(1, 0, 0);

                // ExportSolutionResponse exportSolutionResponse = await Task.Run(() => (ExportSolutionResponse)service.Execute(exportSolutionRequest));
                ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest);
                byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                string filename;
                if (exportSolutionRequest.Managed)
                {
                    filename = exportSolutionRequest.SolutionName + "_" + version + "_managed.zip";
                }
                else
                {
                    filename = exportSolutionRequest.SolutionName + "_" + version + ".zip";
                }

                File.WriteAllBytes(outputDir + filename, exportXml);
                return("Successfully exported");
            }
            catch (SoapException es)
            {
                return(es.Message);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Exemplo n.º 13
0
        public static async Task <string> GetSolutionFromCrm(CrmServiceClient client, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                // Hardcode connection timeout to one-hour to support large solutions.
                if (client.OrganizationServiceProxy != null)
                {
                    client.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                }
                if (client.OrganizationWebProxyClient != null)
                {
                    client.OrganizationWebProxyClient.InnerChannel.OperationTimeout = new TimeSpan(1, 0, 0);
                }

                ExportSolutionRequest request = new ExportSolutionRequest
                {
                    Managed      = managed,
                    SolutionName = selectedSolution.UniqueName
                };
                ExportSolutionResponse response = await Task.Run(() => (ExportSolutionResponse)client.Execute(request));

                string fileName = FileHandler.FormatSolutionVersionString(selectedSolution.UniqueName, selectedSolution.Version, managed);
                string tempFile = FileHandler.WriteTempFile(fileName, response.ExportSolutionFile);

                return(tempFile);
            }
            catch (FaultException <OrganizationServiceFault> crmEx)
            {
                OutputLogger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + crmEx.Message + Environment.NewLine + crmEx.StackTrace, MessageType.Error);
                return(null);
            }
            catch (Exception ex)
            {
                OutputLogger.WriteToOutputWindow("Error Retrieving Solution From CRM: " + ex.Message + Environment.NewLine + ex.StackTrace, MessageType.Error);
                return(null);
            }
        }
Exemplo n.º 14
0
        public static async Task <string> GetSolutionFromCrm(CrmServiceClient client, CrmSolution selectedSolution, bool managed)
        {
            try
            {
                // Hardcode connection timeout to one-hour to support large solutions.
                //TODO: Find a better way to handle this
                if (client.OrganizationServiceProxy != null)
                {
                    client.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                }
                if (client.OrganizationWebProxyClient != null)
                {
                    client.OrganizationWebProxyClient.InnerChannel.OperationTimeout = new TimeSpan(1, 0, 0);
                }

                ExportSolutionRequest request = new ExportSolutionRequest
                {
                    Managed      = managed,
                    SolutionName = selectedSolution.UniqueName
                };
                ExportSolutionResponse response = await Task.Run(() => (ExportSolutionResponse)client.Execute(request));

                OutputLogger.WriteToOutputWindow(Resource.Message_RetrievedSolution, MessageType.Info);

                string fileName = FileHandler.FormatSolutionVersionString(selectedSolution.UniqueName, selectedSolution.Version, managed);
                string tempFile = FileHandler.WriteTempFile(fileName, response.ExportSolutionFile);

                return(tempFile);
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(Logger, Resource.ErrorMessage_ErrorRetrievingSolution, ex);

                return(null);
            }
        }
        /// <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;
            }
        }
Exemplo n.º 16
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    //Define a new publisher
                    Publisher _powerappsSdkPublisher = new Publisher
                    {
                        UniqueName           = "powerappssamples",
                        FriendlyName         = "PowerApps 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 PowerApps 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, _powerappsSdkPublisher.UniqueName);
                    EntityCollection querySDKSamplePublisherResults = service.RetrieveMultiple(querySDKSamplePublisher);
                    Publisher        SDKSamplePublisherResults      = null;

                    //If it already exists, use it
                    if (querySDKSamplePublisherResults.Entities.Count > 0)
                    {
                        SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0];
                        _powerappsSdkPublisherId  = (Guid)SDKSamplePublisherResults.PublisherId;
                        _customizationPrefix      = SDKSamplePublisherResults.CustomizationPrefix;
                    }
                    //If it doesn't exist, create it
                    if (SDKSamplePublisherResults == null)
                    {
                        _powerappsSdkPublisherId = service.Create(_powerappsSdkPublisher);
                        Console.WriteLine(String.Format("Created publisher: {0}.", _powerappsSdkPublisher.FriendlyName));
                        _customizationPrefix = _powerappsSdkPublisher.CustomizationPrefix;
                    }

                    // Retrieve the Default Publisher

                    //The default publisher has a constant GUID value;
                    Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}");

                    Publisher DefaultPublisher = (Publisher)service.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);

                    // Create a Solution
                    //Define a solution
                    Solution solution = new Solution
                    {
                        UniqueName   = "samplesolution",
                        FriendlyName = "Sample Solution",
                        PublisherId  = new EntityReference(Publisher.EntityLogicalName, _powerappsSdkPublisherId),
                        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 = service.RetrieveMultiple(queryCheckForSampleSolution);
                    Solution         SampleSolutionResults      = null;
                    if (querySampleSolutionResults.Entities.Count > 0)
                    {
                        SampleSolutionResults      = (Solution)querySampleSolutionResults.Entities[0];
                        _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId;
                    }
                    if (SampleSolutionResults == null)
                    {
                        _solutionsSampleSolutionId = service.Create(solution);
                    }

                    // 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)service.RetrieveMultiple(querySampleSolution).Entities[0];

                    // Add an existing Solution Component
                    //Add the Account entity to the solution
                    RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse      retrieveForAddAccountResponse = (RetrieveEntityResponse)service.Execute(retrieveForAddAccountRequest);
                    AddSolutionComponentRequest addReq = new AddSolutionComponentRequest()
                    {
                        ComponentType      = (int)componenttype.Entity,
                        ComponentId        = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId,
                        SolutionUniqueName = solution.UniqueName
                    };
                    service.Execute(addReq);

                    // Remove a Solution Component
                    //Remove the Account entity from the solution
                    RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)service.Execute(retrieveForRemoveAccountRequest);

                    RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest()
                    {
                        ComponentId        = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId,
                        ComponentType      = (int)componenttype.Entity,
                        SolutionUniqueName = solution.UniqueName
                    };
                    service.Execute(removeReq);

                    // Export or package a solution
                    //Export an a solution

                    ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                    exportSolutionRequest.Managed      = false;
                    exportSolutionRequest.SolutionName = solution.UniqueName;

                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)service.Execute(exportSolutionRequest);

                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                    string filename  = solution.UniqueName + ".zip";
                    File.WriteAllBytes(outputDir + filename, exportXml);

                    Console.WriteLine("Solution exported to {0}.", outputDir + filename);

                    // Install or Upgrade a Solution

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

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

                    service.Execute(impSolReq);

                    Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation);


                    // Monitor import success
                    byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation);

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

                    service.Execute(impSolReqWithMonitoring);
                    Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation);

                    ImportJob job = (ImportJob)service.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);
                        }
                    }
                    #endregion Demonstrate
                    #endregion Sample Code


                    DeleteRequiredRecords(service, prompt);
                }

                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Exporting Solution: {0}", UniqueSolutionName));

            CrmConnection connection = CrmConnection.Parse(connectionString);

            using (OrganizationService service = new OrganizationService(connection))
            {
                StringBuilder solutionFile = new StringBuilder();
                Solution      solution     = null;

                using (CIContext context = new CIContext(service))
                {
                    var query = from s in context.SolutionSet
                                where s.UniqueName == UniqueSolutionName
                                select s;

                    solution = query.FirstOrDefault <Solution>();
                }

                if (solution == null)
                {
                    throw new Exception(string.Format("Solution {0} could not be found", UniqueSolutionName));
                }
                else
                {
                    solutionFile.Append(UniqueSolutionName);

                    if (IncludeVersionInName)
                    {
                        solutionFile.Append("_");
                        solutionFile.Append(solution.Version.Replace(".", "_"));
                    }
                }

                if (managed)
                {
                    solutionFile.Append("_managed");
                }

                solutionFile.Append(".zip");

                ExportSolutionRequest req = new ExportSolutionRequest()
                {
                    Managed      = managed,
                    SolutionName = UniqueSolutionName,
                    ExportAutoNumberingSettings          = exportAutoNumberingSettings,
                    ExportCalendarSettings               = exportCalendarSettings,
                    ExportCustomizationSettings          = exportCustomizationSettings,
                    ExportEmailTrackingSettings          = exportEmailTrackingSettings,
                    ExportGeneralSettings                = exportGeneralSettings,
                    ExportIsvConfig                      = exportIsvConfig,
                    ExportMarketingSettings              = exportMarketingSettings,
                    ExportOutlookSynchronizationSettings = exportOutlookSynchronizationSettings,
                    ExportRelationshipRoles              = exportRelationshipRoles
                };

                ExportSolutionResponse res = service.Execute(req) as ExportSolutionResponse;

                File.WriteAllBytes(outputFolder + "\\" + solutionFile.ToString(), res.ExportSolutionFile);

                base.WriteObject(solutionFile.ToString());
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        private void CreateRequiredRecords()
        {
            // Create a managed solution for the Install or upgrade a solution sample

            Guid   _tempPublisherId               = new Guid();
            String _tempCustomizationPrefix       = _publisherCustomizationPrefix;
            Guid   _tempSolutionsSampleSolutionId = new Guid();

            Boolean _publisherCreated = false;
            Boolean _solutionCreated  = false;


            //Define a new publisher
            Publisher _crmSdkPublisher = new Publisher
            {
                //UniqueName = "dsleadintegration",
                //FriendlyName = "Dotsquares Ltd.",

                UniqueName           = Constants.PublisherUniqueName,
                FriendlyName         = Constants.PublisherFriendlyName,
                SupportingWebsiteUrl = Constants.PublisherSupportingWebsiteUrl,
                CustomizationPrefix  = Constants.PublisherCustomizationPrefix,
                EMailAddress         = Constants.PublisherEmailAddress,
                Description          = Constants.PublisherDescription
            };

            //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;
            }

            //Upload only configuration page
            UploadConfigurationPageForSolution();

            //Define a solution
            Solution solution = new Solution
            {
                UniqueName          = Constants.SolutionUniqueName,
                FriendlyName        = Constants.SolutionFriendlyName,
                PublisherId         = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId),
                Description         = Constants.SolutionDescription,
                Version             = Constants.SolutionVersion,
                ConfigurationPageId = new EntityReference(WebResource.EntityLogicalName, _webResourceIdForSolution)
            };

            //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;
            }

            //delete webform entity
            if (IsEntityExist(_customEntityName) > 0)
            {
                DeleteEntityRequest customEntityNameFormField = new DeleteEntityRequest()
                {
                    LogicalName = _customEntityName,
                };
                _serviceProxy.Execute(customEntityNameFormField);
            }
            // Create the webform entity.
            WebForm.WebForm.DotsWebFormEntity();


            //delete webfield entity
            if (IsEntityExist(_customFieldEntityName) > 0)
            {
                DeleteEntityRequest customFieldEntityNameFormField = new DeleteEntityRequest()
                {
                    LogicalName = _customFieldEntityName,
                };
                _serviceProxy.Execute(customFieldEntityNameFormField);
            }

            // Create the webfield entity.
            WebForm.WebForm.DotsWebFieldEntity();


            //create relationship with webform and field entity
            WebForm.WebForm.CreateRelationShip();


            //delete webformconfig entity
            if (IsEntityExist(_customConfigurationEntityName) > 0)
            {
                DeleteEntityRequest customEntityConfigNameFormField = new DeleteEntityRequest()
                {
                    LogicalName = _customConfigurationEntityName,
                };
                _serviceProxy.Execute(customEntityConfigNameFormField);
            }
            // Create the config entity.
            WebForm.WebForm.DotsWebFormConfigEntity();

            // assign entity sample form entity to solution
            //##################### Start Assign WebForm Entity #############################
            RetrieveEntityRequest retrievepowertEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = _customEntityName
            };

            RetrieveEntityResponse retrievepowerEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrievepowertEntityRequest);

            AddSolutionComponentRequest addReq = new AddSolutionComponentRequest()
            {
                ComponentType         = 1,
                ComponentId           = (Guid)retrievepowerEntityResponse.EntityMetadata.MetadataId,
                SolutionUniqueName    = solution.UniqueName,
                AddRequiredComponents = true
            };

            _serviceProxy.Execute(addReq);
            //##################### End Assign WebForm Entity #############################



            // assign entity webfield entity to solution
            //##################### Start Assign WebField Entity #############################
            RetrieveEntityRequest retrievewebfieldEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = _customEntityName
            };

            RetrieveEntityResponse retrievefieldEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrievewebfieldEntityRequest);

            AddSolutionComponentRequest addFieldEntityReq = new AddSolutionComponentRequest()
            {
                ComponentType         = 1,
                ComponentId           = (Guid)retrievefieldEntityResponse.EntityMetadata.MetadataId,
                SolutionUniqueName    = solution.UniqueName,
                AddRequiredComponents = true
            };

            _serviceProxy.Execute(addFieldEntityReq);
            //##################### End Assign WebField Entity #############################



            //assign configuration entity to solution
            //##################### End Assign WebConfig Entity #############################
            RetrieveEntityRequest retrieveconfigurationtEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = _customConfigurationEntityName
            };


            RetrieveEntityResponse retrieveconfigEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveconfigurationtEntityRequest);

            AddSolutionComponentRequest addConfigReq = new AddSolutionComponentRequest()
            {
                ComponentType         = 1,
                ComponentId           = (Guid)retrieveconfigEntityResponse.EntityMetadata.MetadataId,
                SolutionUniqueName    = solution.UniqueName,
                AddRequiredComponents = true
            };

            _serviceProxy.Execute(addConfigReq);

            //##################### End Assign WebConfig Entity #############################

            //assign web resource to slution
            CreateWebResource(solution.UniqueName);

            //assign configuration page above creted to solution
            AssiginConfigurationPageToSolution(_webResourceIdForSolution, solution.UniqueName);

            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();

            exportSolutionRequest.Managed      = false;
            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.

            DeleteEntityRequest delEntReq = new DeleteEntityRequest {
                LogicalName = (_customEntityName)
            };

            _serviceProxy.Execute(delEntReq);

            DeleteEntityRequest delFieldEntReq = new DeleteEntityRequest {
                LogicalName = (_customFieldEntityName)
            };

            _serviceProxy.Execute(delFieldEntReq);

            DeleteEntityRequest delEntReqConfig = new DeleteEntityRequest {
                LogicalName = (_customConfigurationEntityName)
            };

            _serviceProxy.Execute(delEntReqConfig);


            if (_solutionCreated)
            {
                _serviceProxy.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId);

                //delete webresorce
                foreach (var _id in _webResourceIds)
                {
                    _serviceProxy.Delete(WebResource.EntityLogicalName, _id);
                }
                //for configuration page above created delete
                _serviceProxy.Delete(WebResource.EntityLogicalName, _webResourceIdForSolution);
            }

            if (_publisherCreated)
            {
                _serviceProxy.Delete(Publisher.EntityLogicalName, _tempPublisherId);
            }


            Console.WriteLine("Managed Solution created and copied to {0}", _managedSolutionLocation);
        }
Exemplo n.º 19
0
        public void Begin()
        {
            data = new Stack <Result>();
            data.Push(LoadData());

            while (true)
            {
                bool breakout = false;

                ResultResponse returnCode = data.Peek().Draw();

                switch (returnCode.ConsoleKey)
                {
                case ConsoleKey.Escape: breakout = true; break;

                default:
                    int selection = -1;

                    if (int.TryParse(returnCode.Response, out selection))
                    {
                        switch (data.Count)
                        {
                        case 1:
                            Console.Write("\r\nExporting solution? ([U]nmanaged/[M]anaged/[C]ancel): ");
                            string answer = Console.ReadLine();
                            if (string.IsNullOrEmpty(answer) || answer.ToUpper().Trim().StartsWith("U") || answer.ToUpper().Trim().StartsWith("M"))
                            {
                                ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                                exportSolutionRequest.Managed      = answer.ToUpper().Trim().StartsWith("M");
                                exportSolutionRequest.SolutionName = (string)data.Peek().Data.Rows[selection - 1]["Logical Name"];        // solution.UniqueName;

                                ExportSolutionResponse exportSolutionResponse = null;
                                try
                                {
                                    exportSolutionResponse = (ExportSolutionResponse)connection.OrganizationService.Execute(exportSolutionRequest);
                                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                                    string filename  = (string)data.Peek().Data.Rows[selection - 1]["Logical Name"] + (exportSolutionRequest.Managed ? "-managed" : "-unmanaged") + ".zip";
                                    File.WriteAllBytes(filename, exportXml);

                                    Console.WriteLine("Solution exported to {0}.", filename);
                                    Console.WriteLine("\r\nEnter to continue");
                                    Console.ReadLine();
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);

                                    Console.WriteLine("\r\nEnter to continue");
                                    Console.ReadLine();
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    break;
                }

                if (breakout)
                {
                    break;
                }
            }
        }
        /// <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);
        }
Exemplo n.º 21
0
        /// <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       = "ds";
            Guid          _tempSolutionsSampleSolutionId = new Guid();
            Random        rn = new Random();

            System.String _TempGlobalOptionSetName = "_TempSampleGlobalOptionSetName" + rn.Next();
            Boolean       _publisherCreated        = false;
            Boolean       _solutionCreated         = false;


            //Define a new publisher
            Publisher _crmSdkPublisher = new Publisher
            {
                UniqueName           = Constants.PublisherUniqueName,
                FriendlyName         = Constants.PublisherFriendlyName,
                SupportingWebsiteUrl = Constants.PublisherSupportingWebsiteUrl,
                CustomizationPrefix  = Constants.PublisherCustomizationPrefix,
                EMailAddress         = Constants.PublisherEmailAddress,
                Description          = Constants.PublisherDescription
            };

            //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;
            }

            //Upload only configuration page
            UploadConfigurationPageForSolution();
            //SetWebResourceConfigurationForSolution();

            //Define a solution
            Solution solution = new Solution
            {
                UniqueName          = Constants.SolutionUniqueName,
                FriendlyName        = Constants.SolutionFriendlyName,
                PublisherId         = new EntityReference(Publisher.EntityLogicalName, _tempPublisherId),
                Description         = Constants.SolutionDescription,
                Version             = Constants.SolutionVersion,
                ConfigurationPageId = new EntityReference(WebResource.EntityLogicalName, _webResourceIdForSolution[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);

            //delete configuration entity
            if (IsEntityExist(_customEntityName) > 0)
            {
                DeleteEntityRequest customEntityNameFormField = new DeleteEntityRequest()
                {
                    LogicalName = _customEntityName,
                };
                _serviceProxy.Execute(customEntityNameFormField);
            }


            // Create the dots_autonumber entity.
            AutoSMS.DotsAutoNumberEntity();
            // CreateTab();


            //delete dots_configuration entity
            if (IsEntityExist(_customConfigurationEntityName) > 0)
            {
                DeleteEntityRequest customEntityNameFormField = new DeleteEntityRequest()
                {
                    LogicalName = _customConfigurationEntityName,
                };
                _serviceProxy.Execute(customEntityNameFormField);
            }


            //for create dots_configuration entity
            AutoSMS.DotsAutoNumberConfigurationEntity();


            // assign dots_autonumber form entity to solution
            RetrieveEntityRequest retrievepowertEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = _customEntityName
            };


            RetrieveEntityResponse retrievepowerEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrievepowertEntityRequest);

            AddSolutionComponentRequest addReq = new AddSolutionComponentRequest()
            {
                ComponentType         = 1,
                ComponentId           = (Guid)retrievepowerEntityResponse.EntityMetadata.MetadataId,
                SolutionUniqueName    = solution.UniqueName,
                AddRequiredComponents = true
            };

            _serviceProxy.Execute(addReq);


            //assign dots_configuration entity to solution
            RetrieveEntityRequest retrieveconfigurationtEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = _customConfigurationEntityName
            };


            RetrieveEntityResponse retrieveconfigEntityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveconfigurationtEntityRequest);

            AddSolutionComponentRequest addConfigReq = new AddSolutionComponentRequest()
            {
                ComponentType         = 1,
                ComponentId           = (Guid)retrieveconfigEntityResponse.EntityMetadata.MetadataId,
                SolutionUniqueName    = solution.UniqueName,
                AddRequiredComponents = true
            };

            _serviceProxy.Execute(addConfigReq);

            //assign web resource to slution
            CreateWebResource(solution.UniqueName);

            //assign configuration page above created to solution
            AssiginConfigurationPageToSolution(_webResourceIdForSolution[0], solution.UniqueName);

            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();

            exportSolutionRequest.Managed      = false;
            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);

            DeleteEntityRequest delEntReq = new DeleteEntityRequest {
                LogicalName = (_customEntityName)
            };

            _serviceProxy.Execute(delEntReq);

            DeleteEntityRequest delEntReqConfig = new DeleteEntityRequest {
                LogicalName = (_customConfigurationEntityName)
            };

            _serviceProxy.Execute(delEntReqConfig);


            if (_solutionCreated)
            {
                _serviceProxy.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId);

                //delete webresorce
                foreach (var _id in _webResourceIds)
                {
                    _serviceProxy.Delete(WebResource.EntityLogicalName, _id);
                }
                //for configuration page above created delete
                _serviceProxy.Delete(WebResource.EntityLogicalName, _webResourceIdForSolution[0]);
            }

            if (_publisherCreated)
            {
                _serviceProxy.Delete(Publisher.EntityLogicalName, _tempPublisherId);
            }

            Console.WriteLine("Managed Solution created and copied to {0}", _managedSolutionLocation);
        }
Exemplo n.º 22
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // 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 _powerappsSdkPublisher = new Publisher
            {
                UniqueName           = "sdksamples",
                FriendlyName         = "PowerApps 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, _powerappsSdkPublisher.UniqueName);
            EntityCollection querySDKSamplePublisherResults = service.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         = service.Create(_powerappsSdkPublisher);
                _tempCustomizationPrefix = _powerappsSdkPublisher.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 PowerApps 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 = service.RetrieveMultiple(querySampleSolution);
            Solution         SampleSolutionResults      = null;

            if (querySampleSolutionResults.Entities.Count > 0)
            {
                SampleSolutionResults          = (Solution)querySampleSolutionResults.Entities[0];
                _tempSolutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId;
            }
            if (SampleSolutionResults == null)
            {
                _tempSolutionsSampleSolutionId = service.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
            };


            service.Execute(createOptionSetRequest);

            //Export an a solution


            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();

            exportSolutionRequest.Managed      = true;
            exportSolutionRequest.SolutionName = solution.UniqueName;

            ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)service.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()
            };

            service.Execute(delOptSetReq);

            if (_solutionCreated)
            {
                service.Delete(Solution.EntityLogicalName, _tempSolutionsSampleSolutionId);
            }

            if (_publisherCreated)
            {
                service.Delete(Publisher.EntityLogicalName, _tempPublisherId);
            }

            Console.WriteLine("Managed Solution created and copied to {0}", ManagedSolutionLocation);
        }
Exemplo n.º 23
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;
            }
        }
Exemplo n.º 24
0
        public string Export(bool managed,
                             string outputFolder,
                             string solutionName,
                             bool exportAutoNumberingSettings,
                             bool exportCalendarSettings,
                             bool exportCustomizationSettings,
                             bool exportEmailTrackingSettings,
                             bool exportGeneralSettings,
                             bool exportIsvConfig,
                             bool exportMarketingSettings,
                             bool exportOutlookSynchronizationSettings,
                             bool exportRelationshipRoles)
        {
            StringBuilder solutionFile = new StringBuilder();
            Solution      solution     = null;

            using (CIContext context = new CIContext(OrgService))
            {
                var query = from s in context.SolutionSet
                            where s.UniqueName == solutionName
                            select s;

                solution = query.FirstOrDefault <Solution>();
            }

            if (solution == null)
            {
                throw new Exception(string.Format("Solution {0} could not be found", solutionName));
            }
            else
            {
                solutionFile.Append(solutionName);
                solutionFile.Append("_");

                solutionFile.Append(solution.Version.Replace(".", "_"));
            }

            if (managed)
            {
                solutionFile.Append("_managed");
            }

            solutionFile.Append(".zip");

            ExportSolutionRequest req = new ExportSolutionRequest()
            {
                Managed      = managed,
                SolutionName = solutionName,
                ExportAutoNumberingSettings          = exportAutoNumberingSettings,
                ExportCalendarSettings               = exportCalendarSettings,
                ExportCustomizationSettings          = exportCustomizationSettings,
                ExportEmailTrackingSettings          = exportEmailTrackingSettings,
                ExportGeneralSettings                = exportGeneralSettings,
                ExportIsvConfig                      = exportIsvConfig,
                ExportMarketingSettings              = exportMarketingSettings,
                ExportOutlookSynchronizationSettings = exportOutlookSynchronizationSettings,
                ExportRelationshipRoles              = exportRelationshipRoles
            };

            ExportSolutionResponse res = OrgService.Execute(req) as ExportSolutionResponse;

            File.WriteAllBytes(outputFolder + "\\" + solutionFile.ToString(), res.ExportSolutionFile);

            return(solutionFile.ToString());
        }
Exemplo n.º 25
0
        private ValidationResults ValidateManagedSolutionComponents()
        {
            ValidationResults results = new ValidationResults();

            // export the solution as managed and extract it to get the customizations xml
            ExportSolutionRequest exportRequest = new ExportSolutionRequest();

            exportRequest.Managed      = true;
            exportRequest.SolutionName = Solution.UniqueName;
            OnValidatorProgress?.Invoke(this, new ProgressEventArgs("Exporting solution as managed"));
            ExportSolutionResponse managedResponse = CRMService.Execute(exportRequest) as ExportSolutionResponse;

            if (managedResponse != null)
            {
                try
                {
                    string zipFileName         = Solution.UniqueName + ".zip";
                    string customiationXmlPath = Constants.APP_DATA_TEMP_DIRECTOY_PATH + "\\customizations.xml";
                    string zipPath             = Constants.APP_DATA_TEMP_DIRECTOY_PATH + zipFileName;

                    // cleanup an existing directory files
                    if (Directory.Exists(Constants.APP_DATA_TEMP_DIRECTOY_PATH))
                    {
                        Directory.Delete(Constants.APP_DATA_TEMP_DIRECTOY_PATH, true);
                    }

                    // recreate the directory
                    if (!Directory.Exists(Constants.APP_DATA_TEMP_DIRECTOY_PATH))
                    {
                        Directory.CreateDirectory(Constants.APP_DATA_TEMP_DIRECTOY_PATH);
                    }

                    // write the managed solution as a zip file in the directory
                    OnValidatorProgress?.Invoke(this, new ProgressEventArgs("Saving Managed Solution"));
                    File.WriteAllBytes(zipPath, managedResponse.ExportSolutionFile);

                    // extract the zip file to get the customizations.xml file content
                    OnValidatorProgress?.Invoke(this, new ProgressEventArgs("Extracting Managed Solution"));
                    ZipFile.ExtractToDirectory(zipPath, Constants.APP_DATA_TEMP_DIRECTOY_PATH);


                    //at this point customization.xml file should be ready, load it into an xdocument object
                    if (File.Exists(customiationXmlPath))
                    {
                        OnValidatorProgress?.Invoke(this, new ProgressEventArgs("Checking the Customization File"));

                        XDocument customizationsXml = XDocument.Load(customiationXmlPath);
                        results.AddResultSet(CheckAttributes(customizationsXml));
                        results.AddResultSet(CheckViews(customizationsXml));
                        results.AddResultSet(CheckForms(customizationsXml));
                    }
                }

                catch (IOException ioEx)
                {
                    // fire an error to be catched by whoever is listening to the OnValidationError Event
                    OnValidatorError?.Invoke(this, new ErrorEventArgs(ioEx));
                    throw ioEx;
                }
                catch (Exception ex)
                {
                    OnValidatorError?.Invoke(this, new ErrorEventArgs(ex));
                    throw ex;
                }
            }
            return(results);
        }
        private void ExportSolutionBlock(XmlNode xBlock)
        {
            log.StartSection("ExportSolutionBlock");

            if (xBlock.Name != "SolutionBlock")
            {
                throw new ArgumentOutOfRangeException("Type", xBlock.Name, "Invalid Block type");
            }
            string name = CintXML.GetAttribute(xBlock, "Name");

            log.Log("Block: {0}", name);
            string path = CintXML.GetAttribute(xBlock, "Path");
            string file = CintXML.GetAttribute(xBlock, "File");

            if (string.IsNullOrWhiteSpace(path) && !string.IsNullOrWhiteSpace(definitionpath))
            {
                path  = definitionpath;
                path += path.EndsWith("\\") ? "" : "\\";
            }
            if (string.IsNullOrWhiteSpace(file))
            {
                file = name;
            }
            XmlNode xExport = CintXML.FindChild(xBlock, "Export");

            if (xExport != null)
            {
                string type          = CintXML.GetAttribute(xExport, "Type");
                string setversion    = CintXML.GetAttribute(xExport, "SetVersion");
                bool   publish       = CintXML.GetBoolAttribute(xExport, "PublishBeforeExport", false);
                string targetversion = CintXML.GetAttribute(xExport, "TargetVersion");

                CintDynEntity cdSolution     = GetAndVerifySolutionForExport(name);
                var           currentversion = new Version(cdSolution.Property("version", "1.0.0.0"));

                SendLine("Solution: {0} {1}", name, currentversion);

                if (!string.IsNullOrWhiteSpace(setversion))
                {
                    SetNewSolutionVersion(setversion, cdSolution, currentversion);
                }

                if (publish)
                {
                    SendLine("Publishing customizations");
                    crmsvc.Execute(new PublishAllXmlRequest());
                }

                ExportSolutionRequest req = new ExportSolutionRequest()
                {
                    SolutionName = name
                };
#if Crm8
                if (!string.IsNullOrWhiteSpace(targetversion))
                {
                    req.TargetVersion = targetversion;
                }
#endif
                XmlNode xSettings = CintXML.FindChild(xExport, "Settings");
                if (xSettings != null)
                {
                    req.ExportAutoNumberingSettings          = CintXML.GetBoolAttribute(xSettings, "AutoNumbering", false);
                    req.ExportCalendarSettings               = CintXML.GetBoolAttribute(xSettings, "Calendar", false);
                    req.ExportCustomizationSettings          = CintXML.GetBoolAttribute(xSettings, "Customization", false);
                    req.ExportEmailTrackingSettings          = CintXML.GetBoolAttribute(xSettings, "EmailTracking", false);
                    req.ExportGeneralSettings                = CintXML.GetBoolAttribute(xSettings, "General", false);
                    req.ExportMarketingSettings              = CintXML.GetBoolAttribute(xSettings, "Marketing", false);
                    req.ExportOutlookSynchronizationSettings = CintXML.GetBoolAttribute(xSettings, "OutlookSync", false);
                    req.ExportRelationshipRoles              = CintXML.GetBoolAttribute(xSettings, "RelationshipRoles", false);
                    req.ExportIsvConfig = CintXML.GetBoolAttribute(xSettings, "IsvConfig", false);
                }

                if (type == "Managed" || type == "Both")
                {
                    string filename = path + file + "_managed.zip";
                    SendLine("Exporting solution to: {0}", filename);
                    req.Managed = true;
                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmsvc.Execute(req);
                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                    File.WriteAllBytes(filename, exportXml);
                }
                if (type == "Unmanaged" || type == "Both")
                {
                    string filename = path + file + ".zip";
                    SendLine("Exporting solution to: {0}", filename);
                    req.Managed = false;
                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmsvc.Execute(req);
                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                    File.WriteAllBytes(filename, exportXml);
                }
            }
            log.EndSection();
        }