/// <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; } }
private void ParseOptionSetValues(AttributeMetadata attribute) { if (attribute is PicklistAttributeMetadata) { var values = new NameValueCollection(); PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)attribute; foreach (var c in optionMetadata.OptionSet.Options) { values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString()); } OptionSetValues = values; } else if (attribute is StateAttributeMetadata) { var values = new NameValueCollection(); StateAttributeMetadata optionMetadata = (StateAttributeMetadata)attribute; foreach (var c in optionMetadata.OptionSet.Options) { values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString()); } OptionSetValues = values; } else if (attribute is StatusAttributeMetadata) { var values = new NameValueCollection(); StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)attribute; foreach (var c in optionMetadata.OptionSet.Options) { values.Add(ProcessName(c.Label.UserLocalizedLabel.Label), c.Value?.ToString()); } OptionSetValues = values; } }
public static AttributeCardModel ToCard(this AttributeMetadata attribute) { AttributeCardModel attributeCard = new AttributeCardModel(attribute.DisplayName.UserLocalizedLabel.Label, attribute.LogicalName); if (attribute is PicklistAttributeMetadata) { PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)attribute; if (picklistAttributeMetadata != null) { var options = new List <OptionAttributeModel>(); foreach (var option_ in picklistAttributeMetadata?.OptionSet?.Options) { var optionAttributeModel = new OptionAttributeModel(option_.Label.UserLocalizedLabel.Label, option_.Value.Value); options.Add(optionAttributeModel); } attributeCard.Properties = options; } } else if (attribute is BooleanAttributeMetadata) { BooleanAttributeMetadata booleanOptionSetMetadata = (BooleanAttributeMetadata)attribute; if (booleanOptionSetMetadata != null) { var options = new List <OptionAttributeModel>(); options.Add(new OptionAttributeModel(booleanOptionSetMetadata?.OptionSet.TrueOption.Label.UserLocalizedLabel.Label, true)); options.Add(new OptionAttributeModel(booleanOptionSetMetadata?.OptionSet.FalseOption.Label.UserLocalizedLabel.Label, false)); attributeCard.Properties = options; } } return(attributeCard); }
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); }
public void OptionSetBeanTest01() { LocalizedLabel lLabel = new LocalizedLabel("Option1", 1041); LocalizedLabel lLabel2 = new LocalizedLabel("Option2", LANG_CODE); PicklistAttributeMetadata meta = new PicklistAttributeMetadata(); meta.OptionSet = new OptionSetMetadata() { Name = "optionSet", DisplayName = new Label("optiondisplay", LANG_CODE), Options = { new OptionMetadata(new Label(lLabel, null), 1), new OptionMetadata(new Label("Option2", LANG_CODE), 2), new OptionMetadata(new Label(lLabel2, null), 3) } }; OptionSetBean cls = new OptionSetBean(meta); Assert.True(cls.HasOptionSet()); Assert.AreEqual("Option1", cls.GetValue(1), "ラベルあり"); Assert.Null(cls.GetValue(2), "ラベルなし"); Assert.AreEqual("Option2", cls.GetValue(3), "ラベルあり"); }
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); }
private OptionSetValue ConvertToOptionSet(object value, AttributeMetadata fieldMetadata) { OptionSetValue optionsetValue; int intValue = default(int); if (value.GetType() == typeof(int)) { intValue = (int)value; } else { var found = false; // try to get the optionset value from a string PicklistAttributeMetadata optionsetMetadata = (PicklistAttributeMetadata)fieldMetadata; foreach (var optionMetadata in optionsetMetadata.OptionSet.Options) { if (optionMetadata.Label.UserLocalizedLabel.Label == (string)value) { intValue = optionMetadata.Value.Value; found = true; break; } } if (!found) { throw new Exception("Optionset value nor found"); } } optionsetValue = new OptionSetValue(intValue); return(optionsetValue); }
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; } }
// 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); }
/// <summary> /// helper method to retrieve option set text /// </summary> /// <param name="entityName"></param> /// <param name="attributeName"></param> /// <param name="optionsetValue"></param> /// <param name="orgService"></param> /// <returns></returns> public static string GetOptionSetText(string entityName, string attributeName, int optionsetValue, IOrganizationService orgService) { try { string optionsetText = string.Empty; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)orgService.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); } catch (Exception ex) { throw new InvalidPluginExecutionException("Error: Unable to load value for " + attributeName, ex); } }
public void GetNameForOptionSet_NonGlobal() { var optionSet = new OptionSetMetadata { Name = "OptionsetName" }; var attMetadata = new PicklistAttributeMetadata { LogicalName = "ee_testid", DisplayName = new Label("Test_OptionsetName", 1033), OptionSet = optionSet }; var em = new EntityMetadata { LogicalName = "ee_test", DisplayName = new Label("Test", 1033), DisplayCollectionName = new Label("Tests", 1033) }; em.Set(x => x.Attributes, new[] { attMetadata }); organizationMetadata.Entities.Returns(new[] { em }); organizationMetadata.OptionSets.Returns(new OptionSetMetadata [0]); var result = sut.GetNameForOptionSet(em, optionSet, serviceProvider); Assert.AreEqual(result, "Test_OptionsetName"); }
public PicklistAttributeMetadata CreateOptionSet(string schema, string label, int lang, AttributeRequiredLevel requiredLevel, string[] optionLabels) { OptionMetadataCollection options = new OptionMetadataCollection(); foreach (string o in optionLabels) { options.Add(new OptionMetadata(new Label(o, lang), null)); } OptionSetMetadata optMetadata = new OptionSetMetadata(options) { IsGlobal = false, OptionSetType = OptionSetType.Picklist, }; PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = schema, DisplayName = new Label(label, lang), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), //Description = new Label("Picklist Attribute", lang), // Set extended properties // Build local picklist options OptionSet = optMetadata }; return(pickListAttribute); }
/// <summary> /// Obtém os rótulos de um determino OptionSetValue (Picklist). /// <para>Ação executado com o usuário Master (CRM ADMIN)</para> /// </summary> /// <param name="propertyName">Nome da priedade do domínio.</param> /// <returns>Retorna um dicionário com o value sendo "key" e rótulo sendo o value</returns> public Dictionary <int, string> RetrieveLabelOptionSetValue(string propertyName) { Dictionary <int, string> dic = new Dictionary <int, string>(); var request = new RetrieveAttributeRequest() { EntityLogicalName = Utility.GetEntityName <T>(), LogicalName = Utility.GetLogicalAttribute <T>(propertyName).Name }; RetrieveAttributeResponse response = (RetrieveAttributeResponse)this.Provider.Execute(request); if (response.Results.Count > 0) { if (response.Results.Values.ElementAt(0).GetType() != typeof(PicklistAttributeMetadata)) { throw new Exception("Atributo informado não é do tipo OptionSetValue"); } var picklist = new PicklistAttributeMetadata(); picklist.OptionSet = ((EnumAttributeMetadata)response.Results.Values.ElementAt(0)).OptionSet; foreach (var item in picklist.OptionSet.Options) { if (!item.Value.HasValue) { continue; } dic.Add(item.Value.Value, item.Label.LocalizedLabels.ElementAt(0).Label); } } return(dic); }
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 List <OptionsetField> GetLocalOptionSet(string optionSetName, string entityName) { List <OptionsetField> optionSets = new List <OptionsetField>(); ServerConnection cnx = new ServerConnection(); try { RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = entityName }; RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)cnx.Service.Execute(retrieveDetails); EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata; PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals (attribute.LogicalName, optionSetName, StringComparison.OrdinalIgnoreCase)) as PicklistAttributeMetadata; picklistMetadata.OptionSet.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); }
private AttributeMetadata CloneAttributes(PicklistAttributeMetadata att) { var picklist = new PicklistAttributeMetadata { FormulaDefinition = att.FormulaDefinition, DefaultFormValue = att.DefaultFormValue, OptionSet = att.OptionSet }; if (picklist.OptionSet.IsGlobal.GetValueOrDefault()) { // Can't send picklist.OptionSet.Options.Clear(); } else { // Can't reuse an existing local Option Set var optionSet = picklist.OptionSet; if (optionSet.Name.EndsWith(TempPostfix)) { optionSet.Name = optionSet.Name.Remove(optionSet.Name.Length - TempPostfix.Length); } else { optionSet.Name = optionSet.Name + TempPostfix; } optionSet.MetadataId = null; } return picklist; }
private List <KeyValuePair <string, string> > RetrieveAttributeMetadata(string entityName, string attributeName) { RetrieveAttributeRequest request = new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse response = (RetrieveAttributeResponse)service.Execute(request); PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)response.AttributeMetadata; OptionSetMetadata optionsetMetadata = (OptionSetMetadata)picklistMetadata.OptionSet; List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >(); foreach (OptionMetadata option in optionsetMetadata.Options) { int? optionKey = option.Value; string optionValue = option.Label.UserLocalizedLabel.Label; if (optionKey.HasValue) { int optionKeyValue = optionKey.Value; list.Add(new KeyValuePair <string, string>(optionKeyValue.ToString(), optionValue)); } } return(list); }
private static IList <OptionMetadata> RetrieveOptionSetAttributeMetadata(string entityLogicalName, string attributeLogicalName) { PicklistAttributeMetadata osvAttrMetadata = RetrieveAttributeMetadata <PicklistAttributeMetadata>(entityLogicalName, attributeLogicalName); return(osvAttrMetadata?.OptionSet.Options.ToList()); }
private void UpdateEntityOptionSet() { int?newValue = Value; if (!Value.HasValue) { // Must be new newValue = _repository.AddOptionSetValue(Entity, Attribute, DisplayName, Value, Description); } else { // Can be new or update PicklistAttributeMetadata optionSetAttribute = (PicklistAttributeMetadata)_repository.GetAttribute(Entity, Attribute); if (optionSetAttribute.OptionSet.Options.Any(o => o.Value.Value.Equals(Value.Value))) { // Existing; Do update _repository.UpdateOptionSetValue(Entity, Attribute, Value.Value, DisplayName, Description); } else { // Not existing; Do new newValue = _repository.AddOptionSetValue(Entity, Attribute, DisplayName, Value, Description); } } }
private void CreateOptionSetField(JToken field) { CreateAttributeRequest req = new CreateAttributeRequest(); req.EntityName = field["entity"].ToString(); var am = new PicklistAttributeMetadata(); am.SchemaName = field["schemaname"].ToString(); am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); am.DisplayName = new Label(field["displayname"].ToString(), 1033); am.Description = new Label("", 1033); OptionSetMetadata os = new OptionSetMetadata(); os.IsGlobal = false; foreach (var option in field["options"]) { Label label = new Label(option["displayname"].ToString(), 1033); int? value = JSONUtil.GetInt32(option, "value"); os.Options.Add(new OptionMetadata(label, value)); } am.OptionSet = os; req.Attribute = am; this._cdsConnection.Execute(req); }
public static OptionSetValue getOptionSetValue(IOrganizationService service, string entityName, string attributeName, string optionsetText) { OptionSetValue optionSetValue = new OptionSetValue(); RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest(); retrieveAttributeRequest.EntityLogicalName = entityName; retrieveAttributeRequest.LogicalName = attributeName; retrieveAttributeRequest.RetrieveAsIfPublished = true; try { 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.Value = optionMetadata.Value.Value; return(optionSetValue); } } return(optionSetValue); } catch (Exception) { return(optionSetValue); } }
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); }
private AttributeMetadata CloneAttributes(PicklistAttributeMetadata att) { var picklist = new PicklistAttributeMetadata { DefaultFormValue = att.DefaultFormValue, FormulaDefinition = att.FormulaDefinition, OptionSet = att.OptionSet, SourceType = att.SourceType }; if (picklist.OptionSet.IsGlobal.GetValueOrDefault()) { // Can't send picklist.OptionSet.Options.Clear(); } else { // Can't reuse an existing local Option Set var optionSet = picklist.OptionSet; if (optionSet.Name.EndsWith(TempPostfix)) { optionSet.Name = optionSet.Name.Remove(optionSet.Name.Length - TempPostfix.Length); } else { optionSet.Name = optionSet.Name + TempPostfix; } optionSet.MetadataId = null; } return(picklist); }
private object CopyValueInternal(PicklistAttributeMetadata oldAttribute, PicklistAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping) { var copy = ((OptionSetValue)value).Value.ToString(); copy = migrationMapping.TryGetValue(copy, out var mappedValue) ? mappedValue : copy; return(new OptionSetValue(int.Parse(copy))); }
public void GenerateGlobalOptionSetNoMatch() { var optionSetMetadata = new OptionSetMetadata { IsGlobal = true, OptionSetType = OptionSetType.Picklist, Name = "ee_TestOpt" }; var id = Guid.NewGuid(); var attId = Guid.NewGuid(); var attributeMetadata = new PicklistAttributeMetadata { MetadataId = attId, OptionSet = optionSetMetadata }.Set(x => x.EntityLogicalName, "ee_test"); organizationMetadata.Entities.Returns(new[] { new EntityMetadata { LogicalName = "ee_test", MetadataId = id, } .Set(x => x.Attributes, new[] { attributeMetadata }) }); SolutionHelper.organisationService.RetrieveMultiple(Arg.Any <QueryExpression>()) .Returns(new EntityCollection(new List <Entity> { new Entity("solutioncomponent") { Attributes = { { "objectid", id }, { "componenttype", 1 } } } })); var result = sut.GenerateOptionSet(optionSetMetadata, serviceProvider); Assert.IsFalse(result); }
public void GeneratePicklistAttribute() { var id = Guid.NewGuid(); var testId = Guid.NewGuid(); var attributeMetadata = new PicklistAttributeMetadata { LogicalName = "ee_testid", MetadataId = testId, DisplayName = new Label("Test Id", 1033) }.Set(x => x.EntityLogicalName, "ee_test"); organizationMetadata.Entities.Returns(new[] { new EntityMetadata { LogicalName = "ee_test", MetadataId = id, DisplayName = new Label("Test", 1033) } .Set(x => x.Attributes, new[] { attributeMetadata }) }); SolutionHelper.organisationService.RetrieveMultiple(Arg.Any <QueryExpression>()) .Returns(new EntityCollection(new List <Entity> { Builder.Create <SolutionComponent>().Set(x => x.Regarding, id).Set(x => x.ObjectTypeCode, ComponentType.Entity), Builder.Create <SolutionComponent>().Set(x => x.Regarding, testId).Set(x => x.ObjectTypeCode, ComponentType.Attribute), })); var result = sut.GenerateAttribute(attributeMetadata, serviceProvider); Assert.IsTrue(result); }
public string getOptionSetText(string entityName, string attributeName, int optionsetValue) { string optionsetText = string.Empty; 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.Value == optionsetValue) { optionsetText = optionMetadata.Label.UserLocalizedLabel.Label; return(optionsetText); } } return(optionsetText); }
public EntityAttributeMetadataBuilder PicklistAttribute(string schemaName, string displayName, string description, AttributeRequiredLevel requiredLevel, bool isGlobal, OptionSetType optionSetType, Dictionary <string, int> optionValues) { // Define the primary attribute for the entity // Create a integer attribute int languageCode = 1033; var att = new PicklistAttributeMetadata() { // Set base properties SchemaName = schemaName, DisplayName = new Label(schemaName, languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(description, languageCode), // Set extended properties OptionSet = new OptionSetMetadata { IsGlobal = isGlobal, OptionSetType = optionSetType } }; foreach (var optionValue in optionValues) { att.OptionSet.Options.Add(new OptionMetadata(new Label(optionValue.Key, languageCode), optionValue.Value)); } this.Attributes.Add(att); return(this); }
public void SetUp() { var fullNameField = new AttributeMetadata(); fullNameField.SetName("fullname"); fullNameField.AddLocalizationText("Full Name"); var genderField = new PicklistAttributeMetadata(); genderField.SetName("gender"); genderField.OptionSet = new OptionSetMetadata(new OptionMetadataCollection(new List <OptionMetadata> { new OptionMetadata("Male".AsLabel(), 0), new OptionMetadata("Female".AsLabel(), 1), new OptionMetadata("Div".AsLabel(), 2) })); var startField = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime); startField.SetName("startdate"); var endField = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime); endField.SetName("enddate"); _contactMetadata = new[] { fullNameField, genderField, startField, endField }.Compile("contact"); }
private AttributeMetadata pickListFieldCreation(string[] row) { PicklistAttributeMetadata attrMetadata = new PicklistAttributeMetadata(Utils.addOrgPrefix(row[ExcelColumsDefinition.SCHEMANAMEEXCELCOL], organizationPrefix, currentOperationCreate)); generalFieldCreation(row, attrMetadata); int parseResult; attrMetadata.DefaultFormValue = int.TryParse(row[ExcelColumsDefinition.PICKLISTDEFAULTVALUE], out parseResult) ? parseResult : (int?)null; bool globalOption; globalOption = Boolean.TryParse(row[ExcelColumsDefinition.PICKLISTGLOBAL], out globalOption) ? globalOption : false; if (globalOption) { attrMetadata.OptionSet = new OptionSetMetadata(); attrMetadata.OptionSet.IsGlobal = true; IEnumerable <OptionSetMetadataBase> selectdeoption = optionSetData.Where(x => x.Name == row[ExcelColumsDefinition.PICKLISTGLOBALNAME]); attrMetadata.OptionSet.Name = selectdeoption.Count() > 0 ? selectdeoption.First().Name : null; } else { attrMetadata.OptionSet = new OptionSetMetadata(); attrMetadata.OptionSet.IsGlobal = false; } return(attrMetadata); }
public void Can_get_option_set_formatted_value() { var metadata = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata { Options = { new OptionMetadata { Value = 111, Label = new Label { UserLocalizedLabel = new LocalizedLabel("Cancel", 1033) } }, new OptionMetadata { Value = 123, Label = new Label { UserLocalizedLabel = new LocalizedLabel("Release", 1033) } } } } }; var test = new TestHelper(); test.Service.Execute(Arg.Is <OrganizationRequest>(req => req is RetrieveAttributeRequest)) .Returns(ci => { var request = ci.ArgAt <RetrieveAttributeRequest>(0); Assert.Equal("entity", request.EntityLogicalName); Assert.Equal("xts_optionsetvalue", request.LogicalName); return(new RetrieveAttributeResponse { ["AttributeMetadata"] = metadata }); }); var target = new Entity("entity"); var current = new Entity("entity") { ["xts_optionsetvalue"] = new OptionSetValue(123) }; var context = Substitute.For <ITransactionContextBase>(); context.Service.Returns(test.Service); var accessor = new FormattedValueCurrentAccessor <Entity>(target, current, context); Assert.Equal("Release", accessor.GetFormattedValue("xts_optionsetvalue")); Assert.Equal("Release", target.GetFormattedValue("xts_optionsetvalue")); test.Service.Received(1).Execute(Arg.Any <OrganizationRequest>()); // Retrieve again, should not get from server again. Assert.Equal("Release", accessor.GetFormattedValue("xts_optionsetvalue")); test.Service.Received(1).Execute(Arg.Any <OrganizationRequest>()); }
private object CopyValueInternal(PicklistAttributeMetadata oldAttribute, BooleanAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping) { var copy = ((OptionSetValue)value).Value.ToString(); string mappedValue; copy = migrationMapping.TryGetValue(copy, out mappedValue) ? mappedValue : copy; return(GetBooleanValue(value, copy)); }
private AttributeMetadata CloneAttributes(PicklistAttributeMetadata att) { return new PicklistAttributeMetadata { FormulaDefinition = att.FormulaDefinition, DefaultFormValue = att.DefaultFormValue, OptionSet = att.OptionSet }; }
public void GetPicklistOptionCountTest_Test() { //ARRANGE - set up everything our test needs //first - set up a mock service to act like the CRM organization service var serviceMock = new Mock<IOrganizationService>(); IOrganizationService service = serviceMock.Object; PicklistAttributeMetadata retrievedPicklistAttributeMetadata = new PicklistAttributeMetadata(); OptionMetadata femaleOption = new OptionMetadata(new Label("Female", 1033), 43); femaleOption.Label.UserLocalizedLabel = new LocalizedLabel("Female", 1033); femaleOption.Label.UserLocalizedLabel.Label = "Female"; OptionMetadata maleOption = new OptionMetadata(new Label("Male", 1033), 400); maleOption.Label.UserLocalizedLabel = new LocalizedLabel("Male", 400); maleOption.Label.UserLocalizedLabel.Label = "Male"; OptionSetMetadata genderOptionSet = new OptionSetMetadata { Name = "gendercode", DisplayName = new Label("Gender", 1033), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { femaleOption, maleOption } }; retrievedPicklistAttributeMetadata.OptionSet = genderOptionSet; RetrieveAttributeResponseWrapper picklistWrapper = new RetrieveAttributeResponseWrapper(new RetrieveAttributeResponse()); picklistWrapper.AttributeMetadata = retrievedPicklistAttributeMetadata; serviceMock.Setup(t => t.Execute(It.Is<RetrieveAttributeRequest>(r => r.LogicalName == "gendercode"))).Returns(picklistWrapper); //ACT int returnedCount = Sample03.GetPicklistOptionCount("ANYENTITYMATCHES", "gendercode", service); //ASSERT Assert.AreEqual(2, returnedCount); }
public void CreateOrUpdatePicklistAttribute(string schemaName, string displayName, string description, bool isRequired, bool audit, bool searchable, string recordType, IEnumerable<KeyValuePair<int, string>> options) { lock (LockObject) { var optionSet = new OptionSetMetadata { OptionSetType = OptionSetType.Picklist, IsGlobal = false }; optionSet.Options.AddRange(options.Select(o => new OptionMetadata(new Label(o.Value, 1033), o.Key))); PicklistAttributeMetadata metadata; var exists = FieldExists(schemaName, recordType); if (exists) metadata = (PicklistAttributeMetadata) GetFieldMetadata(schemaName, recordType); else metadata = new PicklistAttributeMetadata(); SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable); metadata.OptionSet = optionSet; CreateOrUpdateAttribute(schemaName, recordType, metadata); } }
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; }
private object CopyValueInternal(AttributeMetadata oldAttribute, PicklistAttributeMetadata newAttribute, object value) { CopyValueInternal((object)oldAttribute, newAttribute, value); return null; }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a publisher /// Create a new solution, "Primary" /// Create a Global Option Set in solution "Primary" /// Export the "Primary" solution, setting it to Protected /// Delete the option set and solution /// Import the "Primary" solution, creating a managed solution in CRM. /// Create a new solution, "Secondary" /// Create an attribute in "Secondary" that references the Global Option Set /// </summary> public void CreateRequiredRecords() { //Create the publisher that will "own" the two solutions //<snippetGetSolutionDependencies6> Publisher publisher = new Publisher { UniqueName = "examplepublisher", FriendlyName = "An Example Publisher", Description = "This is an example publisher", CustomizationPrefix = _prefix }; _publisherId = _serviceProxy.Create(publisher); //</snippetGetSolutionDependencies6> //Create the primary solution - note that we are not creating it //as a managed solution as that can only be done when exporting the solution. //<snippetGetSolutionDependencies2> Solution primarySolution = new Solution { Version = "1.0", FriendlyName = "Primary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = _primarySolutionName }; _primarySolutionId = _serviceProxy.Create(primarySolution); //</snippetGetSolutionDependencies2> //Now, create the Global Option Set and associate it to the solution. //<snippetGetSolutionDependencies3> OptionSetMetadata optionSetMetadata = new OptionSetMetadata() { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Option 1", _languageCode), 1), new OptionMetadata(new Label("Option 2", _languageCode), 2) } }; CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = optionSetMetadata }; createOptionSetRequest.SolutionUniqueName = _primarySolutionName; _serviceProxy.Execute(createOptionSetRequest); //</snippetGetSolutionDependencies3> //Export the solution as managed so that we can later import it. //<snippetGetSolutionDependencies4> ExportSolutionRequest exportRequest = new ExportSolutionRequest { Managed = true, SolutionName = _primarySolutionName }; ExportSolutionResponse exportResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportRequest); //</snippetGetSolutionDependencies4> // Delete the option set previous created, so it can be imported under the // managed solution. //<snippetGetSolutionDependencies5> DeleteOptionSetRequest deleteOptionSetRequest = new DeleteOptionSetRequest { Name = _globalOptionSetName }; _serviceProxy.Execute(deleteOptionSetRequest); //</snippetGetSolutionDependencies5> // Delete the previous primary solution, so it can be imported as managed. _serviceProxy.Delete(Solution.EntityLogicalName, _primarySolutionId); _primarySolutionId = Guid.Empty; // Re-import the solution as managed. ImportSolutionRequest importRequest = new ImportSolutionRequest { CustomizationFile = exportResponse.ExportSolutionFile }; _serviceProxy.Execute(importRequest); // Retrieve the solution from CRM in order to get the new id. QueryByAttribute primarySolutionQuery = new QueryByAttribute { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet("solutionid"), Attributes = { "uniquename" }, Values = { _primarySolutionName } }; _primarySolutionId = _serviceProxy.RetrieveMultiple(primarySolutionQuery).Entities .Cast<Solution>().FirstOrDefault().SolutionId.GetValueOrDefault(); // Create a secondary solution. Solution secondarySolution = new Solution { Version = "1.0", FriendlyName = "Secondary Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId), UniqueName = "SecondarySolution" }; _secondarySolutionId = _serviceProxy.Create(secondarySolution); // Create a Picklist attribute in the secondary solution linked to the option set in the // primary - see WorkWithOptionSets.cs for more on option sets. PicklistAttributeMetadata picklistMetadata = new PicklistAttributeMetadata { SchemaName = _picklistName, LogicalName = _picklistName, DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = picklistMetadata }; createAttributeRequest["SolutionUniqueName"] = secondarySolution.UniqueName; _serviceProxy.Execute(createAttributeRequest); }
/// <summary> /// DOESN'T UPDATE THE PICKLIST ITSELF - CALL THE UPDATEPICKLISTOPTIONS OR CREATEORUPDATESHAREDOPTIONSET METHOD /// </summary> public void CreateOrUpdatePicklistAttribute(string schemaName, string displayName, string description, bool isRequired, bool audit, bool searchable, string recordType, string sharedOptionSetName) { lock (LockObject) { PicklistAttributeMetadata metadata; var exists = FieldExists(schemaName, recordType); if (exists) metadata = (PicklistAttributeMetadata) GetFieldMetadata(schemaName, recordType); else metadata = new PicklistAttributeMetadata(); SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable); metadata.OptionSet = new OptionSetMetadata {Name = sharedOptionSetName, IsGlobal = true}; CreateOrUpdateAttribute(schemaName, recordType, metadata); } }
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; }
private PicklistAttributeMetadata CreateGlobalOptionSetAttributeMetadata(AttributeTemplate attributeTemplate) { var picklistAttributeMetadata = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata { IsGlobal = true, Name = attributeTemplate.GlobalOptionSetListLogicalName } }; return picklistAttributeMetadata; }
public PicklistAttributeMetadataInfo(PicklistAttributeMetadata amd) : base(amd) { this.amd = amd; }
private PicklistAttributeMetadata CreateOptionSetAttributeMetadata(AttributeTemplate attributeTemplate) { var optionMetadataCollection = GetOptionMetadataCollection(attributeTemplate); var picklistAttributeMetadata = new PicklistAttributeMetadata { OptionSet = new OptionSetMetadata(optionMetadataCollection) }; picklistAttributeMetadata.OptionSet.IsGlobal = false; return picklistAttributeMetadata; }