/// <summary> /// Create and configure the organization service proxy. /// Create few types of attributes. /// Insert status in the existing status list. /// Retrieve attribute. /// Update attribute. /// Update existing state value. /// Optionally delete/revert any attributes /// that were created/changed for this sample. /// </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(); //<snippetWorkWithAttributes1> #region How to create attributes //<snippetWorkWithAttributes2> // Create storage for new attributes being created addedAttributes = new List<AttributeMetadata>(); // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute StringAttributeMetadata stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. _serviceProxy.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } //</snippetWorkWithAttributes2> #endregion How to create attributes #region How to insert status //<snippetWorkWithAttributes3> // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. InsertStatusValueRequest insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); //</snippetWorkWithAttributes3> #endregion How to insert status #region How to retrieve attribute //<snippetWorkWithAttributes4> // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); //</snippetWorkWithAttributes4> #endregion How to retrieve attribute #region How to update attribute //<snippetWorkWithAttributes5> // Modify the retrieved attribute AttributeMetadata retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest UpdateAttributeRequest updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); //</snippetWorkWithAttributes5> #endregion How to update attribute #region How to update state value //<snippetWorkWithAttributes6> // Modify the state value label from Active to Open. // Create the request. UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. _serviceProxy.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); //</snippetWorkWithAttributes6> #endregion How to update state value #region How to insert a new option item in a local option set //<snippetWorkWithAttributes7> // Create a request. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); //</snippetWorkWithAttributes7> #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set //<snippetWorkWithAttributes8> // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute( retrieveAttributeRequest); // Access the retrieved attribute. PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // 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. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // 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); Console.WriteLine("Option Set option order changed"); //</snippetWorkWithAttributes8> #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. _serviceProxy.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); //</snippetWorkWithAttributes1> 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; } }
public long getAttributeMax(string entityName, string attributeName) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse; // Execute the request try { attributeResponse = (RetrieveAttributeResponse)_service.Execute(attributeRequest); } catch (FaultException ex) { throw new attributeMaxException(ex.Message); } var retrievedAttribute = attributeResponse.AttributeMetadata; //get the type of data string[] datatype = retrievedAttribute.GetType().ToString().Split('.'); switch (datatype[datatype.Length-1]) { case "StringAttributeMetadata": StringAttributeMetadata SAM = (StringAttributeMetadata)retrievedAttribute; return (long)SAM.MaxLength; case "MemoAttributeMetadata": MemoAttributeMetadata MeAM = (MemoAttributeMetadata)retrievedAttribute; return (long)MeAM.MaxLength; case "IntegerAttributeMetadata": IntegerAttributeMetadata IAM = (IntegerAttributeMetadata)retrievedAttribute; return (long)IAM.MaxValue; case "MoneyAttributeMetadata": MoneyAttributeMetadata MAM = (MoneyAttributeMetadata)retrievedAttribute; return (long)MAM.MaxValue; case "DecimalAttributeMetadata": DecimalAttributeMetadata DAM = (DecimalAttributeMetadata)retrievedAttribute; return (long)DAM.MaxValue; default: return 0; } }
public int getIndexOfLabel(string entityName, string field, string labelText, IOrganizationService context) { int index = -1; RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = field, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest); EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; foreach (OptionMetadata om in attributeMetadata.OptionSet.Options) { if (om.Label.UserLocalizedLabel.Label.ToString() == labelText) { if (om.Value != null) { index = om.Value.Value; } } } return(index); }
public int?getMaxLength(string stringFieldName) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = _entity.LogicalName, LogicalName = stringFieldName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_service.Execute(attributeRequest); if (attributeResponse != null) { if (attributeResponse.AttributeMetadata is StringAttributeMetadata) { StringAttributeMetadata attributeMetadata = (StringAttributeMetadata)attributeResponse.AttributeMetadata; if (attributeMetadata.MaxLength != null) { return(attributeMetadata.MaxLength); } } } return(null); }
public OptionMetadata[] GetOptionSetItems(string entityName, string optionSetAttributeName) { try { OptionMetadata[] optionList = null; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = optionSetAttributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_service.Execute(retrieveAttributeRequest); if (retrieveAttributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Picklist) { PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); } return(optionList); } catch (Exception ex) { throw ex; } }
private void ExtractAttributes(XmlNode node) { string entity = node.GetAttributeValue("name"); string alias = node.GetAttributeValue("alias"); foreach (XmlNode attribute in node.SelectNodes("./attribute/@name")) { string attributeName = attribute.Value; string qualifiedAttribute = (string.IsNullOrEmpty(alias)) ? attributeName : string.Format("{0}.{1}", alias, attributeName); var attReq = new RetrieveAttributeRequest(); attReq.EntityLogicalName = entity; attReq.LogicalName = attributeName; attReq.RetrieveAsIfPublished = true; var attResponse = (RetrieveAttributeResponse)Service.Execute(attReq); Attributes.Add(qualifiedAttribute, attResponse.AttributeMetadata); if (attResponse.AttributeMetadata is EnumAttributeMetadata) { var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata; var labels = new Dictionary <int, string>(); foreach (var option in attMetadata.OptionSet.Options) { labels.Add(option.Value.GetValueOrDefault(), option.Label.UserLocalizedLabel.Label); } OptionSetLabels.Add(qualifiedAttribute, labels); } } }
public string getLabelFromField(Entity entity, string field, IOrganizationService context) { var fieldValue = ((OptionSetValue)entity.Attributes[field]).Value.ToString(); string fieldLabel = ""; //need to get Option Set display label based on its value. This requires getting attribute metadata RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entity.LogicalName, LogicalName = field, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest); EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; foreach (OptionMetadata om in attributeMetadata.OptionSet.Options) { if (om.Value == ((OptionSetValue)entity.Attributes[field]).Value) { fieldLabel = om.Label.UserLocalizedLabel.Label.ToString(); } } return(fieldLabel); }
public static void When_retrieve_attribute_request_is_called_correctly_attribute_is_returned() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); var entityMetadata = new EntityMetadata() { LogicalName = "account" }; var nameAttribute = new StringAttributeMetadata() { LogicalName = "name", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired) }; entityMetadata.SetAttributeCollection(new[] { nameAttribute }); ctx.InitializeMetadata(entityMetadata); RetrieveAttributeRequest req = new RetrieveAttributeRequest() { EntityLogicalName = "account", LogicalName = "name" }; var response = service.Execute(req) as RetrieveAttributeResponse; Assert.NotNull(response.AttributeMetadata); Assert.Equal(AttributeRequiredLevel.ApplicationRequired, response.AttributeMetadata.RequiredLevel.Value); Assert.Equal("name", response.AttributeMetadata.LogicalName); }
private string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue, int LanCode) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); string selectedOptionLabel = string.Empty; foreach (OptionMetadata oMD in optionList) { if (oMD.Value == selectedValue) { foreach (var item in oMD.Label.LocalizedLabels) { if (item.LanguageCode == LanCode) { selectedOptionLabel = item.Label; } } } } return selectedOptionLabel; }
public static String GetOptionSetValueLabel( this IOrganizationService service, String entityLogicalName, String attributeName, Int32 optionSetValue) { ValidationHelper.EnsureNotNull(service); ValidationHelper.EnsureNotNull(entityLogicalName); ValidationHelper.EnsureNotNull(attributeName); var request = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = attributeName }; var response = service.Execute <RetrieveAttributeResponse>(request); var metadata = (EnumAttributeMetadata)response.AttributeMetadata; return(metadata .OptionSet.Options .Where(x => x.Value == optionSetValue) .FirstOrDefault()? .Label.UserLocalizedLabel.Label); }
public static Dictionary <string, int> GetOptionsSet(IOrganizationService service, string entitySchemaName, string attributeSchemaName) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entitySchemaName, LogicalName = attributeSchemaName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); Dictionary <string, int> metadata = new Dictionary <string, int>(); if (optionList.Length > 0) { foreach (var p in optionList) { if (!metadata.ContainsKey(p.Label.UserLocalizedLabel.Label)) { metadata.Add(p.Label.UserLocalizedLabel.Label, p.Value.Value); } } } return(metadata); }
/// <summary> /// /// </summary> /// <param name="entityName"></param> /// <param name="attributeName"></param> /// <returns></returns> public AttributeMetadata GetAttributeMetadata(string entityName, string attributeName) { string entityAndAttribute = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", entityName, attributeName); AttributeMetadata attributeMetadata = null; ValidateMetadata(); if (!_attributeMetadataCache.TryGetValue(entityAndAttribute, out attributeMetadata)) { if (!_attributeMetadataCache.TryGetValue(entityAndAttribute, out attributeMetadata)) { RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entityName; request.LogicalName = attributeName; RetrieveAttributeResponse response = (RetrieveAttributeResponse)svcAct.CdsCommand_Execute(request, "GetAttributeMetadata"); if (response != null) { attributeMetadata = response.AttributeMetadata; _attributeMetadataCache.TryAdd(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", entityName, attributeName), attributeMetadata); _metadataLastValidatedAt = DateTime.UtcNow; } } } return(attributeMetadata); }
private string RetrieveBooleanLabel(bool optionsetValue, string attributeName, string entityName) { var optionsetText = string.Empty; var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; var retrieveAttributeResponse = (RetrieveAttributeResponse)Service.Execute(retrieveAttributeRequest); var optionSets = retrieveAttributeResponse.AttributeMetadata; OptionMetadata optionMetaData = null; if (optionSets is BooleanAttributeMetadata) { optionMetaData = optionsetValue ? ((BooleanAttributeMetadata)optionSets).OptionSet.TrueOption : ((BooleanAttributeMetadata)optionSets).OptionSet.FalseOption; } if (optionMetaData != null) { optionsetText = optionMetaData.Label.UserLocalizedLabel.Label; } return(optionsetText); }
public String GetStatuslistStr(IOrganizationService _Service, String EntityLogicalName, String LogicalName) { String rV = ""; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = EntityLogicalName, LogicalName = LogicalName, RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_Service.Execute(retrieveAttributeRequest); Microsoft.Xrm.Sdk.Metadata.StatusAttributeMetadata retrievedStatusAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedStatusAttributeMetadata.OptionSet.Options.ToArray(); foreach (OptionMetadata oMD in optionList) { if (rV != "") { rV += ";"; } rV += oMD.Label.UserLocalizedLabel.Label; rV += "|"; rV += oMD.Value.ToString(); } return(rV); }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var optionSet = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata() }; response.Results["AttributeMetadata"] = optionSet; var enumExpression = CrmServiceUtility.GetEarlyBoundProxyAssembly(). GetTypes(). Where( t => t.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0 && t.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), false).Length > 0 && t.Name.Contains(request.LogicalName)). ToList(); // Search By EntityLogicalName_LogicalName // Then By LogicName_EntityLogicalName // Then By LogicaName var enumType = enumExpression.FirstOrDefault(t => t.Name == request.EntityLogicalName + "_" + request.LogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName + "_" + request.EntityLogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName); AddEnumTypeValues(optionSet.OptionSet, enumType, $"Unable to find local optionset enum for entity: {request.EntityLogicalName}, attribute: {request.LogicalName}"); return(response); }
// get a local option set value public static String getOptionName(Entity entity, string attributeName, IOrganizationService service) { int optionsetValue = getIntValue(entity, attributeName); string optionsetText = string.Empty; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest(); retrieveAttributeRequest.EntityLogicalName = entity.LogicalName; retrieveAttributeRequest.LogicalName = attributeName; retrieveAttributeRequest.RetrieveAsIfPublished = true; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet; foreach (OptionMetadata optionMetadata in optionsetMetadata.Options) { if (optionMetadata.Value == optionsetValue) { optionsetText = optionMetadata.Label.UserLocalizedLabel.Label; return(optionsetText); } } return(optionsetText); }
private PicklistAttributeMetadata CreateOptionSetAttributeMetadata(RetrieveAttributeRequest request, Type propertyType) { if (propertyType == typeof(OptionSetValue)) { var enumExpression = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().Where( t => t.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0 && t.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), false).Length > 0 && t.Name.Contains(request.LogicalName)).ToList(); // Search By EntityLogicalName_LogicalName // Then By LogicName_EntityLogicalName // Then By LogicalName propertyType = enumExpression.FirstOrDefault(t => t.Name == request.EntityLogicalName + "_" + request.LogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName + "_" + request.EntityLogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName); } var optionSet = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata() }; AddEnumTypeValues(optionSet.OptionSet, propertyType, $"Unable to find local OptionSet enum for entity: {request.EntityLogicalName}, attribute: {request.LogicalName}"); return(optionSet); }
/// <summary> /// Gets the options set text on value. /// </summary> /// <param name="service">The service.</param> /// <param name="entityName">Name of the entity.</param> /// <param name="attributeName">Name of the attribute.</param> /// <param name="selectedValue">The selected value.</param> /// <returns>Option set Value.</returns> private static string GetOptionsSetTextOnValue(IOrganizationService service, ITracingService tracingService, string entityName, string attributeName, int selectedValue) { try { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; //// Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); string selectedOptionLabel = string.Empty; foreach (OptionMetadata oMD in optionList) { if (oMD.Value == selectedValue) { selectedOptionLabel = oMD.Label.UserLocalizedLabel.Label; } } return(selectedOptionLabel); } catch (Exception ex) { tracingService.Trace("Error while getting time zone offset text." + " ----Error Message----" + ex.Message + " -----Stack Trace---- " + ex.StackTrace); CustomServiceManagementPortalException customEx = new CustomServiceManagementPortalException("Error while getting time zone offset text.", ex); throw customEx; } }
// credit: https://community.dynamics.com/crm/b/mshelp/archive/2012/06/12/get-optionset-text-from-value-or-value-from-text /// <summary> /// This function is used to retrieve the optionset label using the optionset value /// </summary> /// <param name="service"></param> /// <param name="entityName"></param> /// <param name="attributeName"></param> /// <param name="selectedValue"></param> /// <returns></returns> internal static string GetOptionsSetTextForValue(IOrganizationService service, string entityName, string attributeName, int selectedValue, string orgId) { var cacheKey = $"GetOptionsSetTextForValue|{entityName}|{attributeName}" + $"|{selectedValue}|{Libraries.Common.Helpers.GetAssemblyName(0)}"; var attributeCached = CacheHelpers.GetFromMemCache <string>(cacheKey, orgId); if (attributeCached != null) { return(attributeCached); } var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request. var retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); // Access the retrieved attribute. var retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; var optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); return(CacheHelpers.AddToMemCache(cacheKey, (from oMD in optionList where oMD.Value == selectedValue select oMD.Label.LocalizedLabels[0].Label).FirstOrDefault(), DateTime.Now.AddHours(12), orgId)); }
public static Dictionary<int, string> GetOptionsSetValues(IOrganizationService service, string entityName, string attributeName) { var oList = new Dictionary<int, string>(); var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; var reqRespMD = ((RetrieveAttributeResponse)(service.Execute(retrieveAttributeRequest))).AttributeMetadata; OptionMetadata[] optionList = null; if (reqRespMD is Microsoft.Xrm.Sdk.Metadata.StatusAttributeMetadata) { var retrievedStatusAttributeMetadata = (StatusAttributeMetadata)reqRespMD; optionList = retrievedStatusAttributeMetadata.OptionSet.Options.ToArray(); } else { var retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)reqRespMD; optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); } // loop through the option set and add the ids and labels to the list foreach (OptionMetadata oMD in optionList) { if (oMD.Value.HasValue && !string.IsNullOrWhiteSpace(oMD.Label.UserLocalizedLabel.Label)) oList.Add(oMD.Value.Value, oMD.Label.UserLocalizedLabel.Label); } // return the populated list return oList; }
public static int getOptionSetValue(string entityName, string attributeName, string optionsetText, OrganizationService _service) { int optionSetValue = 0; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest(); retrieveAttributeRequest.EntityLogicalName = entityName; retrieveAttributeRequest.LogicalName = attributeName; retrieveAttributeRequest.RetrieveAsIfPublished = true; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_service.Execute(retrieveAttributeRequest); PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet; foreach (OptionMetadata optionMetadata in optionsetMetadata.Options) { if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower()) { optionSetValue = optionMetadata.Value.Value; return(optionSetValue); } } return(optionSetValue); }
public string getLabelFromField(Entity entity, string field, IOrganizationService context) { var fieldValue = ((OptionSetValue)entity.Attributes[field]).Value.ToString(); string fieldLabel = ""; //need to get Option Set display label based on its value. This requires getting attribute metadata RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entity.LogicalName, LogicalName = field, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest); EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; foreach (OptionMetadata om in attributeMetadata.OptionSet.Options) { if (om.Value == ((OptionSetValue)entity.Attributes[field]).Value) { fieldLabel = om.Label.UserLocalizedLabel.Label.ToString(); } } return fieldLabel; }
public OptionMetadata[] GetOptionSet(string entityName, string fieldName) { OptionMetadata[] optionMetadatas; IOrganizationService orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService); RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = fieldName, RetrieveAsIfPublished = false }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgService.Execute(attributeRequest); if (attributeResponse.AttributeMetadata.AttributeType == Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Boolean) { BooleanAttributeMetadata boolenAttributeMetadata = (BooleanAttributeMetadata)attributeResponse.AttributeMetadata; BooleanOptionSetMetadata boolenOptionSetMetadata = boolenAttributeMetadata.OptionSet; OptionMetadata[] options = new OptionMetadata[2]; options[0] = boolenOptionSetMetadata.TrueOption; options[1] = boolenOptionSetMetadata.FalseOption; optionMetadatas = options; } else { EnumAttributeMetadata picklistAttributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; OptionSetMetadata optionSetMetadata = picklistAttributeMetadata.OptionSet; OptionMetadata[] optionList = optionSetMetadata.Options.ToArray(); optionMetadatas = optionList; } return(optionMetadatas); }
public int getIndexOfLabel(string entityName, string field, string labelText, IOrganizationService context) { int index = -1; RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = field, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest); EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; foreach (OptionMetadata om in attributeMetadata.OptionSet.Options) { if (om.Label.UserLocalizedLabel.Label.ToString() == labelText) { if (om.Value != null) { index = om.Value.Value; } } } return index; }
/// <summary> /// Generic retrieve option set text values /// </summary> public static string GetOptionsSetTextOnValue(IOrganizationService service, string entityName, string attributeName, int selectedValue) { var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request. var retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); // Access the retrieved attribute. var retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); string selectedOptionLabel = string.Empty; foreach (OptionMetadata optionMetadata in optionList) { if (optionMetadata.Value == selectedValue) { selectedOptionLabel = optionMetadata.Label.UserLocalizedLabel.Label; } } return(selectedOptionLabel); }
public string GetOptionSetValueLabel(string entityname, string attribute, OptionSetValue option) { string optionLabel = String.Empty; RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityname, LogicalName = attribute, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_service.Execute(attributeRequest); AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata; PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata; // For every status code value within all of our status codes values // (all of the values in the drop down list) foreach (OptionMetadata optionMeta in picklistMetadata.OptionSet.Options) { // Check to see if our current value matches if (optionMeta.Value == option.Value) { // If our numeric value matches, set the string to our status code // label optionLabel = optionMeta.Label.UserLocalizedLabel.Label; } } return(optionLabel); }
public static string GetOptionsSetTextForValue(IOrganizationService service, string entityName, string attributeName, int selectedValue) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); // Access the retrieved attribute. StatusAttributeMetadata retrievedPicklistAttributeMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;// Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); string selectedOptionLabel = null; foreach (OptionMetadata oMD in optionList) { if (oMD.Value == selectedValue) { selectedOptionLabel = oMD.Label.LocalizedLabels[0].Label.ToString(); break; } } return(selectedOptionLabel); }
private void LoadcmbType() { cmbType.Items.Clear(); RetrieveAttributeRequest req = new RetrieveAttributeRequest(); req.EntityLogicalName = "incident"; req.LogicalName = "casetypecode"; req.RetrieveAsIfPublished = true; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)crmService.Execute(req); PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)attributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); foreach (OptionMetadata oMD in optionList) { foreach (var item in oMD.Label.LocalizedLabels) { if (item.LanguageCode == 1065) { ListItem _item = new ListItem(item.Label, oMD.Value.Value.ToString()); cmbType.Items.Add(_item); break; } } } }
public void Should_also_update_entity_metadata_when_not_using_global_option_set() { var label = "dummy label"; var attributeName = "statuscode"; var ctx = new XrmFakedContext(); var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata() { LogicalName = attributeName }; entityMetadata.SetAttributeCollection(new List <AttributeMetadata>() { enumAttribute }); ctx.InitializeMetadata(entityMetadata); var req = new InsertOptionValueRequest() { EntityLogicalName = Contact.EntityLogicalName, AttributeLogicalName = attributeName, Label = new Label(label, 0) }; var service = ctx.GetOrganizationService(); service.Execute(req); //Check the optionsetmetadata was updated var key = $"{Contact.EntityLogicalName}#{attributeName}"; Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key)); var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.Equal(label, option.Label.LocalizedLabels[0].Label); // Get a list of Option Set values for the Status Reason fields from its metadata RetrieveAttributeRequest attReq = new RetrieveAttributeRequest { EntityLogicalName = "contact", LogicalName = "statuscode", RetrieveAsIfPublished = true }; RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq); StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata; Assert.NotNull(statusAttributeMetadata.OptionSet); Assert.NotNull(statusAttributeMetadata.OptionSet.Options); Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Count(o => o.Label.LocalizedLabels[0].Label == label)); }
public IEnumerable<Category> GetCategories() { RetrieveAttributeRequest attr = new RetrieveAttributeRequest(); attr.LogicalName = "new_category"; attr.EntityLogicalName = "new_timeslot"; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_context.Execute(attr); return (attributeResponse.AttributeMetadata as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata).OptionSet.Options.Select(x => new Category() { Label = x.Label.LocalizedLabels.First().Label, Id = x.Value.Value }); }
public static AttributeMetadata GetAttributeMataData(IOrganizationService svc, string entityName, string attributeName) { var oRequest = new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; return ((RetrieveAttributeResponse)svc.Execute(oRequest)).AttributeMetadata; }
/// <summary> /// Fakes the RetrieveAttributeRequest that checks if an attribute exists for a given entity /// For simpicity, it asumes all attributes exist /// </summary> /// <param name="context"></param> /// <param name="fakedService"></param> protected static OrganizationResponse FakeRetrieveAttributeRequest(XrmFakedContext context, IOrganizationService fakedService, RetrieveAttributeRequest req) { var response = new RetrieveAttributeResponse { }; return response; }
public static AttributeMetadata GetAttributeMetadata(this IOrganizationService service, string entityLogicalName, string attributeLogicalName) { var request = new RetrieveAttributeRequest() { EntityLogicalName = entityLogicalName, LogicalName = attributeLogicalName }; return((service.Execute(request) as RetrieveAttributeResponse).AttributeMetadata); }
/// <summary> /// The function gets the attrubute metadata specifically to translate between text and value for option sets /// </summary> /// <param name="entity">Name of the entity (Constants.ENTITYNAME.This)</param> /// <param name="service"></param> /// <param name="property"></param> /// <returns></returns> static public RetrieveAttributeResponse RetrieveAttributeMetaData(this Entity entity, IOrganizationService service, string property) { RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest(); attribReq.EntityLogicalName = entity.LogicalName; attribReq.LogicalName = property; attribReq.RetrieveAsIfPublished = true; return((RetrieveAttributeResponse)service.Execute(attribReq)); }
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 static AttributeMetadata GetMetadata(IOrganizationService orgSvc, Guid attributeId) { var retrieveAttributeRequest = new RetrieveAttributeRequest { MetadataId = attributeId }; var retrieveAttributeResponse = (RetrieveAttributeResponse)orgSvc.Execute(retrieveAttributeRequest); return(retrieveAttributeResponse.AttributeMetadata); }
public static PickListEnums GetOptionPickListValues(string entityLogicalName, string entityDisplayName, string attributeName, IOrganizationService _serviceProxy) { // set the properties to get back the codeable concept picklist values // from the picklist (optionset) RetrieveAttributeRequest retrieveEntityRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // execute the call and retrieve the actual metadata directly RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveEntityRequest); var attributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; // retrieve each option list item var optionList = (from o in attributeMetadata.OptionSet.Options select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList(); // iterate through each option and write out the value and text // this will enable us to map the "Text" value given to us in the // codeable concepts file that we generated OR if you generate some new ones // you can run this program again to create the mapping file // or at least have the copy that was generated for you PickListEnums ple = new PickListEnums(); ple.AttributeLogicalName = attributeName; ple.EntityDisplayName = entityDisplayName; ple.EntityLogicalName = entityLogicalName; ple.EnumName = GenerateEnumName(entityDisplayName, attributeName); foreach (var option in optionList) { totalOptions++; PickListValues plv = new PickListValues(); // add to our stirng list of options picklistmappingdata.Add(entityDisplayName + "," + entityLogicalName + "," + attributeName + "," + option.Text.Trim() + "," + option.Value.ToString().Trim()); //default to first string of the label plv.PickListDisplay = option.Text.Trim(); plv.PickListValue = option.Value.ToString().Trim(); ple.EnumValues.Add(option.Text.Trim(), plv); // write out our option count Console.SetCursorPosition(0, Console.CursorTop); Console.WriteLine("Total Options Found [" + totalOptions.ToString() + "]"); System.Threading.Thread.Sleep(1); } return(ple); }
/// <summary> /// Gets a <c>Picklist</c> instance who's values are set based on the parameters provided. /// </summary> /// <param name="entity">The current <c>Entity</c>.</param> /// <param name="field">The current <c>DefinitionField</c> for the property being mapped to this <c>Picklist</c>.</param> /// <param name="mappedLookupObject">The <c>Dictionary</c> containing the lookup information for the <c>Picklist</c>.</param> /// <param name="crm2011Adapter">The <c>CRM2011Adapter</c> to use when calling the CRM web service.</param> /// <param name="providedEntityName">The name of the <c>Entity</c> that the current object provider is for.</param> /// <returns>A <c>Picklist</c> with it's value property set to the one requested in the <c>Dictionary</c>, if one is found and <c>null</c> otherwise.</returns> /// <exception cref="ArgumentException">Thrown if the requested value is not currently in the <c>Picklist</c> within the CRM system.</exception> public static OptionSetValue MapPicklist(Entity entity, FieldDefinition field, Dictionary <string, object> mappedLookupObject, DynamicCrmAdapter crm2011Adapter, string providedEntityName) { if (entity == null || field == null || crm2011Adapter == null) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage)) { ExceptionId = AdapterException.SystemExceptionGuid }; } ValidateDictionary(mappedLookupObject); if (!mappedLookupObject.Keys.Contains("Value")) { if (!mappedLookupObject.Keys.Contains("name") || string.IsNullOrEmpty(mappedLookupObject["name"] as string)) { return(null); } RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest() { EntityLogicalName = entity.LogicalName, LogicalName = field.Name, RetrieveAsIfPublished = true }; if (IsSpecialAddressPicklist(entity, field)) { attribReq.EntityLogicalName = providedEntityName; attribReq.LogicalName = string.Format(CultureInfo.CurrentCulture, "address{0}_{1}", ((int?)entity["addressnumber"]).Value.ToString(CultureInfo.CurrentCulture), field.Name); } // Get the attribute metadata for the state attribute. RetrieveAttributeResponse metadataResponse = (RetrieveAttributeResponse)crm2011Adapter.OrganizationService.Execute(attribReq); PicklistAttributeMetadata picklistAttrib = (PicklistAttributeMetadata)metadataResponse.AttributeMetadata; var picklistValue = from option in picklistAttrib.OptionSet.Options where option.Label.UserLocalizedLabel.Label.ToUpperInvariant() == mappedLookupObject["name"].ToString().ToUpperInvariant() select option.Value; // ensure that both the returned list and the first item in the returned list are not null or empty. if ((picklistValue.Count() > 0) && (picklistValue.First() != null)) { return(new OptionSetValue(picklistValue.First().Value)); } throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.PicklistValueNotFound, mappedLookupObject["name"].ToString(), field.DisplayName, entity.LogicalName)) { ExceptionId = ErrorCodes.PicklistMappingNotFound }; } OptionSetValue mapping = new OptionSetValue(); SetRelationshipValuesFromDictionary(mappedLookupObject, mapping); return(mapping); }
public static void When_retrieve_attribute_request_is_called_an_exception_is_not_thrown() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); RetrieveAttributeRequest req = new RetrieveAttributeRequest() { EntityLogicalName = "account", LogicalName = "name" }; Assert.Throws<PullRequestException>(() => service.Execute(req)); }
/// <summary> /// Returns the number of options for a picklist /// </summary> /// <param name="entityName">name of the entity</param> /// <param name="picklistName">name of the picklist</param> /// <param name="service">CRM service</param> /// <returns>integer count</returns> public static int GetPicklistOptionCount(string entityName, string picklistName, IOrganizationService service) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = picklistName, RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponseWrapper retrieveAttributeResponse = (new RetrieveAttributeResponseWrapper(service.Execute(retrieveAttributeRequest))); //this is the only change from before // Access the retrieved attribute. PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); return optionList.Length; }
public string GetEntityStatusLabel(string entityLogicalName, int statusCode) { // Create the attribute request (define which entities attribute // information we want to get) entity.LogicalName is our current // name of our entity (ex: contact, account, etc.) RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = "statuscode", RetrieveAsIfPublished = true }; // Execute the request to get the attribute information RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)XrmContext.Execute(attributeRequest); AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata; // Cast the AttributeMetadata to StatusAttribute data StatusAttributeMetadata statusAttrMetadata = (StatusAttributeMetadata)attrMetadata; // Get the status code label by comparing all of the status code values // possible for the status code drop down list. Once we get a match on // the value we take the label for that value // For every status code value within all of our status codes values // (all of the values in the drop down list) foreach (StatusOptionMetadata statusMeta in statusAttrMetadata.OptionSet.Options) { // Check to see if our current value matches if (statusMeta.Value == statusCode) { // If our numeric value matches, set the string to our status code // label return statusMeta.Label.UserLocalizedLabel.Label; } } // if we got this far, something didn't add up. return string.Empty; }
/// <summary> /// Returns the OptionMetadataCollection for an entity attribute option set. Unless you already have an IOrganizationService, use the CrmService's GetEntityOptionSet method since it won't create a new connection to the server if the value is already cached. /// </summary> /// <param name="service">The service.</param> /// <param name="entityLogicalName">Logical name of the entity.</param> /// <param name="attributeName">Attribute name of the entity.</param> /// <returns></returns> public static OptionMetadataCollection GetEntityOptionSet(this IOrganizationService service, string entityLogicalName, string attributeName) { string key = GetEntityOptionSetKey(service.GetOrganizationKey(), entityLogicalName, attributeName); OptionMetadataCollection options; if (!_optionSets.TryGetValue(key, out options)) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = attributeName, RetrieveAsIfPublished = true }; var response = (RetrieveAttributeResponse)service.Execute(attributeRequest); options = ((EnumAttributeMetadata)response.AttributeMetadata).OptionSet.Options; _optionSets.AddOrUpdate(key, options, (k, o) => o); // If the value already exists, just use the old value... } return options; }
public int getOptionSetValue(string entityName, string attributeName, string optionsetText) { int optionSetValue = 0; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest(); retrieveAttributeRequest.EntityLogicalName = entityName; retrieveAttributeRequest.LogicalName = attributeName; retrieveAttributeRequest.RetrieveAsIfPublished = true; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest); PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet; foreach (OptionMetadata optionMetadata in optionsetMetadata.Options) { if (optionMetadata.Label.UserLocalizedLabel.Label.ToString() == optionsetText) { optionSetValue = optionMetadata.Value.Value; return optionSetValue; } } return optionSetValue; }
private RetrieveAttributeResponse ExecuteRetrieveAttributeRequest(string entityName, string attributeName) { RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entityName; request.LogicalName = attributeName; request.RetrieveAsIfPublished = true; return (RetrieveAttributeResponse)_service.Execute(request); }
private void AssertCanDelete(IOrganizationService service, AttributeMetadata attribute) { Trace("Checking for Delete Dependencies for " + attribute.EntityLogicalName + "." + attribute.LogicalName); var depends = (RetrieveDependenciesForDeleteResponse)service.Execute(new RetrieveDependenciesForDeleteRequest { ComponentType = (int)ComponentType.Attribute, ObjectId = attribute.MetadataId.GetValueOrDefault() }); var errors = new List<string>(); foreach (var d in depends.EntityCollection.ToEntityList<Dependency>()) { var type = (ComponentType)d.DependentComponentType.GetValueOrDefault(); var dependentId = d.DependentComponentObjectId.GetValueOrDefault(); var err = type + " " + dependentId; switch (type) { case ComponentType.Attribute: var req = new RetrieveAttributeRequest { MetadataId = dependentId }; var dependent = ((RetrieveAttributeResponse)service.Execute(req)).AttributeMetadata; err = $"{err} ({dependent.EntityLogicalName + " : " + dependent.DisplayName.GetLocalOrDefaultText()}"; break; case ComponentType.EntityRelationship: var response = (RetrieveRelationshipResponse)service.Execute(new RetrieveRelationshipRequest { MetadataId = dependentId }); Trace("Entity Relationship / Mapping {0} must be manually removed/added", response.RelationshipMetadata.SchemaName); break; case ComponentType.SavedQueryVisualization: var sqv = service.GetEntity<SavedQueryVisualization>(dependentId); err = $"{err} ({sqv.Name} - {sqv.CreatedBy.Name})"; break; case ComponentType.SavedQuery: var sq = service.GetEntity<SavedQuery>(dependentId); err = $"{err} ({sq.Name} - {sq.CreatedBy.Name})"; break; case ComponentType.Workflow: var workflow = service.GetEntity<Workflow>(d.DependentComponentObjectId.GetValueOrDefault()); err = err + " " + workflow.Name + " (" + workflow.CategoryEnum + ")"; break; } errors.Add(err); } if (errors.Count > 0) { throw new Exception("Dependencies found: " + Environment.NewLine + "\t" + string.Join(Environment.NewLine + "\t", errors)); } }
public CRMPicklist CRMGetPicklist(CRMPicklist picklist) { OrganizationServiceProxy _serviceProxy; using (_serviceProxy = GetCRMConnection()) { try { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = picklist.EntityLogicalName, LogicalName = picklist.AttributeLogicalName }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeRequest); PicklistAttributeMetadata pick = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; StateAttributeMetadata a = new StateAttributeMetadata(); List<CRMPicklistOption> options = new List<CRMPicklistOption>(); foreach (OptionMetadata o in pick.OptionSet.Options) { CRMPicklistOption option = new CRMPicklistOption(); option.PicklistValue = o.Value.HasValue ? o.Value.Value : 0; option.PicklistLabel = o.Label.UserLocalizedLabel.Label; options.Add(option); } picklist.Picklist = options; } catch (Exception ex) { throw; } } return picklist; }
/// <summary> /// Get PickList Metadata /// </summary> /// <param name="entityLogicalName"></param> /// <param name="logicalName"></param> /// <returns></returns> private static OptionMetadataCollection _GetPicklistMetaData(string entityLogicalName, string logicalName) { var result = new OptionMetadataCollection(); RetrieveAttributeRequest request = new RetrieveAttributeRequest(); request.EntityLogicalName = entityLogicalName; request.LogicalName = logicalName; // get the reference type request.RetrieveAsIfPublished = true; RetrieveAttributeResponse response; try { using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm"))) { response = (RetrieveAttributeResponse)svc.Execute(request); } if (response.AttributeMetadata is StatusAttributeMetadata) { StatusAttributeMetadata picklist = (StatusAttributeMetadata)response.AttributeMetadata; OptionMetadataCollection omd = picklist.OptionSet.Options; result = omd; } else { PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata; OptionMetadataCollection omd = picklist.OptionSet.Options; result = omd; } return result; } catch (Exception ex) { Util.WriteErrorToLog("_GetPicklistMetaData", new Dictionary<string, string>() { { "entityLogicalName", entityLogicalName }, { "logicalName", logicalName} }, ex); throw ex; } }
private string RetrieveAttributeMetadataPicklistValue(IOrganizationService CrmService, int AddTypeValue, string Entity, string LogicalName) { RetrieveAttributeRequest objRetrieveAttributeRequest; objRetrieveAttributeRequest = new RetrieveAttributeRequest(); objRetrieveAttributeRequest.EntityLogicalName = Entity; objRetrieveAttributeRequest.LogicalName = LogicalName; int indexAddtypeCode = AddTypeValue - 1; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)CrmService.Execute(objRetrieveAttributeRequest); PicklistAttributeMetadata objPckLstAttMetadata = new PicklistAttributeMetadata(); ICollection<object> objCollection = attributeResponse.Results.Values; objPckLstAttMetadata.OptionSet = ((EnumAttributeMetadata)(objCollection.ElementAt(0))).OptionSet; Microsoft.Xrm.Sdk.Label objLabel = objPckLstAttMetadata.OptionSet.Options[indexAddtypeCode].Label; string lblAddTypeLabel = objLabel.LocalizedLabels.ElementAt(0).Label; return lblAddTypeLabel; }
public IDictionary<int, string> GetOptionSetValues(string entityLogicalName, string optionSetLogicalName) { IDictionary<int, string> optionSet = new Dictionary<int, string>(); if (string.IsNullOrEmpty(entityLogicalName) || string.IsNullOrEmpty(optionSetLogicalName)) return null; var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = optionSetLogicalName }; var retrieveAttributeResponse = (RetrieveAttributeResponse)XrmContext.Execute(retrieveAttributeRequest); var retrievedPicklistAttributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; for (int i = 0; i < retrievedPicklistAttributeMetadata.OptionSet.Options.Count(); i++) { optionSet.Add(new KeyValuePair<int, string>(retrievedPicklistAttributeMetadata.OptionSet.Options[i].Value.Value, retrievedPicklistAttributeMetadata.OptionSet.Options[i].Label.LocalizedLabels[0].Label)); } return optionSet; }
private void RefreshFieldMetadata(string schemaName, string entityType) { lock (LockObject) { var fieldMetadata = GetEntityFieldMetadata(entityType); if (fieldMetadata.Any(m => m.SchemaName == schemaName)) fieldMetadata.Remove(fieldMetadata.Single(m => m.SchemaName == schemaName)); var request = new RetrieveAttributeRequest { EntityLogicalName = entityType, LogicalName = schemaName, RetrieveAsIfPublished = true }; var response = (RetrieveAttributeResponse) Execute(request); fieldMetadata.Add(response.AttributeMetadata); } }
public void Create(string entityName, [FromBody] JObject objStructure) { var connectionString = ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString; CrmConnection crmConnection = CrmConnection.Parse(connectionString); using (OrganizationService service = new OrganizationService(crmConnection)) { if (objStructure != null) { Entity entity = new Entity(entityName); Guid guidValue; foreach (var attribute in objStructure) { if (Guid.TryParse(attribute.Value.ToString(), out guidValue)) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attribute.Key.ToString(), RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Lookup) { string relatedEntityName = ((LookupAttributeMetadata)(attributeResponse.AttributeMetadata)).Targets[0]; EntityReference eref = new EntityReference(relatedEntityName, guidValue); entity[attribute.Key.ToString()] = eref; continue; } } entity[attribute.Key.ToString()] = attribute.Value.ToString(); } service.Create(entity); } } }
public CRMPicklist CRMGetStateStatus(CRMPicklist picklist) { OrganizationServiceProxy _serviceProxy; using (_serviceProxy = GetCRMConnection()) { try { RetrieveAttributeRequest retrieveAttributeStateRequest = new RetrieveAttributeRequest { EntityLogicalName = picklist.EntityLogicalName, LogicalName = "statecode", }; RetrieveAttributeResponse retrieveAttributeStateResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeStateRequest); RetrieveAttributeRequest retrieveAttributeStatusRequest = new RetrieveAttributeRequest { EntityLogicalName = picklist.EntityLogicalName, LogicalName = "statuscode" }; RetrieveAttributeResponse retrieveAttributeStatusResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(retrieveAttributeStatusRequest); StateAttributeMetadata state = (StateAttributeMetadata)retrieveAttributeStateResponse.AttributeMetadata; StatusAttributeMetadata status = (StatusAttributeMetadata)retrieveAttributeStatusResponse.AttributeMetadata; List<CRMPicklistOption> options = new List<CRMPicklistOption>(); foreach (StatusOptionMetadata o in status.OptionSet.Options) { OptionMetadata s = state.OptionSet.Options.Where(p => p.Value.Value == o.State.Value).First(); CRMPicklistOption option = new CRMPicklistOption(); option.PicklistValue = o.Value.HasValue ? o.Value.Value : 0; option.PicklistLabel = o.Label.UserLocalizedLabel.Label; option.PicklistParentLabel = s.Label.UserLocalizedLabel.Label.ToString(); option.PicklistParentValue = s.Value.HasValue ? s.Value.Value : 0; options.Add(option); } picklist.Picklist = options; } catch (Exception ex) { throw; } } return picklist; }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var optionSet = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata() }; response.Results["AttributeMetadata"] = optionSet; var enumExpression = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().Where(t => t.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0 && t.GetCustomAttributes(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute), false).Length > 0 && t.Name.Contains(request.LogicalName)).ToList(); // Search By EntityLogicalName_LogicalName // Then By LogicName_EntityLogicalName // Then By LogicaName var enumType = enumExpression.FirstOrDefault(t => t.Name == request.EntityLogicalName + "_" + request.LogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName + "_" + request.EntityLogicalName) ?? enumExpression.FirstOrDefault(t => t.Name == request.LogicalName); AddEnumTypeValues(optionSet.OptionSet, enumType, String.Format("Unable to find local optionset enum for entity: {0}, attribute: {1}", request.EntityLogicalName, request.LogicalName)); return response; }
public string GetOptionSetLabelByValue(string entityLogicalName, string optionSetLogicalName, int value) { if (string.IsNullOrEmpty(entityLogicalName) || string.IsNullOrEmpty(optionSetLogicalName)) { return string.Empty; } var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = optionSetLogicalName }; var retrieveAttributeResponse = (RetrieveAttributeResponse)XrmContext.Execute(retrieveAttributeRequest); var retrievedPicklistAttributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; var option = retrievedPicklistAttributeMetadata.OptionSet.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; }
public OptionMetadataCollection getOptionSetValues(string entityName, string attributeName) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest(); retrieveAttributeRequest.EntityLogicalName = entityName; retrieveAttributeRequest.LogicalName = attributeName; retrieveAttributeRequest.RetrieveAsIfPublished = true; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)context.Execute(retrieveAttributeRequest); PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet; return optionsetMetadata.Options; }
public Dictionary<int, string> getOptionSet(string entityName, string attributeName) { // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_service.Execute(attributeRequest); PicklistAttributeMetadata retrievedOptionSet = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata; OptionMetadata[] optionSet = retrievedOptionSet.OptionSet.Options.ToArray(); Dictionary<int, string> eventTypes = new Dictionary<int, string>(); foreach (OptionMetadata om in optionSet) { eventTypes.Add((int)om.Value, om.Label.UserLocalizedLabel.Label); } return eventTypes; }
/// <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; } }
public int GetOptionSetValueByLabel(string entityLogicalName, string optionSetLogicalName, string label) { if (string.IsNullOrEmpty(entityLogicalName) || string.IsNullOrEmpty(optionSetLogicalName)) { return 0; } var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityLogicalName, LogicalName = optionSetLogicalName }; var retrieveAttributeResponse = (RetrieveAttributeResponse)XrmContext.Execute(retrieveAttributeRequest); var retrievedPicklistAttributeMetadata = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata; int value = 0; for (int i = 0; i < retrievedPicklistAttributeMetadata.OptionSet.Options.Count(); i++) { if (retrievedPicklistAttributeMetadata.OptionSet.Options[i].Label.LocalizedLabels[0].Label == label) value = retrievedPicklistAttributeMetadata.OptionSet.Options[i].Value.Value; } return value; }
// Retrieve the display name and parent entity information about an attribute solution component. public string getAttributeInformation(Guid id) { String attributeInformation = ""; RetrieveAttributeRequest req = new RetrieveAttributeRequest { MetadataId = id }; RetrieveAttributeResponse resp = (RetrieveAttributeResponse)_serviceProxy.Execute(req); AttributeMetadata attmet = resp.AttributeMetadata; attributeInformation = attmet.EntityLogicalName + " : " + attmet.DisplayName.UserLocalizedLabel.Label; return attributeInformation; }
private string GetOptionSetValueLabel(IOrganizationService service, Entity entity, string attribute, OptionSetValue option) { string optionLabel = String.Empty; var attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entity.LogicalName, LogicalName = attribute, RetrieveAsIfPublished = true }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata; PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata; // For every status code value within all of our status codes values // (all of the values in the drop down list) foreach (OptionMetadata optionMeta in picklistMetadata.OptionSet.Options) { // Check to see if our current value matches if (optionMeta.Value == option.Value) { // If our numeric value matches, set the string to our status code // label optionLabel = optionMeta.Label.UserLocalizedLabel.Label; } } return optionLabel; }