/******
         *  XrmToolBox - Code Now - Find and remove invalid attributes -> bettercrm.blog/.../query-builder-error-when-exporting-solution-in-dynamics-365
         *  Add These to the Using box on the right
         *
         *  using System;
         *  using Microsoft.Xrm.Sdk;
         *  using Microsoft.Xrm.Sdk.Query;
         *  using Microsoft.Xrm.Sdk.Messages;
         *  using Microsoft.Crm.Sdk.Messages;
         *******/

        public void CodeNow(IOrganizationService service, string solutionName)
        {
            string SOLUTION_NAME = solutionName;

            LogMessage("------------- Start -----------------");
            LogMessage("Solution " + SOLUTION_NAME);

            var solutionComponentQuery = new QueryExpression("solutioncomponent");

            solutionComponentQuery.Distinct = true;
            solutionComponentQuery.ColumnSet.AddColumns("objectid", "componenttype", "solutioncomponentid");
            var solutioncomponentSolutionLink = solutionComponentQuery.AddLink("solution", "solutionid", "solutionid");

            solutioncomponentSolutionLink.EntityAlias = "aa";
            solutioncomponentSolutionLink.LinkCriteria.AddCondition("uniquename", ConditionOperator.Equal, SOLUTION_NAME);

            var results = service.RetrieveMultiple(solutionComponentQuery);

            foreach (var item in results.Entities)
            {
                var componentType = item.GetAttributeValue <OptionSetValue>("componenttype").Value;
                //LogMessage("Checking Component " + componentType);
                if (componentType == 2)
                {
                    //LogMessage("Checking Attribute");
                    var attributeRequest = new RetrieveAttributeRequest
                    {
                        MetadataId = item.GetAttributeValue <Guid>("objectid")
                    };

                    try
                    {
                        var result = (RetrieveAttributeResponse)service.Execute(attributeRequest);
                        LogMessage("Attribute " + result.AttributeMetadata.LogicalName + " is valid");
                    }
                    catch
                    {
                        // //attribute is missing, remove it from solution
                        LogMessage("Attribute {" + attributeRequest.MetadataId + "} is missing. Removing from the solution.");

                        var removeRequest = new RemoveSolutionComponentRequest
                        {
                            SolutionUniqueName = SOLUTION_NAME,
                            ComponentId        = attributeRequest.MetadataId,
                            ComponentType      = componentType
                        };
                        service.Execute(removeRequest);
                    }
                }
            }
            LogMessage("----------------------DONE-------------------");
        }
Beispiel #2
0
        private void RemoveWebresourceFromSolution(string solutionName, WebResource webresource)
        {
            // Find solution
            RemoveSolutionComponentRequest removeFromSolution = new RemoveSolutionComponentRequest()
            {
                ComponentType      = (int)componenttype.WebResource,
                ComponentId        = webresource.Id,
                SolutionUniqueName = solutionName
            };

            _trace.WriteLine(string.Format("Solution: '{0}' Removing: '{1}'", solutionName, webresource.Name));
            _service.Execute(removeFromSolution);
        }
        public static void RemoveAllSolutionComponent(EntityCollection solutionComponents, string solnUniqueName)
        {
            try
            {
                if (solutionComponents == null || solutionComponents.Entities.Count == 0)
                {
                    return;
                }
                Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Preparing to empty Solution : " + solnUniqueName); Console.ForegroundColor = ConsoleColor.White;

                foreach (var component in solutionComponents.Entities)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    try
                    {
                        RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest()
                        {
                            ComponentId        = component.GetAttributeValue <Guid>("objectid"),
                            ComponentType      = component.GetAttributeValue <OptionSetValue>("componenttype").Value,
                            SolutionUniqueName = solnUniqueName
                        };
                        _serviceProxy.Execute(removeReq);
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(Environment.NewLine + "\nFailed to Remove Solution Component - {0}", component.GetAttributeValue <Guid>("objectid").ToString().PadRight(20, '.'));
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    Console.WriteLine(Environment.NewLine + "Removed Solution Component - {0}", component.GetAttributeValue <Guid>("objectid").ToString().PadRight(20, '.'));
                }
                Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Completed {0} truncation with above status", solnUniqueName); Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Access to remove solution component failed");
                Console.ForegroundColor = ConsoleColor.White;
            }
            finally
            {
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        private void RemoveSolutionComponents(string solutionUniqueName, IEnumerable <SolutionComponent> components)
        {
            foreach (var component in components.Where(c => c.ObjectId.HasValue && c.ComponentType != null).OrderByDescending(c => c.ComponentType?.Value))
            {
                RemoveSolutionComponentRequest request = new RemoveSolutionComponentRequest()
                {
                    SolutionUniqueName = solutionUniqueName,

                    ComponentType = component.ComponentType.Value,
                    ComponentId   = component.ObjectId.Value,
                };

                try
                {
                    var response = (RemoveSolutionComponentResponse)_service.Execute(request);
                }
                catch (Exception ex)
                {
                    Helpers.DTEHelper.WriteExceptionToOutput(_service.ConnectionData, ex);
                }
            }
        }
Beispiel #5
0
        public static void CleanSolution(IOrganizationService service, string uniqueName)
        {
            var solution = GetSolution(service, uniqueName);

            if (solution != null)
            {
                var solutionComponents = GetSolutionComponents(service, solution.Id)
                                         .OrderBy(k => k.GetOrderWeight())
                                         .Reverse();

                foreach (var item in solutionComponents)
                {
                    RemoveSolutionComponentRequest req = new RemoveSolutionComponentRequest()
                    {
                        ComponentId        = item.ObjectId,
                        ComponentType      = (int)item.Type,
                        SolutionUniqueName = uniqueName,
                    };
                    service.Execute(req);
                }
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            base.WriteVerbose(string.Format("Removing Solution Components: {0}", SolutionName));

            using (var context = new CIContext(OrganizationService))
            {
                var query1 = from solution in context.SolutionSet
                             where solution.UniqueName == SolutionName
                             select solution.Id;

                if (query1 == null)
                {
                    throw new Exception(string.Format("Solution {0} could not be found", SolutionName));
                }

                var solutionId = query1.FirstOrDefault();

                var query = from s in context.SolutionComponentSet
                            where s.SolutionId == new EntityReference(Solution.EntityLogicalName, solutionId) && s.RootSolutionComponentId == null
                            select new { s.ComponentType, s.ObjectId };

                foreach (var solutionComponent in query.ToList())
                {
                    var removeReq = new RemoveSolutionComponentRequest()
                    {
                        ComponentId        = (Guid)solutionComponent.ObjectId,
                        ComponentType      = (int)solutionComponent.ComponentType.Value,
                        SolutionUniqueName = SolutionName
                    };
                    OrganizationService.Execute(removeReq);
                    base.WriteVerbose(string.Format("Removed component from solution with Id : {0} and Type: {1}", solutionComponent.ObjectId, solutionComponent.ComponentType.Value));
                }
            }
        }
Beispiel #7
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;
            }
        }
        [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();
            }
        }
Beispiel #9
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;
            }
        }