示例#1
2
        public IDictionary<int, string> GetGlobalOptionSetValues(string optionSetLogicalName)
        {
            IDictionary<int, string> optionSet = new Dictionary<int, string>();

            if (string.IsNullOrEmpty(optionSetLogicalName))
                return null;

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);
            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            for (int i = 0; i < retrievedPicklistAttributeMetadata.Options.Count(); i++)
            {
                optionSet.Add(new KeyValuePair<int, string>(retrievedPicklistAttributeMetadata.Options[i].Value.Value,
                    retrievedPicklistAttributeMetadata.Options[i].Label.LocalizedLabels[0].Label));
            }

            return optionSet;
        }
示例#2
0
        private static bool DoesGlobalOptionSetExist(string logicalName)
        {
            RetrieveOptionSetRequest request = new RetrieveOptionSetRequest
            {
                Name = logicalName
            };

            try
            {
                var respone = (RetrieveOptionSetResponse)_organizationService.Execute(request);
                if (respone?.OptionSetMetadata != null && respone.Results != null)
                {
                    return(true);
                }
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                ExConsole.WriteLineColor(
                    $"Could not find global option set {logicalName}: {ex.Message}",
                    ConsoleColor.DarkGray);
            }


            return(false);
        }
示例#3
0
        public string GetOptionsetText(string optionsetName, int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;

            RetrieveOptionSetRequest retrieveOptionSetRequest =
                new RetrieveOptionSetRequest
            {
                Name = optionsetName
            };

            // Execute the request.
            RetrieveOptionSetResponse retrieveOptionSetResponse = null;

            retrieveOptionSetResponse = (RetrieveOptionSetResponse)_service.Execute(retrieveOptionSetRequest);

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

            // Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
            foreach (OptionMetadata optionMetadata in optionList)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                    break;
                }
            }

            return(optionsetSelectedText);
        }
示例#4
0
        public string GetOptionsetText(Entity entity, IOrganizationService service, string optionsetName, int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;

            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                    Name = optionsetName
                };
                RetrieveOptionSetResponse retrieveOptionSetResponse  = (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);
                OptionSetMetadata         retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;
                OptionMetadata[]          optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(optionsetSelectedText);
        }
示例#5
0
        public int GetGlobalOptionSetValueByLabel(string optionSetLogicalName, string label)
        {
            if (string.IsNullOrEmpty(optionSetLogicalName))
            {
                return(0);
            }

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse          = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);
            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            int value = 0;

            for (int i = 0; i < retrievedPicklistAttributeMetadata.Options.Count(); i++)
            {
                if (retrievedPicklistAttributeMetadata.Options[i].Label.LocalizedLabels[0].Label == label)
                {
                    value = retrievedPicklistAttributeMetadata.Options[i].Value.Value;
                }
            }

            return(value);
        }
示例#6
0
        public IDictionary <int, string> GetGlobalOptionSetValues(string optionSetLogicalName)
        {
            IDictionary <int, string> optionSet = new Dictionary <int, string>();

            if (string.IsNullOrEmpty(optionSetLogicalName))
            {
                return(null);
            }

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse          = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);
            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            for (int i = 0; i < retrievedPicklistAttributeMetadata.Options.Count(); i++)
            {
                optionSet.Add(new KeyValuePair <int, string>(retrievedPicklistAttributeMetadata.Options[i].Value.Value,
                                                             retrievedPicklistAttributeMetadata.Options[i].Label.LocalizedLabels[0].Label));
            }

            return(optionSet);
        }
示例#7
0
        /// <summary>
        /// Global OptionSet이 존재하는지 여부 체크 (존재하면 true 리턴)
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        public bool IsExistGlobalOptionSet(string optionSetName)
        {
            bool retVal = true;

            RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetName
            };

            string retText = string.Empty;

            try
            {
                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_orgService.Execute(retrieveOptionSetRequest);
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Could not find optionset"))
                {
                    retVal = false;
                }
                else
                {
                    throw;
                }
            }

            return(retVal);
        }
 /// <summary>
 /// Processes the global option sets
 /// </summary>
 /// <param name="dictionary">The <see cref="String"/> array that contains the global option set values.</param>
 /// <param name="key">The option set name to be created or updated.</param>
 private void ProcessGlobalPicklists(string[] dictionary, string key)
 {
     if (dictionary.Length > 0)
     {
         try
         {
             RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                 Name = key
             };
             RetrieveOptionSetResponse retrieveOptionSetResponse  = (RetrieveOptionSetResponse)this.CrmAdapter.OrganizationService.Execute(retrieveOptionSetRequest);
             OptionSetMetadata         retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;
             OptionMetadata[]          optionList = retrievedOptionSetMetadata.Options.ToArray();
             foreach (string label in dictionary)
             {
                 var option = optionList.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label == label);
                 if (option == null)
                 {
                     InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest {
                         OptionSetName = key, Label = new Label(label, retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.LanguageCode)
                     };
                     this.CrmAdapter.OrganizationService.Execute(insertOptionValueRequest);
                 }
             }
         }
         catch (FaultException ex)
         {
             throw new AdapterException(ex.Message, ex)
                   {
                       ExceptionId = ErrorCodes.CrmPlatformException
                   };
         }
     }
 }
示例#9
0
        public string GetGlobalOptionSetLabelByValue(string optionSetLogicalName, int value)
        {
            if (string.IsNullOrEmpty(optionSetLogicalName))
            {
                return string.Empty;
            }

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);

            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            var option = retrievedPicklistAttributeMetadata.Options.FirstOrDefault(o => o.Value == value);

            if (option == null)
            {
                return string.Empty;
            }

            var label = option.Label.UserLocalizedLabel.Label;

            if (option.Value.HasValue)
            {
                _optionSetLabelCache[option.Value.Value] = label;
            }

            return label;
        }
示例#10
0
        /// <summary>
        /// 옵션집합 가져오기
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        public DtoOptionSet RetrieveGlobalOptionSet(string optionSetName)
        {
            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
                {
                    Name = optionSetName
                };

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

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

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

                DtoOptionSet retVal = new DtoOptionSet
                {
                    SchemaName  = optionSetName,
                    DisplayName = retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.Label,
                    Description = retrievedOptionSetMetadata.Description.UserLocalizedLabel.Label
                };

                return(retVal);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#11
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());
        }
示例#12
0
        /// <summary>
        /// 옵션집합의 Options 가져오기
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        private OptionMetadata[] RetrieveGlobalOptionSetOptions(string optionSetName)
        {
            try
            {
                // Use the RetrieveOptionSetRequest message to retrieve
                // a global option set by it's name.
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
                {
                    Name = optionSetName
                };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_orgService.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[] options = retrievedOptionSetMetadata.Options.ToArray();

                return(options);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public List <OptionsetField> GetGlobalOptionSet(string optionSetName)
        {
            List <OptionsetField> optionSets = new List <OptionsetField>();
            ServerConnection      cnx        = new ServerConnection();

            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest {
                    Name = optionSetName
                };

                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)cnx.Context.Execute(retrieveOptionSetRequest);

                OptionSetMetadata opcionesMedaData = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                opcionesMedaData.Options.ToList().ForEach
                    (l =>
                    optionSets.Add(new OptionsetField()
                {
                    Label = l.Label.UserLocalizedLabel.Label,
                    Value = Convert.ToInt32(l.Value)
                })
                    );
            }
            catch (Exception ex)
            {
                cnx = null;
                throw new CrmDataException(ex);
            }

            return(optionSets);
        }
示例#14
0
        public string GetGlobalOptionSetLabelByValue(string optionSetLogicalName, int value)
        {
            if (string.IsNullOrEmpty(optionSetLogicalName))
            {
                return(string.Empty);
            }

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);

            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            var option = retrievedPicklistAttributeMetadata.Options.FirstOrDefault(o => o.Value == value);

            if (option == null)
            {
                return(string.Empty);
            }

            var label = option.Label.UserLocalizedLabel.Label;

            if (option.Value.HasValue)
            {
                _optionSetLabelCache[option.Value.Value] = label;
            }

            return(label);
        }
示例#15
0
        // get a global option set value
        public static String getGlobalOptionSetName(String optionsetName, int optionsetValue, IOrganizationService service)
        {
            string ret = string.Empty;

            RetrieveOptionSetRequest req = new RetrieveOptionSetRequest {
                Name = optionsetName
            };

            // Execute the request.
            RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)service.Execute(req);

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

            // Get the current options list for the retrieved attribute.
            OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
            foreach (OptionMetadata optionMetadata in optionList)
            {
                if (optionMetadata.Value == optionsetValue)
                {
                    ret = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                    break;
                }
            }

            return(ret);
        }
示例#16
0
        public static List <OptionMetadata> GetOptionSet(IOrganizationService organisationService, string name)
        {
            var optionSet = new List <OptionMetadata>();

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

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


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

            foreach (var optionMetadata in retrievedOptionSetMetadata.Options)
            {
                optionSet.Add(optionMetadata);
            }

            // Get the current options list for the retrieved attribute.
            return(optionSet);
        }
示例#17
0
        /// <summary>
        /// Retrieve Global OptionSet Information.
        /// </summary>
        /// <param name="optionSetName"></param>
        /// <returns></returns>
        public OptionSetMetadata GetGlobalOptionSetMetadata(string optionSetName)
        {
            if (string.IsNullOrEmpty(optionSetName))
            {
                return(null);
            }

            ValidateMetadata();             // Check to see if Metadata has expired.

            if (_globalOptionMetadataCache.ContainsKey(optionSetName))
            {
                return(_globalOptionMetadataCache[optionSetName]);
            }

            // Create the RetrieveOption Set
            RetrieveOptionSetRequest optReq = new RetrieveOptionSetRequest {
                Name = optionSetName
            };

            // query CRM
            RetrieveOptionSetResponse response = (RetrieveOptionSetResponse)svcAct.CdsCommand_Execute(optReq, "GetGlobalOptionSetMetadata");

            if (response != null)
            {
                if (response.OptionSetMetadata is OptionSetMetadata && (OptionSetMetadata)response.OptionSetMetadata != null)
                {
                    lock (_lockObject)
                    {
                        _globalOptionMetadataCache.Add(optionSetName, (OptionSetMetadata)response.OptionSetMetadata);
                    }
                    return(_globalOptionMetadataCache[optionSetName]);
                }
            }
            return(null);
        }
        public void When_execute_is_called_And_The_request_does_not_have_a_name_throw_servicefault()
        {
            var context  = new XrmFakedContext();
            var executor = new RetrieveOptionSetRequestExecutor();
            var req      = new RetrieveOptionSetRequest();

            Assert.Throws <FaultException <OrganizationServiceFault> >(() => executor.Execute(req, context));
        }
示例#19
0
        public static Dictionary <String, String> FetchOptionSetList(IOrganizationService service, String entityName, String fieldName)
        {
            Dictionary <String, String> dcOptionDic = new Dictionary <String, String>();

            try
            {
                if (String.Equals(entityName, "GlobalOptionSet", StringComparison.OrdinalIgnoreCase))
                {
                    #region "--- Global OptionSet ---"
                    RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
                    {
                        Name = fieldName
                    };

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

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

                    // Get the current options list for the retrieved attribute.
                    OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();

                    for (int optionCount = 0; optionCount < optionList.Length; optionCount++)
                    {
                        dcOptionDic.Add(optionList[optionCount].Label.UserLocalizedLabel.Label, optionList[optionCount].Value.ToString());
                    }
                    return(dcOptionDic);

                    #endregion
                }
                else
                {
                    #region "--- Entity OptionSet ---"
                    RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
                    {
                        EntityLogicalName     = entityName,
                        LogicalName           = fieldName,
                        RetrieveAsIfPublished = true
                    };
                    // Execute the request
                    RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
                    OptionMetadata[]          optionList        = (((Microsoft.Xrm.Sdk.Metadata.EnumAttributeMetadata)(attributeResponse.AttributeMetadata)).OptionSet.Options).ToArray();
                    for (int optionCount = 0; optionCount < optionList.Length; optionCount++)
                    {
                        dcOptionDic.Add(optionList[optionCount].Label.UserLocalizedLabel.Label, optionList[optionCount].Value.ToString());
                    }
                    return(dcOptionDic);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void When_execute_is_called_And_The_OptionSetMetadata_Does_Not_Exist_In_The_Context_Throw_ServiceFault()
        {
            var context  = new XrmFakedContext();
            var executor = new RetrieveOptionSetRequestExecutor();
            var req      = new RetrieveOptionSetRequest {
                Name = "test"
            };

            Assert.Throws <FaultException <OrganizationServiceFault> >(() => executor.Execute(req, context));
        }
示例#21
0
        public static OptionSetMetadata GetGlobalOptionSetValues(this OrganizationServiceProxy connexion, string nomInterneListe)
        {
            var retrieveOptionSetRequest = new RetrieveOptionSetRequest();

            retrieveOptionSetRequest.Name = nomInterneListe;

            RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)connexion.Execute(retrieveOptionSetRequest);

            return((OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata);
        }
示例#22
0
        public static OptionSetMetadata GetMetadata(IOrganizationService orgSvc, string globalOptionSetName)
        {
            var retrieveOptionSetRequest = new RetrieveOptionSetRequest
            {
                Name = globalOptionSetName
            };

            var retrieveOptionSetResponse = (RetrieveOptionSetResponse)orgSvc.Execute(retrieveOptionSetRequest);

            return((OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata);
        }
示例#23
0
        /// <summary>
        /// Gets the option set metadata.
        /// </summary>
        /// <param name="metadataId">The metadata identifier.</param>
        /// <returns></returns>
        public OptionSetMetadata GetOptionSetMetadata(Guid metadataId)
        {
            var retrieveEntityRequest = new RetrieveOptionSetRequest()
            {
                MetadataId = metadataId
            };

            var response = (RetrieveOptionSetResponse)_service.Execute(retrieveEntityRequest);

            return((OptionSetMetadata)response.OptionSetMetadata);
        }
示例#24
0
        public static OptionSetMetadataBase GetOptionSetMetadata(IOrganizationService service, Guid objectId)
        {
            RetrieveOptionSetRequest attributeRequest = new RetrieveOptionSetRequest
            {
                MetadataId            = objectId,
                RetrieveAsIfPublished = true
            };
            RetrieveOptionSetResponse attributeResponse =
                (RetrieveOptionSetResponse)service.Execute(attributeRequest);

            return(attributeResponse.OptionSetMetadata);
        }
 //Retrieve the name of a global Option set
    public String getGlobalOptionSetName(Guid id)
    {
     String name = "";
      RetrieveOptionSetRequest req = new RetrieveOptionSetRequest
      {
       MetadataId = id
      };
      RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)_serviceProxy.Execute(req);
      OptionSetMetadataBase os = (OptionSetMetadataBase)resp.OptionSetMetadata;
      name = os.DisplayName.UserLocalizedLabel.Label;      
     return name;
    }
示例#26
0
        //Retrieve the name of a global Option set
        public static String getGlobalOptionSetName(CrmServiceClient service, Guid id)
        {
            String name = "";
            RetrieveOptionSetRequest req = new RetrieveOptionSetRequest
            {
                MetadataId = id
            };
            RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)service.Execute(req);
            OptionSetMetadataBase     os   = (OptionSetMetadataBase)resp.OptionSetMetadata;

            name = os.DisplayName.UserLocalizedLabel.Label;
            return(name);
        }
        /// <summary>
        /// Returns global option set as array
        /// </summary>
        /// <param name="optionSetName"> name of option set </param>
        /// <returns> Array of OptionMetadata </returns>
        public OptionMetadata[] GetGlobalOptionSet(string optionSetName)
        {
            RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetName
            };

            RetrieveOptionSetResponse retrieveOptionSetResponse  = (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);
            OptionSetMetadata         retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

            OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();

            return(optionList);
        }
示例#28
0
        private void AddOptionSet(IOrganizationService service, string ObjectName, string solutionName)
        {
            RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest()
            {
                Name = ObjectName
            };
            RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

            Guid componentid   = (Guid)retrieveOptionSetResponse.OptionSetMetadata.MetadataId;
            int  componentType = 9;

            AddComponent(service, solutionName, componentType, componentid);
            return;
        }
示例#29
0
        private RetrieveOptionSetResponse ExecuteInternal(RetrieveOptionSetRequest request)
        {
            var response  = new RetrieveOptionSetResponse();
            var optionSet = new OptionSetMetadata(new OptionMetadataCollection());

            response.Results["OptionSetMetadata"] = optionSet;

            var types    = CrmServiceUtility.GetEarlyBoundProxyAssembly(Info.EarlyBoundEntityAssembly).GetTypes();
            var enumType = types.FirstOrDefault(t => IsEnumType(t, request.Name)) ?? types.FirstOrDefault(t => IsEnumType(t, request.Name + "Enum"));

            AddEnumTypeValues(optionSet, enumType, "Unable to find global optionset enum " + request.Name);

            return(response);
        }
示例#30
0
        public OptionMetadata[] GetOptionSet(string optionSetName)
        {
            IOrganizationService orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);

            RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetName
            };
            RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)orgService.Execute(retrieveOptionSetRequest);
            OptionSetMetadata         optionSetMetadata         = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

            OptionMetadata[] optionList = optionSetMetadata.Options.ToArray();

            return(optionList);
        }
示例#31
0
        /// <summary>
        /// Gets the metadata for a global option set.
        /// </summary>
        /// <param name="globalOptionSetName">Logical name of the option set.</param>
        /// <returns>List of OptionMetadata for the option set.</returns>
        public List <OptionMetadata> RetrieveGlobalOptionSet(string globalOptionSetName)
        {
            var retrieveOptionSetRequest = new RetrieveOptionSetRequest
            {
                Name = globalOptionSetName
            };

            var retrieveOptionSetResponse = (RetrieveOptionSetResponse)
                                            _service.Execute(retrieveOptionSetRequest);

            var retrievedOptionSetMetadata = (OptionSetMetadata)
                                             retrieveOptionSetResponse.OptionSetMetadata;

            return(new List <OptionMetadata>(retrievedOptionSetMetadata.Options.ToArray()));
        }
示例#32
0
        public static OptionSetMetadata GetOptionSetMetadata(string attributeName, string entityLogicaName, IOrganizationService organizationService)
        {
            OptionSetMetadata optionSetMetadata = null;

            if (!string.IsNullOrEmpty(entityLogicaName))
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
                {
                    EntityLogicalName     = entityLogicaName,
                    LogicalName           = attributeName,
                    RetrieveAsIfPublished = true
                };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)organizationService.Execute(retrieveAttributeRequest);
                AttributeMetadata         attributeMetadata         = retrieveAttributeResponse.AttributeMetadata;

                if (attributeMetadata is StateAttributeMetadata)
                {
                    optionSetMetadata = (attributeMetadata as StateAttributeMetadata).OptionSet;
                }
                else if (attributeMetadata is StatusAttributeMetadata)
                {
                    optionSetMetadata = (attributeMetadata as StatusAttributeMetadata).OptionSet;
                }
                else if (attributeMetadata is PicklistAttributeMetadata)
                {
                    optionSetMetadata = (attributeMetadata as PicklistAttributeMetadata).OptionSet;
                }
                else if (attributeMetadata is EntityNameAttributeMetadata)
                {
                    optionSetMetadata = (attributeMetadata as EntityNameAttributeMetadata).OptionSet;
                }
            }
            else
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest()
                {
                    Name = attributeName
                };
                RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)organizationService.Execute(retrieveOptionSetRequest);
                if (retrieveOptionSetResponse != null)
                {
                    optionSetMetadata = retrieveOptionSetResponse.OptionSetMetadata as OptionSetMetadata;
                }
            }

            return(optionSetMetadata);
        }
        private RetrieveOptionSetResponse ExecuteInternal(RetrieveOptionSetRequest request)
        {
            var response = new RetrieveOptionSetResponse();
            var optionSet = new OptionSetMetadata(new OptionMetadataCollection());

            response.Results["OptionSetMetadata"] = optionSet;

            var types = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes();
            var enumType = types.FirstOrDefault(t => IsEnumType(t, request.Name)) ??
                           types.FirstOrDefault(t => IsEnumType(t, request.Name + "Enum"));

            AddEnumTypeValues(optionSet, enumType, "Unable to find global optionset enum " + request.Name);

            return response;
        }
示例#34
0
 //Retrieve the name of a global Option set
    public String getGlobalOptionSetName(Guid id)
    {
     String name = "";
      RetrieveOptionSetRequest req = new RetrieveOptionSetRequest
      {
       MetadataId = id
      };
      RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)_serviceProxy.Execute(req);
      OptionSetMetadataBase os = (OptionSetMetadataBase)resp.OptionSetMetadata;
      name = os.DisplayName.UserLocalizedLabel.Label;      
     return name;
    }
示例#35
0
        private void RefreshSharedOptionValues(string schemaName)
        {
            lock (LockObject)
            {
                if (SharedOptionSets.Any(m => m.Name == schemaName))
                    SharedOptionSets.Remove(SharedOptionSets.Single(m => m.Name == schemaName));

                var request = new RetrieveOptionSetRequest
                {
                    Name = schemaName
                };
                var response = (RetrieveOptionSetResponse) Execute(request);
                SharedOptionSets.Add((OptionSetMetadata) response.OptionSetMetadata);
            }
        }
        private void SaveGlobalOptionSet()
        {
            WorkAsync("Saving global optionset...",
                (w, e) =>
                {
                    var req = new RetrieveOptionSetRequest()
                    {
                        Name = ((Item)cboOptionSets.SelectedItem).Value,
                    };
                    var resp = (RetrieveOptionSetResponse)Service.Execute(req);
                    OptionSetMetadata md = (OptionSetMetadata)resp.OptionSetMetadata;

                    //foreach (var option in md.Options)
                    //{
                    //    var delReq = new DeleteOptionValueRequest()
                    //    {
                    //        OptionSetName = md.Name,
                    //        Value = option.Value.Value
                    //    };
                    //    Service.Execute(delReq);
                    //}

                    var data = (BindingList<Item>)dgvOptions.DataSource;

                    var execMultiReq = new ExecuteMultipleRequest()
                    {
                        Settings = new Microsoft.Xrm.Sdk.ExecuteMultipleSettings()
                        {
                            ContinueOnError = true,
                            ReturnResponses = false
                        },
                        Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection()
                    };

                    foreach (var item in data)
                    {
                        var exists = (from o in md.Options where o.Value.Value == int.Parse(item.Value) select true).FirstOrDefault();
                        if (exists)
                        {
                            var upReq = new UpdateOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033),
                                Value = int.Parse(item.Value)
                            };
                            execMultiReq.Requests.Add(upReq);
                        }
                        else
                        {
                            var addReq = new InsertOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033),
                                Value = int.Parse(item.Value)
                            };
                            execMultiReq.Requests.Add(addReq);
                        }
                    }

                    foreach (var item in md.Options)
                    {
                        var exists = (from d in data where int.Parse(d.Value) == item.Value.Value select true).FirstOrDefault();
                        if (!exists)
                        {
                            var delReq = new DeleteOptionValueRequest()
                            {
                                OptionSetName = md.Name,
                                Value = item.Value.Value
                            };
                            execMultiReq.Requests.Add(delReq);
                        }
                    }

                    Service.Execute(execMultiReq);

                    w.ReportProgress(50, "Publishing global optionset...");

                    PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", md.Name) };
                    Service.Execute(pxReq1);
                },
                e =>
                {
                },
                e =>
                {
                    SetWorkingMessage(e.UserState.ToString());
                }
            );
        }
        private void LoadSelectedOptionSetOptions()
        {
            WorkAsync("Retrieving global optionsets...",
                (e) =>
                {
                    var req = new RetrieveOptionSetRequest()
                        {
                            Name = ((Item)cboOptionSets.SelectedItem).Value,
                        };
                    var resp = (RetrieveOptionSetResponse)Service.Execute(req);
                    OptionSetMetadata md = (OptionSetMetadata)resp.OptionSetMetadata;
                    if (md.Options != null
                        && md.Options.Count > 0)
                    {
                        var items = new List<Item>();
                        foreach (var item in md.Options)
                        {
                            items.Add(new Item(
                                    item.Label.LocalizedLabels.FirstOrDefault().Label,
                                    item.Value.ToString()
                                ));
                        }

                        dgvOptions.Rows.Clear();
                        dgvOptions.AutoGenerateColumns = false;

                        dgvOptions.Columns[0].DataPropertyName = "Name";
                        dgvOptions.Columns[1].DataPropertyName = "Value";

                        dgvOptions.DataSource = new BindingList<Item>(items);
                    }
                },
                e =>
                {
                }
            );
        }
示例#38
0
        public int GetGlobalOptionSetValueByLabel(string optionSetLogicalName, string label)
        {
            if (string.IsNullOrEmpty(optionSetLogicalName))
            {
                return 0;
            }

            var retrieveAttributeRequest = new RetrieveOptionSetRequest
            {
                Name = optionSetLogicalName
            };

            var retrieveAttributeResponse = (RetrieveOptionSetResponse)XrmContext.Execute(retrieveAttributeRequest);
            var retrievedPicklistAttributeMetadata = (OptionSetMetadata)retrieveAttributeResponse.OptionSetMetadata;

            int value = 0;
            for (int i = 0; i < retrievedPicklistAttributeMetadata.Options.Count(); i++)
            {
                if (retrievedPicklistAttributeMetadata.Options[i].Label.LocalizedLabels[0].Label == label)
                    value = retrievedPicklistAttributeMetadata.Options[i].Value.Value;
            }

            return value;
        }
        /// <summary>
        /// Read an <c>object</c> from the stream
        /// </summary>
        /// <param name="key">The key for the <c>object</c> to be read</param>
        /// <returns>An instance of the <c>object</c> provided by this <c>ObjectProvider</c> that has the key provided</returns>
        public object ReadObject(object key)
        {
            if (key == null || key.GetType() != typeof(Guid))
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.SuppliedKeyTypeExceptionMessage), new ArgumentException(Resources.SuppliedKeyTypeExceptionMessage, "key")) { ExceptionId = ErrorCodes.SuppliedKeyCastException };
            }

            Guid metaKey = (Guid)key;

            // Will throw exception if the GUID is not related to a Entity but rather to a global option set.
            try
            {
                RetrieveEntityRequest entityRequest = new RetrieveEntityRequest() { EntityFilters = EntityFilters.Attributes, MetadataId = metaKey, RetrieveAsIfPublished = true };
                RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)this.CallMetadataExecuteWebMethod(entityRequest);
                var anyPicklist = entityResponse.EntityMetadata.Attributes.Where(x => x.AttributeType == AttributeTypeCode.Picklist);

                if (anyPicklist.Count() > 0)
                {
                    Dictionary<string, object> parentDictionary = new Dictionary<string, object>();
                    Dictionary<string, object> childDictionary = new Dictionary<string, object>();

                    foreach (var attributeMeta in anyPicklist)
                    {
                        var picklistMeta = attributeMeta as PicklistAttributeMetadata;
                        if (picklistMeta.OptionSet.IsGlobal.Value != true)
                        {
                            var options = new List<string>();
                            foreach (var option in picklistMeta.OptionSet.Options)
                            {
                                if (option.Label.LocalizedLabels.Count > 0)
                                {
                                    options.Add(option.Label.LocalizedLabels[0].Label);
                                }
                            }

                            childDictionary.Add(attributeMeta.LogicalName, options.ToArray<string>());
                        }
                    }

                    parentDictionary.Add(entityResponse.EntityMetadata.DisplayName.LocalizedLabels[0].Label.Replace(" ", string.Empty), childDictionary);

                    return parentDictionary;
                }
                else
                {
                    return null;
                }
            }
            catch (AdapterException)
            {
                var optionSetMetaRequest = new RetrieveOptionSetRequest() { MetadataId = metaKey };
                var optionSetMetaResponse = (RetrieveOptionSetResponse)this.CallMetadataExecuteWebMethod(optionSetMetaRequest);
                var optionSetMeta = (OptionSetMetadata)optionSetMetaResponse.OptionSetMetadata;
                var metaOptions = optionSetMeta.Options;

                var options = new List<string>();

                foreach (var option in metaOptions)
                {
                    options.Add(option.Label.LocalizedLabels[0].Label);
                }

                Dictionary<string, object> optionSet = new Dictionary<string, object>();
                optionSet.Add(optionSetMeta.Name, options.ToArray<string>());
                return optionSet;
            }
        }
 /// <summary>
 /// Processes the global option sets
 /// </summary>
 /// <param name="dictionary">The <see cref="String"/> array that contains the global option set values.</param>
 /// <param name="key">The option set name to be created or updated.</param>
 private void ProcessGlobalPicklists(string[] dictionary, string key)
 {
     if (dictionary.Length > 0)
     {
         try
         {
             RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = key };
             RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)this.CrmAdapter.OrganizationService.Execute(retrieveOptionSetRequest);
             OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;
             OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
             foreach (string label in dictionary)
             {
                 var option = optionList.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label == label);
                 if (option == null)
                 {
                     InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = key, Label = new Label(label, retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.LanguageCode) };
                     this.CrmAdapter.OrganizationService.Execute(insertOptionValueRequest);
                 }
             }
         }
         catch (FaultException ex)
         {
             throw new AdapterException(ex.Message, ex) { ExceptionId = ErrorCodes.CrmPlatformException };
         }
     }
 }
示例#41
0
        //<snippetGetSolutionDependencies7>
        /// <summary>
        /// Shows how to get a more friendly message based on information within the dependency
        /// <param name="dependency">A Dependency returned from the RetrieveDependentComponents message</param>
        /// </summary> 
     public void DependencyReport(Dependency dependency)
        {
      //These strings represent parameters for the message.
         String dependentComponentName = "";
         String dependentComponentTypeName = "";
         String dependentComponentSolutionName = "";
         String requiredComponentName = "";
         String requiredComponentTypeName = "";
         String requiredComponentSolutionName = "";

      //The ComponentType global Option Set contains options for each possible component.
         RetrieveOptionSetRequest componentTypeRequest = new RetrieveOptionSetRequest
         {
          Name = "componenttype"
         };

         RetrieveOptionSetResponse componentTypeResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute(componentTypeRequest);
         OptionSetMetadata componentTypeOptionSet = (OptionSetMetadata)componentTypeResponse.OptionSetMetadata;
      // Match the Component type with the option value and get the label value of the option.
         foreach (OptionMetadata opt in componentTypeOptionSet.Options)
         {
          if (dependency.DependentComponentType.Value == opt.Value)
          {
           dependentComponentTypeName = opt.Label.UserLocalizedLabel.Label;
          }
          if (dependency.RequiredComponentType.Value == opt.Value)
          {
           requiredComponentTypeName = opt.Label.UserLocalizedLabel.Label;
          }
         }
      //The name or display name of the compoent is retrieved in different ways depending on the component type
         dependentComponentName = getComponentName(dependency.DependentComponentType.Value, (Guid)dependency.DependentComponentObjectId);
         requiredComponentName = getComponentName(dependency.RequiredComponentType.Value, (Guid)dependency.RequiredComponentObjectId);

      // Retrieve the friendly name for the dependent solution.
         Solution dependentSolution = (Solution)_serviceProxy.Retrieve
          (
           Solution.EntityLogicalName,
           (Guid)dependency.DependentComponentBaseSolutionId,
           new ColumnSet("friendlyname")
          );
         dependentComponentSolutionName = dependentSolution.FriendlyName;
         
      // Retrieve the friendly name for the required solution.
         Solution requiredSolution = (Solution)_serviceProxy.Retrieve
           (
            Solution.EntityLogicalName,
            (Guid)dependency.RequiredComponentBaseSolutionId,
            new ColumnSet("friendlyname")
           );
         requiredComponentSolutionName = requiredSolution.FriendlyName;

      //Display the message
          Console.WriteLine("The {0} {1} in the {2} depends on the {3} {4} in the {5} solution.",
          dependentComponentName,
          dependentComponentTypeName,
          dependentComponentSolutionName,
          requiredComponentName,
          requiredComponentTypeName,
          requiredComponentSolutionName);
        }
示例#42
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;
            }
        }
示例#43
0
文件: Program.cs 项目: Phil-Ruben/CRM
        private static void getOptionSet(XrmServiceContext xrm)
        {
            #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
        }
示例#44
0
        /// <summary>
        /// Shows how to detect dependencies that may cause a managed solution to become
        /// un-deletable.
        /// 
        /// Get all solution components of a solution
        /// For each solution component, list the dependencies upon that component.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();
                    //<snippetGetSolutionDependencies1>

                    // Grab all Solution Components for a solution.
                    QueryByAttribute componentQuery = new QueryByAttribute
                    {
                        EntityName = SolutionComponent.EntityLogicalName,
                        ColumnSet = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"),
                        Attributes = { "solutionid" },

                        // In your code, this value would probably come from another query.
                        Values = { _primarySolutionId }
                    };

                    IEnumerable<SolutionComponent> allComponents =
                        _serviceProxy.RetrieveMultiple(componentQuery).Entities.Cast<SolutionComponent>();

                    foreach (SolutionComponent component in allComponents)
                    {
                        // For each solution component, retrieve all dependencies for the component.
                        RetrieveDependentComponentsRequest dependentComponentsRequest =
                            new RetrieveDependentComponentsRequest
                            {
                                ComponentType = component.ComponentType.Value,
                                ObjectId = component.ObjectId.Value
                            };
                        RetrieveDependentComponentsResponse dependentComponentsResponse =
                            (RetrieveDependentComponentsResponse)_serviceProxy.Execute(dependentComponentsRequest);

                        // If there are no dependent components, we can ignore this component.
                        if (dependentComponentsResponse.EntityCollection.Entities.Any() == false)
                            continue;

                        // If there are dependencies upon this solution component, and the solution
                        // itself is managed, then you will be unable to delete the solution.
                        Console.WriteLine("Found {0} dependencies for Component {1} of type {2}",
                            dependentComponentsResponse.EntityCollection.Entities.Count,
                            component.ObjectId.Value,
                            component.ComponentType.Value
                            );
                        //A more complete report requires more code
                        foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities)
                        {
                            DependencyReport(d);
                        }
                    }
                    //</snippetGetSolutionDependencies1>

                 //Find out if any dependencies on a  specific global option set would prevent it from being deleted
                    //<snippetGetSolutionDependencies8>
                    // 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);
                    _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId;
                    if (_globalOptionSetId != null)
                    { 
                     //Use the global OptionSet MetadataId with the appropriate componenttype
                     // to call RetrieveDependenciesForDeleteRequest
                     RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest 
                    { 
                     ComponentType = (int)componenttype.OptionSet,
                     ObjectId = (Guid)_globalOptionSetId
                    };

                     RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse =
                      (RetrieveDependenciesForDeleteResponse)_serviceProxy.Execute(retrieveDependenciesForDeleteRequest);
                     Console.WriteLine("");
                     foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities)
                     {

                      if (d.DependentComponentType.Value == 2)//Just testing for Attributes
                      {
                       String attributeLabel = "";
                       RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
                       {
                        MetadataId = (Guid)d.DependentComponentObjectId
                       };
                       RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeRequest);

                       AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata;

                       attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label;
                      
                        Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.", 
                       (componenttype)d.DependentComponentType.Value, 
                       attributeLabel, 
                       _globalOptionSetName);
                      }
                     }                 
                    }

                    //</snippetGetSolutionDependencies8>

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