Ejemplo n.º 1
0
        public static List <OptionSetMetadataBase> GetOptionSetMetadata(IOrganizationService service)
        {
            RetrieveAllOptionSetsRequest  req = new RetrieveAllOptionSetsRequest();
            RetrieveAllOptionSetsResponse res = (RetrieveAllOptionSetsResponse)service.Execute(req);

            return(res.OptionSetMetadata.ToList());
        }
Ejemplo n.º 2
0
        private OptionSetMetadata[] RetrieveGlobalOptionSetsMetadataFromServer(IOrganizationService service)
        {
            var results = new List <OptionSetMetadata>();
            // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
            // Create the request.
            RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest();

            // Execute the request
            RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)service.Execute(retrieveAllOptionSetsRequest);

            //return retrieveAllOptionSetsResponse.OptionSetMetadata;
            // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
            // work with all retrieved option sets.
            if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
            {
                Console.WriteLine("All the global option sets retrieved as below:");
                foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata)
                {
                    if (!optionSetMetadata.IsManaged.Value && optionSetMetadata.IsGlobal.Value)
                    {
                        RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                            Name = optionSetMetadata.Name
                        };
                        // Execute the request.
                        RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);
                        results.Add((OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata);
                    }
                }
            }

            return(results.ToArray());
        }
Ejemplo n.º 3
0
        public OptionSetMetadataBase[] RetrieveAllOptionSets()
        {
            var optionSetRequest = new RetrieveAllOptionSetsRequest {
                RetrieveAsIfPublished = true
            };
            var results = service.Execute(optionSetRequest) as RetrieveAllOptionSetsResponse;

            return(results.OptionSetMetadata);
        }
        public OptionSetMetadataBase[] retrieveAllGlobalOptionSets()
        {
            RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                new RetrieveAllOptionSetsRequest();

            RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                (RetrieveAllOptionSetsResponse)Service.Execute(retrieveAllOptionSetsRequest);

            return(retrieveAllOptionSetsResponse.OptionSetMetadata);
        }
        public static List<OptionSetMetadataBase > RetrieveGlobalOptionSets(IOrganizationService service, bool retrieveAsIfPublished = true, string solutionName = null) {
            var request = new RetrieveAllOptionSetsRequest() {
                RetrieveAsIfPublished = retrieveAsIfPublished
            };

            // Execute the request
            var response = (RetrieveAllOptionSetsResponse)service.Execute(request);

            return response.OptionSetMetadata.ToList();
        }
Ejemplo n.º 6
0
        private List <OptionSetMetadata> GetOptionSets()
        {
            RetrieveAllOptionSetsRequest request = new RetrieveAllOptionSetsRequest();

            RetrieveAllOptionSetsResponse retrieve = (RetrieveAllOptionSetsResponse)_service.Execute(request);

            return(retrieve
                   .OptionSetMetadata
                   .OfType <OptionSetMetadata>()
                   .Where(e => e.Options.Any(o => o.Value.HasValue))
                   .OrderBy(e => e.Name)
                   .ToList());
        }
        public OrganizationData(IOrganizationService orgService)
        {
            var optionSetRequest = new RetrieveAllOptionSetsRequest();
            var entityRequest = new RetrieveAllEntitiesRequest
            {
                EntityFilters = EntityFilters.Entity | EntityFilters.Attributes,
                RetrieveAsIfPublished = false
            };

            OptionSets = ((RetrieveAllOptionSetsResponse)orgService.Execute(optionSetRequest))
                .OptionSetMetadata.OrderBy(o => o.Name).ToArray();

            Entities = ((RetrieveAllEntitiesResponse)orgService.Execute(entityRequest))
                .EntityMetadata.OrderBy(e => e.LogicalName).ToArray();
        }
Ejemplo n.º 8
0
        private List <OptionSetMetadata> GetListByIdList(IEnumerable <Guid> ids)
        {
            RetrieveAllOptionSetsRequest request = new RetrieveAllOptionSetsRequest();

            RetrieveAllOptionSetsResponse retrieve = (RetrieveAllOptionSetsResponse)_service.Execute(request);

            var hash = new HashSet <Guid>(ids);

            return(retrieve
                   .OptionSetMetadata
                   .OfType <OptionSetMetadata>()
                   .Where(e => e.Options.Any(o => o.Value.HasValue) && hash.Contains(e.MetadataId.Value))
                   .OrderBy(e => e.Name)
                   .ToList());
        }
Ejemplo n.º 9
0
        public List <string> GetGlobalOptionSets()
        {
            var result = new List <string>();

            RetrieveAllOptionSetsRequest raor = new RetrieveAllOptionSetsRequest
            {
                RetrieveAsIfPublished = true,
            };

            var response = (RetrieveAllOptionSetsResponse)_client.Execute(raor);

            foreach (var r in response.OptionSetMetadata)
            {
                if (r.IsGlobal.HasValue && r.IsGlobal.Value)
                {
                    result.Add(r.Name);
                }
            }

            return(result);
        }
        /// <summary>
        /// Gets an <c>ICollection</c> containing <c>Key</c> objects that match the supplied modifiedDate
        /// </summary>
        /// <param name="modifiedDate">A <c>DateTime</c> containing the last modified date for the object keys to be returned</param>
        /// <returns>An <c>ICollection</c> containing keys that can be used to retrieve instances of the provided object from the source system</returns>
        public ICollection ReadObjectKeys(DateTime modifiedDate)
        {
            List <Guid> keys = new List <Guid>();

            // Retrieve all entities and parse for local picklists
            RetrieveAllEntitiesRequest allRequest = new RetrieveAllEntitiesRequest()
            {
                RetrieveAsIfPublished = true, EntityFilters = EntityFilters.Attributes
            };
            RetrieveAllEntitiesResponse allresponse = (RetrieveAllEntitiesResponse)this.CallMetadataExecuteWebMethod(allRequest);

            foreach (var meta in allresponse.EntityMetadata.OrderBy(x => x.LogicalName))
            {
                var picklistMeta = meta.Attributes.Where(x => x.AttributeType == AttributeTypeCode.Picklist && x.IsCustomizable.Value == true && meta.DisplayName.LocalizedLabels.Count > 0);
                if (picklistMeta.Count() > 0)
                {
                    if (picklistMeta.Cast <PicklistAttributeMetadata>().Any(x => x.OptionSet.IsGlobal.Value == false))
                    {
                        keys.Add(meta.MetadataId.Value);
                    }
                }
            }

            // Retrieve global option sets that are customizable
            var globalOptionSetRequest = new RetrieveAllOptionSetsRequest()
            {
                RetrieveAsIfPublished = true
            };
            var globalResponse         = (RetrieveAllOptionSetsResponse)this.CallMetadataExecuteWebMethod(globalOptionSetRequest);
            var usableGlobalOptionSets = globalResponse.OptionSetMetadata.Where(x => x.IsCustomizable.Value == true && x.DisplayName.LocalizedLabels.Count > 0);

            foreach (var globalOption in usableGlobalOptionSets)
            {
                keys.Add(globalOption.MetadataId.Value);
            }

            return(keys);
        }
        private void FillPicklistObjectDef(ObjectDefinition objDef)
        {
            var entityMetaDataRequest = new RetrieveAllEntitiesRequest();
            entityMetaDataRequest.EntityFilters = EntityFilters.Attributes;
            entityMetaDataRequest.RetrieveAsIfPublished = true;
            var entityMetaDataResponse = this.InstallAdapter.OrganizationService.Execute(entityMetaDataRequest) as RetrieveAllEntitiesResponse;

            GeneratePicklistObjectDefinitionEntries(objDef, entityMetaDataResponse);

            var allSetsRequest = new RetrieveAllOptionSetsRequest();
            var allSetsResponse = this.InstallAdapter.OrganizationService.Execute(allSetsRequest) as RetrieveAllOptionSetsResponse;
            GenerateGlobalPicklistObjectDefinitionEntries(objDef, allSetsResponse);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// </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(IOrganizationService service, string solutionName)
        {
            try
            {
                //  string serverName = "https://workflow.crm.dynamics.com/Workflow_10312017";
                //  Uri organizationUri = new Uri(string.Format("{0}/XRMServices/2011/Organization.svc", serverName));
                //  Uri homeRealmUri = null;
                //  ClientCredentials credentials = new ClientCredentials();

                //  //use UserName object for CRM Online

                //credentials.UserName.UserName = "******";
                //credentials.UserName.Password = "******";

                //  use default for OnPrem...
                //credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;

                //IOrganizationService service = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);

                #region How to dump option set info
                RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                    new RetrieveAllOptionSetsRequest();

                // Execute the request
                RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                    (RetrieveAllOptionSetsResponse)service.Execute(
                        retrieveAllOptionSetsRequest);

                // Create an instance of StreamWriter to write text to a file.
                // The using statement also closes the StreamWriter.
                // To view this file, right click the file and choose open with Excel.
                // Excel will figure out the schema and display the information in columns.

                String filename = String.Concat("AllOptionSetValues.xml");
                using (StreamWriter sw = new StreamWriter(filename))
                {
                    // Create Xml Writer.
                    XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                    // Start Xml File.
                    metadataWriter.WriteStartDocument();

                    // Metadata Xml Node.
                    metadataWriter.WriteStartElement("Metadata");

                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        foreach (OptionSetMetadataBase optionSetMetadataBase in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            if (optionSetMetadataBase.OptionSetType != null)
                            {
                                if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Picklist)
                                {
                                    OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSetMetadataBase;
                                    // Start OptionSet Node
                                    metadataWriter.WriteStartElement("OptionSet");
                                    metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Picklist.ToString());
                                    metadataWriter.WriteElementString("OptionSetDisplayName",
                                                                      (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);

                                    // Writes the options
                                    metadataWriter.WriteStartElement("Options");

                                    foreach (OptionMetadata option in optionSetMetadata.Options)
                                    {
                                        metadataWriter.WriteStartElement("Option");
                                        metadataWriter.WriteElementString("OptionValue", option.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", option.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();
                                    }
                                    metadataWriter.WriteEndElement();

                                    // End OptionSet Node
                                    metadataWriter.WriteEndElement();
                                }
                                else if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Boolean)
                                {
                                    BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSetMetadataBase;
                                    // Start OptionSet Node
                                    metadataWriter.WriteStartElement("OptionSet");
                                    metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Boolean.ToString());
                                    if (optionSetMetadata.DisplayName.LocalizedLabels.Count != 0)
                                    {
                                        metadataWriter.WriteElementString("OptionSetDisplayName", optionSetMetadata.DisplayName.LocalizedLabels[0].Label);
                                    }
                                    else
                                    {
                                        metadataWriter.WriteElementString("OptionSetDisplayName", "UNDEFINED");
                                    }

                                    // Writes the TrueOption
                                    metadataWriter.WriteStartElement("TrueOption");
                                    metadataWriter.WriteElementString("OptionValue", optionSetMetadata.TrueOption.Value.ToString());
                                    metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label.ToString());
                                    metadataWriter.WriteEndElement();
                                    // Writes the FalseOption
                                    metadataWriter.WriteStartElement("FalseOption");
                                    metadataWriter.WriteElementString("OptionValue", optionSetMetadata.FalseOption.Value.ToString());
                                    metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label.ToString());
                                    metadataWriter.WriteEndElement();

                                    // End OptionSet Node
                                    metadataWriter.WriteEndElement();
                                }
                            }
                        }
                    }

                    // End Metadata Xml Node
                    metadataWriter.WriteEndElement();
                    metadataWriter.WriteEndDocument();

                    // Close xml writer.
                    metadataWriter.Close();
                }

                #endregion How to dump option set info
                Console.WriteLine("Done.");
                //DeleteRequiredRecords(promptForDelete);
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// OptionSet Id;OptionSet Name;OptionSetValue;Type;LCID1;LCID2;...;LCIDX
        /// </example>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        /// <param name="service"></param>
        /// <param name="settings"></param>
        public void Export(List <int> languages, ExcelWorksheet sheet, IOrganizationService service, ExportSettings settings)
        {
            var line = 0;

            AddHeader(sheet, languages);

            var request  = new RetrieveAllOptionSetsRequest();
            var response = (RetrieveAllOptionSetsResponse)service.Execute(request);
            var omds     = response.OptionSetMetadata;

            if (settings.SolutionId != Guid.Empty)
            {
                var oids = service.GetSolutionComponentObjectIds(settings.SolutionId, 9); // 9 = Global OptionSets
                omds = omds.Where(o => oids.Contains(o.MetadataId ?? Guid.Empty)).ToArray();
            }

            foreach (var omd in omds)
            {
                int cell;
                if (omd is OptionSetMetadata oomd)
                {
                    foreach (var option in oomd.Options.OrderBy(o => o.Value))
                    {
                        if (settings.ExportNames)
                        {
                            line++;
                            cell = 0;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = (oomd.MetadataId ?? Guid.Empty).ToString("B");
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = oomd.Name;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                            foreach (var lcid in languages)
                            {
                                var label = string.Empty;

                                var optionLabel =
                                    option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                                if (optionLabel != null)
                                {
                                    label = optionLabel.Label;
                                }

                                ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                            }
                        }

                        if (settings.ExportDescriptions)
                        {
                            line++;
                            cell = 0;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = (oomd.MetadataId ?? Guid.Empty).ToString("B");
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = oomd.Name;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                            foreach (var lcid in languages)
                            {
                                var label = string.Empty;

                                var optionDescription =
                                    option.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                                if (optionDescription != null)
                                {
                                    label = optionDescription.Label;
                                }

                                ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                            }
                        }
                    }
                }
                else if (omd is BooleanOptionSetMetadata)
                {
                    var bomd = (BooleanOptionSetMetadata)omd;

                    if (settings.ExportNames)
                    {
                        line++;
                        cell = 0;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = (omd.MetadataId ?? Guid.Empty).ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            if (bomd.FalseOption.Label != null)
                            {
                                var optionLabel =
                                    bomd.FalseOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                                if (optionLabel != null)
                                {
                                    label = optionLabel.Label;
                                }
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }
                    }

                    if (settings.ExportDescriptions)
                    {
                        line++;
                        cell = 0;

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = (omd.MetadataId ?? Guid.Empty).ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            if (bomd.FalseOption.Description != null)
                            {
                                var optionLabel =
                                    bomd.FalseOption.Description.LocalizedLabels.FirstOrDefault(l =>
                                                                                                l.LanguageCode == lcid);
                                if (optionLabel != null)
                                {
                                    label = optionLabel.Label;
                                }
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }
                    }

                    if (settings.ExportNames)
                    {
                        line++;
                        cell = 0;

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = (omd.MetadataId ?? Guid.Empty).ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            if (bomd.TrueOption.Label != null)
                            {
                                var optionLabel =
                                    bomd.TrueOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                                if (optionLabel != null)
                                {
                                    label = optionLabel.Label;
                                }
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }
                    }

                    if (settings.ExportDescriptions)
                    {
                        line++;
                        cell = 0;

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = (omd.MetadataId ?? Guid.Empty).ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            if (bomd.TrueOption.Description != null)
                            {
                                var optionLabel =
                                    bomd.TrueOption.Description.LocalizedLabels.FirstOrDefault(l =>
                                                                                               l.LanguageCode == lcid);
                                if (optionLabel != null)
                                {
                                    label = optionLabel.Label;
                                }
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }
                    }
                }
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i <= line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// OptionSet Id;OptionSet Name;OptionSetValue;Type;LCID1;LCID2;...;LCIDX
        /// </example>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        /// <param name="service"></param>
        public void Export(List<int> languages, ExcelWorksheet sheet, IOrganizationService service)
        {
            var line = 1;

            AddHeader(sheet, languages);

            var request = new RetrieveAllOptionSetsRequest();
            var response = (RetrieveAllOptionSetsResponse)service.Execute(request);

            foreach (var omd in response.OptionSetMetadata)
            {
                if (omd is OptionSetMetadata)
                {
                    var oomd = (OptionSetMetadata)omd;
                    foreach (var option in oomd.Options.OrderBy(o => o.Value))
                    {
                        var cell = 0;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            var optionLabel = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }

                        line++;
                        cell = 0;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            var optionDescription = option.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionDescription != null)
                            {
                                label = optionDescription.Label;
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }

                        line++;
                    }
                }
                else if (omd is BooleanOptionSetMetadata)
                {
                    var bomd = (BooleanOptionSetMetadata)omd;

                    var cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.FalseOption.Label != null)
                        {
                            var optionLabel =
                                bomd.FalseOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.FalseOption.Description != null)
                        {
                            var optionLabel =
                                bomd.FalseOption.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.TrueOption.Label != null)
                        {
                            var optionLabel =
                                bomd.TrueOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.TrueOption.Description != null)
                        {
                            var optionLabel =
                                bomd.TrueOption.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                }
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
        /// <summary>
        /// Gets an <c>ICollection</c> containing <c>Key</c> objects that match the supplied modifiedDate
        /// </summary>
        /// <param name="modifiedDate">A <c>DateTime</c> containing the last modified date for the object keys to be returned</param>
        /// <returns>An <c>ICollection</c> containing keys that can be used to retrieve instances of the provided object from the source system</returns>
        public ICollection ReadObjectKeys(DateTime modifiedDate)
        {
            List<Guid> keys = new List<Guid>();

            // Retrieve all entities and parse for local picklists
            RetrieveAllEntitiesRequest allRequest = new RetrieveAllEntitiesRequest() { RetrieveAsIfPublished = true, EntityFilters = EntityFilters.Attributes };
            RetrieveAllEntitiesResponse allresponse = (RetrieveAllEntitiesResponse)this.CallMetadataExecuteWebMethod(allRequest);
            foreach (var meta in allresponse.EntityMetadata.OrderBy(x => x.LogicalName))
            {
                var picklistMeta = meta.Attributes.Where(x => x.AttributeType == AttributeTypeCode.Picklist && x.IsCustomizable.Value == true && meta.DisplayName.LocalizedLabels.Count > 0);
                if (picklistMeta.Count() > 0)
                {
                    if (picklistMeta.Cast<PicklistAttributeMetadata>().Any(x => x.OptionSet.IsGlobal.Value == false))
                    {
                        keys.Add(meta.MetadataId.Value);
                    }
                }
            }

            // Retrieve global option sets that are customizable
            var globalOptionSetRequest = new RetrieveAllOptionSetsRequest() { RetrieveAsIfPublished = true };
            var globalResponse = (RetrieveAllOptionSetsResponse)this.CallMetadataExecuteWebMethod(globalOptionSetRequest);
            var usableGlobalOptionSets = globalResponse.OptionSetMetadata.Where(x => x.IsCustomizable.Value == true && x.DisplayName.LocalizedLabels.Count > 0);

            foreach (var globalOption in usableGlobalOptionSets)
            {
                keys.Add(globalOption.MetadataId.Value);
            }

            return keys;
        }
 private void LoadGlobalOptionSets()
 {
     WorkAsync("Retrieving global optionsets...",
         (e) =>
         {
             cboOptionSets.Items.Clear();
             RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest();
             RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)Service.Execute(retrieveAllOptionSetsRequest);
             if (retrieveAllOptionSetsResponse.OptionSetMetadata != null
                 && retrieveAllOptionSetsResponse.OptionSetMetadata.Length > 0)
             {
                 var optionsets = new Dictionary<string, string>();
                 foreach (var om in retrieveAllOptionSetsResponse.OptionSetMetadata)
                 {
                     if (om.IsCustomizable.Value == true)
                     {
                         cboOptionSets.Items.Add(new Item(
                                 string.Format("{0} ({1})", om.DisplayName.LocalizedLabels.FirstOrDefault().Label, om.Name),
                                 om.Name)
                             );
                     }
                 }
             }
         },
         e =>
         {
         }
     );
 }
        /// <summary>
        /// Create a global option set.
        /// Set the options for that option set.
        /// Create a new reference to that option set on an entity.
        /// Update the option set's properties.
        /// Check the global option set for dependencies.
        /// Delete the option set.
        /// </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();

                    #region How to create global option set
                    // Define the request object and pass to the service.
                    CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name          = _globalOptionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(new Label("Open",      _languageCode), null),
                                new OptionMetadata(new Label("Suspended", _languageCode), null),
                                new OptionMetadata(new Label("Cancelled", _languageCode), null),
                                new OptionMetadata(new Label("Closed",    _languageCode), null)
                            }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest);

                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    CreateAttributeRequest createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute  = new PicklistAttributeMetadata
                        {
                            SchemaName    = "sample_examplepicklist",
                            LogicalName   = "sample_examplepicklist",
                            DisplayName   = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name     = _globalOptionSetName
                            }
                        }
                    };

                    _serviceProxy.Execute(createRequest);
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name        = _globalOptionSetName,
                            IsGlobal    = true
                        }
                    };

                    _serviceProxy.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq1 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq1);
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    // Use InsertOptionValueRequest to insert a new option into a
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        Label         = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request and store the newly inserted option value
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                                                insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq2);
                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

                    // Execute the request.
                    RetrieveOptionSetResponse retrieveOptionSetResponse =
                        (RetrieveOptionSetResponse)_serviceProxy.Execute(
                            retrieveOptionSetRequest);

                    Console.WriteLine("Retrieved {0}.",
                                      retrieveOptionSetRequest.Name);

                    // Access the retrieved OptionSetMetadata.
                    OptionSetMetadata retrievedOptionSetMetadata =
                        (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        // Update the second option value.
                        Value = optionList[1].Value.Value,
                        Label = new Label("Updated Option 1", _languageCode)
                    };

                    _serviceProxy.Execute(updateOptionValueRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq3 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq3);



                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    _serviceProxy.Execute(pxReq4);
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                            retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                              (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    #endregion How to retrieve all global option sets



                    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;
            }
        }
Ejemplo n.º 18
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    // Define the request object and pass to the service.
                    var createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name          = _globalOptionSetName,
                            DisplayName   = new Label("Example Option Set", _languageCode),
                            IsGlobal      = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options       =
                            {
                                new OptionMetadata(new Label("Open",      _languageCode), null),
                                new OptionMetadata(new Label("Suspended", _languageCode), null),
                                new OptionMetadata(new Label("Cancelled", _languageCode), null),
                                new OptionMetadata(new Label("Closed",    _languageCode), null)
                            }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)service.Execute(createOptionSetRequest);

                    //</snippetWorkwithGlobalOptionSets2>
                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    //<snippetWorkwithGlobalOptionSets3>
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    var createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute  = new PicklistAttributeMetadata
                        {
                            SchemaName    = "sample_examplepicklist",
                            LogicalName   = "sample_examplepicklist",
                            DisplayName   = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name     = _globalOptionSetName
                            }
                        }
                    };

                    service.Execute(createRequest);
                    //</snippetWorkwithGlobalOptionSets3>
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    //<snippetWorkwithGlobalOptionSets4>
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    var updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name        = _globalOptionSetName,
                            IsGlobal    = true
                        }
                    };

                    service.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    var pxReq1 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq1);
                    //</snippetWorkwithGlobalOptionSets4>
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    //<snippetWorkwithGlobalOptionSets5>
                    // Use InsertOptionValueRequest to insert a new option into a
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        Label         = new Label("New Picklist Label", _languageCode)
                    };

                    // Execute the request and store the newly inserted option value
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(
                                                insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq2);
                    //</snippetWorkwithGlobalOptionSets5>
                    Console.WriteLine("Created {0} with the value of {1}.",
                                      insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                                      _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    //<snippetWorkwithGlobalOptionSets6>
                    // Use the RetrieveOptionSetRequest message to retrieve
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                    {
                        Name = _globalOptionSetName
                    };

                    // Execute the request.
                    RetrieveOptionSetResponse retrieveOptionSetResponse =
                        (RetrieveOptionSetResponse)service.Execute(
                            retrieveOptionSetRequest);

                    Console.WriteLine("Retrieved {0}.",
                                      retrieveOptionSetRequest.Name);

                    // Access the retrieved OptionSetMetadata.
                    OptionSetMetadata retrievedOptionSetMetadata =
                        (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    //</snippetWorkwithGlobalOptionSets6>
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    //<snippetWorkwithGlobalOptionSets7>
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                    {
                        OptionSetName = _globalOptionSetName,
                        // Update the second option value.
                        Value = optionList[1].Value.Value,
                        Label = new Label("Updated Option 1", _languageCode)
                    };

                    service.Execute(updateOptionValueRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq3 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq3);



                    //</snippetWorkwithGlobalOptionSets7>
                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    //<snippetWorkwithGlobalOptionSets8>
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    service.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest {
                        ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
                    };
                    service.Execute(pxReq4);
                    //</snippetWorkwithGlobalOptionSets8>
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    //<snippetWorkwithGlobalOptionSets9>
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)service.Execute(
                            retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                                 retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                              (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                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();
            }
        }
Ejemplo n.º 19
0
        private async Task CheckingGlobalOptionSetDuplicates(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(Properties.OutputStrings.ConnectingToCRM);
            content.AppendLine(connectionData.GetConnectionDescription());
            content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine();

            var entityMetadataSource = new SolutionComponentMetadataSource(service);

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.WithUrls          = true;
            descriptor.WithManagedInfo   = true;
            descriptor.WithSolutionsInfo = true;

            var dependencyRepository = new DependencyRepository(service);
            var descriptorHandler    = new DependencyDescriptionHandler(descriptor);

            RetrieveAllOptionSetsRequest request = new RetrieveAllOptionSetsRequest();

            RetrieveAllOptionSetsResponse response = (RetrieveAllOptionSetsResponse)service.Execute(request);

            bool hasInfo = false;

            foreach (var optionSet in response.OptionSetMetadata.OfType <OptionSetMetadata>().OrderBy(e => e.Name))
            {
                var coll = await dependencyRepository.GetDependentComponentsAsync((int)ComponentType.OptionSet, optionSet.MetadataId.Value);

                if (coll.Any())
                {
                    var filter = coll
                                 .Where(c => c.DependentComponentType.Value == (int)ComponentType.Attribute)
                                 .Select(c => new { Dependency = c, Attribute = entityMetadataSource.GetAttributeMetadata(c.DependentComponentObjectId.Value) })
                                 .Where(c => c.Attribute != null)
                                 .GroupBy(c => c.Attribute.EntityLogicalName)
                                 .Where(gr => gr.Count() > 1)
                                 .SelectMany(gr => gr.Select(c => c.Dependency))
                                 .ToList()
                    ;

                    if (filter.Any())
                    {
                        var desc = await descriptorHandler.GetDescriptionDependentAsync(filter);

                        if (!string.IsNullOrEmpty(desc))
                        {
                            if (content.Length > 0)
                            {
                                content
                                .AppendLine(new string('-', 150))
                                .AppendLine();
                            }

                            hasInfo = true;

                            content.AppendFormat("Global OptionSet Name {0}       IsCustomOptionSet {1}      IsManaged {2}", optionSet.Name, optionSet.IsCustomOptionSet, optionSet.IsManaged).AppendLine();

                            content.AppendLine(desc);
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine("No duplicates were found.");
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string fileName = string.Format("{0}.Checking Global OptionSet Duplicates on Entity at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithCheckingGlobalOptionSetDuplicatesOnEntityFormat1, filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        /// <summary>
        /// </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();

                    #region How to dump option set info


                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                            retrieveAllOptionSetsRequest);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AllOptionSetValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                        {
                            foreach (OptionSetMetadataBase optionSetMetadataBase in
                                     retrieveAllOptionSetsResponse.OptionSetMetadata)
                            {
                                if (optionSetMetadataBase.OptionSetType != null)
                                {
                                    if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Picklist)
                                    {
                                        OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Picklist.ToString());
                                        metadataWriter.WriteElementString("OptionSetDisplayName",
                                                                          (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);

                                        // Writes the options
                                        metadataWriter.WriteStartElement("Options");

                                        foreach (OptionMetadata option in optionSetMetadata.Options)
                                        {
                                            metadataWriter.WriteStartElement("Option");
                                            metadataWriter.WriteElementString("OptionValue", option.Value.ToString());
                                            metadataWriter.WriteElementString("OptionDescription", option.Label.UserLocalizedLabel.Label.ToString());
                                            metadataWriter.WriteEndElement();
                                        }
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                    else if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Boolean)
                                    {
                                        BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Boolean.ToString());
                                        if (optionSetMetadata.DisplayName.LocalizedLabels.Count != 0)
                                        {
                                            metadataWriter.WriteElementString("OptionSetDisplayName", optionSetMetadata.DisplayName.LocalizedLabels[0].Label);
                                        }
                                        else
                                        {
                                            metadataWriter.WriteElementString("OptionSetDisplayName", "UNDEFINED");
                                        }

                                        // Writes the TrueOption
                                        metadataWriter.WriteStartElement("TrueOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.TrueOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();
                                        // Writes the FalseOption
                                        metadataWriter.WriteStartElement("FalseOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.FalseOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }


                    #endregion How to dump option set info



                    Console.WriteLine("Done.");

                    //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;
            }
        }
Ejemplo n.º 21
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate

                    var retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    var retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)service.Execute(
                        retrieveAllOptionSetsRequest);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AllOptionSetValues.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                        {
                            foreach (OptionSetMetadataBase optionSetMetadataBase in
                                     retrieveAllOptionSetsResponse.OptionSetMetadata)
                            {
                                if (optionSetMetadataBase.OptionSetType != null)
                                {
                                    if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Picklist)
                                    {
                                        OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Picklist.ToString());
                                        metadataWriter.WriteElementString("OptionSetDisplayName",
                                                                          (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);

                                        // Writes the options
                                        metadataWriter.WriteStartElement("Options");

                                        foreach (OptionMetadata option in optionSetMetadata.Options)
                                        {
                                            metadataWriter.WriteStartElement("Option");
                                            metadataWriter.WriteElementString("OptionValue", option.Value.ToString());
                                            metadataWriter.WriteElementString("OptionDescription", option.Label.UserLocalizedLabel.Label.ToString());
                                            metadataWriter.WriteEndElement();
                                        }
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                    else if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Boolean)
                                    {
                                        BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Boolean.ToString());
                                        if (optionSetMetadata.DisplayName.LocalizedLabels.Count != 0)
                                        {
                                            metadataWriter.WriteElementString("OptionSetDisplayName", optionSetMetadata.DisplayName.LocalizedLabels[0].Label);
                                        }
                                        else
                                        {
                                            metadataWriter.WriteElementString("OptionSetDisplayName", "UNDEFINED");
                                        }

                                        // Writes the TrueOption
                                        metadataWriter.WriteStartElement("TrueOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.TrueOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();
                                        // Writes the FalseOption
                                        metadataWriter.WriteStartElement("FalseOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.FalseOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                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();
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// OptionSet Id;OptionSet Name;OptionSetValue;Type;LCID1;LCID2;...;LCIDX
        /// </example>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        /// <param name="service"></param>
        public void Export(List <int> languages, ExcelWorksheet sheet, IOrganizationService service)
        {
            var line = 1;

            AddHeader(sheet, languages);

            var request  = new RetrieveAllOptionSetsRequest();
            var response = (RetrieveAllOptionSetsResponse)service.Execute(request);

            foreach (var omd in response.OptionSetMetadata)
            {
                if (omd is OptionSetMetadata)
                {
                    var oomd = (OptionSetMetadata)omd;
                    foreach (var option in oomd.Options.OrderBy(o => o.Value))
                    {
                        var cell = 0;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            var optionLabel = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }

                        line++;
                        cell = 0;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = option.Value;
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                        foreach (var lcid in languages)
                        {
                            var label = string.Empty;

                            var optionDescription = option.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionDescription != null)
                            {
                                label = optionDescription.Label;
                            }

                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                        }

                        line++;
                    }
                }
                else if (omd is BooleanOptionSetMetadata)
                {
                    var bomd = (BooleanOptionSetMetadata)omd;

                    var cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.FalseOption.Label != null)
                        {
                            var optionLabel =
                                bomd.FalseOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.FalseOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.FalseOption.Description != null)
                        {
                            var optionLabel =
                                bomd.FalseOption.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Label";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.TrueOption.Label != null)
                        {
                            var optionLabel =
                                bomd.TrueOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                    cell = 0;

                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.MetadataId.Value.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = omd.Name;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = bomd.TrueOption.Value;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var label = string.Empty;

                        if (bomd.TrueOption.Description != null)
                        {
                            var optionLabel =
                                bomd.TrueOption.Description.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == lcid);
                            if (optionLabel != null)
                            {
                                label = optionLabel.Label;
                            }
                        }

                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = label;
                    }

                    line++;
                }
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Create a global option set.
        /// Set the options for that option set.
        /// Create a new reference to that option set on an entity.
        /// Update the option set's properties.
        /// Check the global option set for dependencies.
        /// Delete the option set.
        /// </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();

                    //<snippetWorkwithGlobalOptionSets1>
                    //<snippetWorkwithGlobalOptionSets2>
                    #region How to create global option set
                    // Define the request object and pass to the service.
                    CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
                    {
                        // Create a global option set (OptionSetMetadata).
                        OptionSet = new OptionSetMetadata
                        {
                            Name = _globalOptionSetName,
                            DisplayName = new Label("Example Option Set", _languageCode),
                            IsGlobal = true,
                            OptionSetType = OptionSetType.Picklist,
                            Options = 
                        {
                            new OptionMetadata(new Label("Open", _languageCode), null),
                            new OptionMetadata(new Label("Suspended", _languageCode), null),
                            new OptionMetadata(new Label("Cancelled", _languageCode), null),
                            new OptionMetadata(new Label("Closed", _languageCode), null)
                        }
                        }
                    };

                    // Execute the request.
                    CreateOptionSetResponse optionsResp =
                        (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest);

                    //</snippetWorkwithGlobalOptionSets2>
                    #endregion How to create global option set

                    // Store the option set's id as it will be needed to find all the
                    // dependent components.
                    _optionSetId = optionsResp.OptionSetId;
                    Console.WriteLine("The global option set has been created.");

                    #region How to create a picklist linked to the global option set
                    //<snippetWorkwithGlobalOptionSets3>
                    // Create a Picklist linked to the option set.
                    // Specify which entity will own the picklist, and create it.
                    CreateAttributeRequest createRequest = new CreateAttributeRequest
                    {
                        EntityName = Contact.EntityLogicalName,
                        Attribute = new PicklistAttributeMetadata
                        {
                            SchemaName = "sample_examplepicklist",
                            LogicalName = "sample_examplepicklist",
                            DisplayName = new Label("Example Picklist", _languageCode),
                            RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                            // In order to relate the picklist to the global option set, be sure
                            // to specify the two attributes below appropriately.
                            // Failing to do so will lead to errors.
                            OptionSet = new OptionSetMetadata
                            {
                                IsGlobal = true,
                                Name = _globalOptionSetName
                            }
                        }
                    };

                    _serviceProxy.Execute(createRequest);
                    //</snippetWorkwithGlobalOptionSets3>
                    Console.WriteLine("Referring picklist attribute created.");
                    #endregion How to create a picklist linked to the global option set

                    #region How to update a global option set
                    //<snippetWorkwithGlobalOptionSets4>
                    // Use UpdateOptionSetRequest to update the basic information of an option
                    // set. Updating option set values requires different messages (see below).
                    UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest
                    {
                        OptionSet = new OptionSetMetadata
                        {
                            DisplayName = new Label("Updated Option Set", _languageCode),
                            Name = _globalOptionSetName,
                            IsGlobal = true
                        }
                    };

                    _serviceProxy.Execute(updateOptionSetRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq1);
                    //</snippetWorkwithGlobalOptionSets4>
                    Console.WriteLine("Option Set display name changed.");
                    #endregion How to update a global option set properties

                    #region How to insert a new option item in a global option set
                    //<snippetWorkwithGlobalOptionSets5>
                    // Use InsertOptionValueRequest to insert a new option into a 
                    // global option set.
                    InsertOptionValueRequest insertOptionValueRequest =
                        new InsertOptionValueRequest
                        {
                            OptionSetName = _globalOptionSetName,
                            Label = new Label("New Picklist Label", _languageCode)
                        };

                    // Execute the request and store the newly inserted option value 
                    // for cleanup, used in the later part of this sample.
                    _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute(
                        insertOptionValueRequest)).NewOptionValue;

                    //Publish the OptionSet
                    PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq2);
                    //</snippetWorkwithGlobalOptionSets5>
                    Console.WriteLine("Created {0} with the value of {1}.",
                        insertOptionValueRequest.Label.LocalizedLabels[0].Label,
                        _insertedOptionValue);
                    #endregion How to insert a new option item in a global option set

                    #region How to retrieve a global option set by it's name
                    //<snippetWorkwithGlobalOptionSets6>
                    // Use the RetrieveOptionSetRequest message to retrieve  
                    // a global option set by it's name.
                    RetrieveOptionSetRequest retrieveOptionSetRequest =
                        new RetrieveOptionSetRequest
                        {
                            Name = _globalOptionSetName
                        };

                    // Execute the request.
                    RetrieveOptionSetResponse retrieveOptionSetResponse =
                        (RetrieveOptionSetResponse)_serviceProxy.Execute(
                        retrieveOptionSetRequest);

                    Console.WriteLine("Retrieved {0}.",
                        retrieveOptionSetRequest.Name);

                    // Access the retrieved OptionSetMetadata.
                    OptionSetMetadata retrievedOptionSetMetadata =
                        (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList =
                        retrievedOptionSetMetadata.Options.ToArray();
                    //</snippetWorkwithGlobalOptionSets6>
                    #endregion How to retrieve a global option set by it's name

                    #region How to update an option item in a picklist
                    //<snippetWorkwithGlobalOptionSets7>
                    // In order to change labels on option set values (or delete) option set
                    // values, you must use UpdateOptionValueRequest 
                    // (or DeleteOptionValueRequest).
                    UpdateOptionValueRequest updateOptionValueRequest =
                        new UpdateOptionValueRequest
                        {
                            OptionSetName = _globalOptionSetName,
                            // Update the second option value.
                            Value = optionList[1].Value.Value,
                            Label = new Label("Updated Option 1", _languageCode)
                        };

                    _serviceProxy.Execute(updateOptionValueRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq3);

                    

                    //</snippetWorkwithGlobalOptionSets7>
                    Console.WriteLine("Option Set option label changed.");
                    #endregion How to update an option item in a picklist

                    #region How to change the order of options of a global option set
                    //<snippetWorkwithGlobalOptionSets8>
                    // Change the order of the original option's list.
                    // Use the OrderBy (OrderByDescending) linq function to sort options in  
                    // ascending (descending) order according to label text.
                    // For ascending order use this:
                    var updateOptionList =
                        optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

                    // For descending order use this:
                    // var updateOptionList =
                    //      optionList.OrderByDescending(
                    //      x => x.Label.LocalizedLabels[0].Label).ToList();

                    // Create the request.
                    OrderOptionRequest orderOptionRequest = new OrderOptionRequest
                    {
                        // Set the properties for the request.
                        OptionSetName = _globalOptionSetName,
                        // Set the changed order using Select linq function 
                        // to get only values in an array from the changed option list.
                        Values = updateOptionList.Select(x => x.Value.Value).ToArray()
                    };

                    // Execute the request
                    _serviceProxy.Execute(orderOptionRequest);

                    //Publish the OptionSet
                    PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
                    _serviceProxy.Execute(pxReq4);
                    //</snippetWorkwithGlobalOptionSets8>
                    Console.WriteLine("Option Set option order changed");
                    #endregion How to change the order of options of a global option set

                    #region How to retrieve all global option sets
                    //<snippetWorkwithGlobalOptionSets9>
                    // Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
                    // Create the request.
                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                        new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                        retrieveAllOptionSetsRequest);

                    // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to 
                    // work with all retrieved option sets.
                    if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                    {
                        Console.WriteLine("All the global option sets retrieved as below:");
                        int count = 1;
                        foreach (OptionSetMetadataBase optionSetMetadata in
                            retrieveAllOptionSetsResponse.OptionSetMetadata)
                        {
                            Console.WriteLine("{0} {1}", count++,
                                (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
                        }
                    }
                    //</snippetWorkwithGlobalOptionSets9>
                    #endregion How to retrieve all global option sets


                    //</snippetWorkwithGlobalOptionSets1>

                    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;
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Load Global Option Set
        /// </summary>
        private static void LoadGlobalOptionSet()
        {
            RetrieveAllOptionSetsRequest request   = new RetrieveAllOptionSetsRequest {
            };
            RetrieveAllOptionSetsResponse response = (RetrieveAllOptionSetsResponse)organizationService.Execute(request);
            var optionSetData = response.OptionSetMetadata;

            string content = string.Empty;

            foreach (var optionSet in optionSetData)
            {
                if (optionSet.IsGlobal.HasValue &&
                    !optionSet.IsGlobal.Value)
                {
                    continue;
                }

                string optionSetCode = GlobalOptionSetCodeTemplate;

                string label       = GetOptionSetLabel(optionSet);
                string displayName = label;
                string description = label;
                if (string.IsNullOrEmpty(description))
                {
                    description = displayName;
                }

                optionSetCode = optionSetCode.Replace("[@OptionSet.DisplayName]", displayName);
                optionSetCode = optionSetCode.Replace("[@OptionSet.Description]", TransformToSymmary(description));
                optionSetCode = optionSetCode.Replace("[@OptionSet.SchemaName]", optionSet.Name);
                optionSetCode = optionSetCode.Replace("[@OptionSet.OptionSetType.Value]", optionSet.OptionSetType.Value.ToString());
                optionSetCode = optionSetCode.Replace("[@OptionSet.LogicalName]", optionSet.Name);

                string optionSetEnums = string.Empty;

                if (optionSet.OptionSetType != null)
                {
                    if ((OptionSetType)optionSet.OptionSetType == OptionSetType.Picklist)
                    {
                        OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSet;
                        int optionCount = 1;
                        foreach (OptionMetadata option in optionSetMetadata.Options)
                        {
                            var desc   = label;
                            var value  = option.Value.Value.ToString(CultureInfo.InvariantCulture);
                            var label2 = optionCount + "_" + ConvertNameAsVariable(desc);

                            string optionSetEnumCode = OptionSetEnumCodeTemplate;
                            optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Description]", TransformToSymmary(desc));
                            optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Label]", label2);
                            optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Value]", value);
                            optionSetEnums   += optionSetEnumCode;
                            optionCount++;
                        }
                    }
                    else if ((OptionSetType)optionSet.OptionSetType == OptionSetType.Boolean)
                    {
                        BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSet;

                        string optionSetEnumCode = OptionSetEnumCodeTemplate;
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Description]", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label);
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Label]", "TrueOption");
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Value]", optionSetMetadata.TrueOption.Value.ToString());
                        optionSetEnums   += optionSetEnumCode;

                        optionSetEnumCode = OptionSetEnumCodeTemplate;
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Description]", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label);
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Label]", "FalseOption");
                        optionSetEnumCode = optionSetEnumCode.Replace("[@Option.Value]", optionSetMetadata.FalseOption.Value.ToString());
                        optionSetEnums   += optionSetEnumCode;
                    }
                    optionSetCode = optionSetCode.Replace("[@OptionSet.Values]", optionSetEnums);
                }

                content += optionSetCode;
            }

            string classContent = GlobalOptionSetClassCodeTemplate;

            classContent = classContent.Replace("[@DefaultNamespace]", DefaultNamespace);
            classContent = classContent.Replace("[@OptionSetDefinition]", content);

            string fileName = Path.Combine(TargetPath, "GlobalOptionSet.generated.cs");

            File.WriteAllText(fileName, classContent);
        }
Ejemplo n.º 25
0
        private static void dumpAllOptionSet(OrganizationServiceProxy _serviceProxy)
        {
            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();

                    #region How to dump option set info

                    RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
                         new RetrieveAllOptionSetsRequest();

                    // Execute the request
                    RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
                        (RetrieveAllOptionSetsResponse)_serviceProxy.Execute(
                        retrieveAllOptionSetsRequest);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel. 
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("d:\\Temp\\AllOptionSetValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
                        {
                            foreach (OptionSetMetadataBase optionSetMetadataBase in
                                retrieveAllOptionSetsResponse.OptionSetMetadata)
                            {
                                if (optionSetMetadataBase.OptionSetType != null)
                                {
                                    if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Picklist)
                                    {
                                        OptionSetMetadata optionSetMetadata = (OptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Picklist.ToString());
                                        metadataWriter.WriteElementString("OptionSetDisplayName",
                                            (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);

                                        // Writes the options
                                        metadataWriter.WriteStartElement("Options");

                                        foreach (OptionMetadata option in optionSetMetadata.Options)
                                        {
                                            metadataWriter.WriteStartElement("Option");
                                            metadataWriter.WriteElementString("OptionValue", option.Value.ToString());
                                            metadataWriter.WriteElementString("OptionDescription", option.Label.UserLocalizedLabel.Label.ToString());
                                            metadataWriter.WriteEndElement();
                                        }
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                    else if ((OptionSetType)optionSetMetadataBase.OptionSetType == OptionSetType.Boolean)
                                    {
                                        BooleanOptionSetMetadata optionSetMetadata = (BooleanOptionSetMetadata)optionSetMetadataBase;
                                        // Start OptionSet Node
                                        metadataWriter.WriteStartElement("OptionSet");
                                        metadataWriter.WriteAttributeString("OptionSetType", OptionSetType.Boolean.ToString());
                                        if (optionSetMetadata.DisplayName.LocalizedLabels.Count != 0)
                                            metadataWriter.WriteElementString("OptionSetDisplayName", optionSetMetadata.DisplayName.LocalizedLabels[0].Label);
                                        else
                                            metadataWriter.WriteElementString("OptionSetDisplayName", "UNDEFINED");

                                        // Writes the TrueOption
                                        metadataWriter.WriteStartElement("TrueOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.TrueOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.TrueOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();
                                        // Writes the FalseOption
                                        metadataWriter.WriteStartElement("FalseOption");
                                        metadataWriter.WriteElementString("OptionValue", optionSetMetadata.FalseOption.Value.ToString());
                                        metadataWriter.WriteElementString("OptionDescription", optionSetMetadata.FalseOption.Label.UserLocalizedLabel.Label.ToString());
                                        metadataWriter.WriteEndElement();

                                        // End OptionSet Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }


                    #endregion How to dump option set info



                    Console.WriteLine("Done.");

                    //DeleteRequiredRecords(promptForDelete);
                //}
            }

                       // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (Exception ex)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }

        }