private CodeTypeDeclaration GenerateEnum(EntityMetadata entityMetadata, MultiSelectPicklistAttributeMetadata metadata, IServiceProvider services, INamingService service) { var name = service.GetNameForOptionSet(entityMetadata, metadata.OptionSet, services); var type = new CodeTypeDeclaration(name) { IsEnum = true }; type.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(DataContractAttribute)))); var version = System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(INamingService).Assembly.Location).ProductVersion; type.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(GeneratedCodeAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression("CrmSvcUtil")), new CodeAttributeArgument(new CodePrimitiveExpression(version)))); foreach (var option in metadata.OptionSet.Options) { // Creates the enum member CodeMemberField value = new CodeMemberField { Name = service.GetNameForOption(metadata.OptionSet, option, services), InitExpression = new CodePrimitiveExpression(option.Value.GetValueOrDefault()) }; value.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(EnumMemberAttribute)))); type.Members.Add(value); } return(type); }
private Dictionary <int, string> GetOptionsNames(EntityReference sourceEntityReference, string attributeName, Common context) { RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = sourceEntityReference.LogicalName, LogicalName = attributeName, RetrieveAsIfPublished = false }; RetrieveAttributeResponse response = context.service.Execute(attributeRequest) as RetrieveAttributeResponse; MultiSelectPicklistAttributeMetadata attributeMetadata = response.AttributeMetadata as MultiSelectPicklistAttributeMetadata; if (attributeMetadata == null) { throw new InvalidPluginExecutionException($"Attribute {attributeName} is not an expected multi-select optionset / choices type"); } OptionMetadataCollection options = attributeMetadata.OptionSet.Options; Dictionary <int, string> optionsTable = new Dictionary <int, string>(options.Count); foreach (OptionMetadata optionMetadata in options) { optionsTable.Add(optionMetadata.Value.Value, optionMetadata.Label.UserLocalizedLabel.Label); } return(optionsTable); }
public AttributeMetadata ReturnAttributeMetadata(Attribute attribute) { try { switch (attribute.OptionSetType) { case "New Option Set": var OptionSetAttr = new MultiSelectPicklistAttributeMetadata() { SchemaName = AttrSchemaName, DisplayName = new Label(AttrFieldLabel, CultureInfo.CurrentCulture.LCID), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttrRequiredLevel), IsAuditEnabled = new BooleanManagedProperty(AttrAuditEnabled), OptionSet = GenerateOptionSetMetadata(), Description = (AttrDescription != null) ? new Label(AttrDescription, CultureInfo.CurrentCulture.LCID) : null }; return(OptionSetAttr); case "New Global Option Set": var NewGlobalOptionSetAttr = new MultiSelectPicklistAttributeMetadata() { SchemaName = AttrSchemaName, DisplayName = new Label(AttrFieldLabel, CultureInfo.CurrentCulture.LCID), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttrRequiredLevel), IsAuditEnabled = new BooleanManagedProperty(AttrAuditEnabled), Description = (AttrDescription != null) ? new Label(AttrDescription, CultureInfo.CurrentCulture.LCID) : null, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = (string.IsNullOrWhiteSpace(attribute.GlobalOSSchemaName)) ? AttrSchemaName : attribute.GlobalOSSchemaName } }; return(NewGlobalOptionSetAttr); default: var ExistGlobalOptionSetAttr = new MultiSelectPicklistAttributeMetadata() { SchemaName = AttrSchemaName, DisplayName = new Label(AttrFieldLabel, CultureInfo.CurrentCulture.LCID), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttrRequiredLevel), IsAuditEnabled = new BooleanManagedProperty(AttrAuditEnabled), Description = (AttrDescription != null) ? new Label(AttrDescription, CultureInfo.CurrentCulture.LCID) : null, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = attribute.ExistingGlobalOSSchemaName.ToLower() } }; return(ExistGlobalOptionSetAttr); } } catch (Exception ex) { throw new ArgumentException($"{attribute.FieldSchemaName}: {ex.Message}"); } }
/// <summary> /// Create Picklist Field /// </summary> /// <param name="SchemaName">Schema name of Attribute, as well as the optionset</param> /// <param name="DisplayName">Display name of Attribute.</param> /// <param name="addedAttributes">Pass by reference, your Entity List.</param> /// <param name="multi">Pass "multi" for multiple picklist</param> static void createFieldPicklist(string SchemaName, string DisplayName, ref List <AttributeMetadata> addedAttributes, string multi = "single") { if ("multi" == multi) { var CreatedMultiSelectPicklistAttributeMetadata = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " multi check List", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Name = SchemaName + "_local", Options = { new OptionMetadata(new Label("-", _languageCode), null), } } }; // Add and return early. addedAttributes.Add(CreatedMultiSelectPicklistAttributeMetadata); } else { var CreatedPicklistAttributeMetadata = new PicklistAttributeMetadata() { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " single checklist", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = false, Name = SchemaName + "_local", Options = { new OptionMetadata(new Label("-", _languageCode), null), } } }; addedAttributes.Add(CreatedPicklistAttributeMetadata); } }
public static void When_using_proxy_types_assembly_multi_select_option_set_metadata_is_inferred_from_injected_metadata_as_a_fallback() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var record1 = new Entity("contact") { Id = Guid.NewGuid(), ["new_injectedmultiselectoptionset"] = new OptionSetValueCollection( new[] { new OptionSetValue(100001), new OptionSetValue(100002) }) }; var record2 = new Entity("contact") { Id = Guid.NewGuid(), ["new_injectedmultiselectoptionset"] = new OptionSetValueCollection( new[] { new OptionSetValue(100002), new OptionSetValue(100003) }) }; fakedContext.Initialize(new List <Entity>() { record1, record2 }); var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; var injectedAttribute = new MultiSelectPicklistAttributeMetadata() { LogicalName = "new_injectedmultiselectoptionset" }; entityMetadata.SetAttribute(injectedAttribute); fakedContext.InitializeMetadata(entityMetadata); var guid = Guid.NewGuid(); //Empty context (no Initialize), but we should be able to query any typed entity without an entity not found exception var service = fakedContext.GetOrganizationService(); var contacts = service.RetrieveMultiple(new QueryExpression(Contact.EntityLogicalName) { Criteria = new FilterExpression() { Conditions = { new ConditionExpression("new_injectedmultiselectoptionset", ConditionOperator.In, new[] { 100002, 100003 }) } } }); Assert.True(contacts.Entities.Count == 1); }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate _productVersion = Version.Parse(((RetrieveVersionResponse)service.Execute(new RetrieveVersionRequest())).Version); #region How to create attributes // Create storage for new attributes being created addedAttributes = new List <AttributeMetadata>(); // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_Boolean", LogicalName = "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 var dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_Datetime", LogicalName = "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 var decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_Decimal", LogicalName = "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 var integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_Integer", LogicalName = "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 var memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_Memo", LogicalName = "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 var moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_Money", LogicalName = "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 var pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_Picklist", LogicalName = "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 var stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_String", LogicalName = "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); //Multi-select attribute requires version 9.0 or higher. if (_productVersion > new Version("9.0")) { // Create a multi-select optionset var multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_MultiSelectOptionSet", LogicalName = "new_multiselectoptionset", DisplayName = new Label("Multi-Select OptionSet", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Multi-Select OptionSet description", _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option", _languageCode), null), new OptionMetadata(new Label("Second Option", _languageCode), null), new OptionMetadata(new Label("Third Option", _languageCode), null) } } }; // Add to list addedAttributes.Add(multiSelectOptionSetAttribute); } // 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. var createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. service.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } #endregion How to create attributes #region How to insert status // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. var 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)service.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created status named '{0}' with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); #endregion How to insert status #region How to retrieve attribute // Create the request var attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); #endregion How to retrieve attribute #region How to update attribute // Modify the retrieved attribute var retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest var updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request service.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); #endregion How to update attribute #region How to update state value // Modify the state value label from Active to Open. // Create the request. var updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. service.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); #endregion How to update state value #region How to insert a new option item in a local option set // Create a request. var insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)service.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); #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 // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse 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(); // 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. var 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 service.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. service.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// Create Picklist Field /// </summary> /// <param name="SchemaName">Schema name of Attribute.</param> /// <param name="DisplayName">Display name of Attribute.</param> /// <param name="pickListArray">String Array for options set.</param> /// <param name="addedAttributes">Pass by reference, your Entity List.</param> /// <param name="multi">Pass "multi" for multiple picklist</param> static void createFieldPicklist(string SchemaName, string DisplayName, string[] pickListArray, ref List <AttributeMetadata> addedAttributes, string multi = "single") { // Option attribute meta mapper IList <OptionMetadata> options = new List <OptionMetadata>(); foreach (string singleTupleOptionMetadata in pickListArray) { options.Add(new OptionMetadata(new Label(singleTupleOptionMetadata, 1033), null)); } OptionSetMetadata optionset = new OptionSetMetadata(new OptionMetadataCollection(options)); optionset.IsGlobal = true; optionset.OptionSetType = OptionSetType.Picklist; optionset.DisplayName = new Label(DisplayName + " Global Picklist *", 1033); optionset.Description = new Label("MSVProperties - " + DisplayName + " picklist option set", 1033); optionset.Name = "new_msvproperties_" + SchemaName + "_option_global"; try { CrmServiceClient service = SampleHelpers.Connect("Connect"); CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = optionset }; CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)service.Execute(createOptionSetRequest); } catch (Exception ex) { //Supress Error. } if ("multi" == multi) { var CreatedMultiSelectPicklistAttributeMetadata = new MultiSelectPicklistAttributeMetadata("new_" + SchemaName) { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " multi check List", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = optionset.Name } }; // Add and return early. addedAttributes.Add(CreatedMultiSelectPicklistAttributeMetadata); } else { var CreatedPicklistAttributeMetadata = new PicklistAttributeMetadata("new_" + SchemaName) { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + " *", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM " + DisplayName + " single checklist", 1033), IsValidForForm = true, IsValidForGrid = true, OptionSet = new OptionSetMetadata { IsGlobal = true, Name = optionset.Name } }; addedAttributes.Add(CreatedPicklistAttributeMetadata); } }
private AttributeMetadata CreateOptionsetAttribute(ExcelWorksheet sheet, int rowIndex, int startCell, bool isMultiSelect, string displayName, string schemaName, string entity, string description, OptionSetMetadata eomd) { var isGlobal = sheet.GetValue <string>(rowIndex, startCell + 1) == "Yes"; var omd = new OptionSetMetadata { IsGlobal = isGlobal, DisplayName = new Label(displayName, settings.LanguageCode), OptionSetType = OptionSetType.Picklist, Name = schemaName//.ToLower() }; if (!string.IsNullOrEmpty(description)) { omd.Description = new Label(description, settings.LanguageCode); } string optionsString = sheet.GetValue <string>(rowIndex, startCell); if (optionsString.Length == 0) { throw new Exception("OptionSet values cannot be null"); } var containsValue = optionsString.IndexOf(':') > 0; if (containsValue) { foreach (var optionRow in optionsString.Split('\n')) { var parts = optionRow.Split(':'); if (parts.Length != 2) { continue; } var index = int.Parse(parts[0]); var om = new OptionMetadata(new Label(parts[1], settings.LanguageCode), index); if (parts.Length > 2) { om.Description = new Label(parts[2], settings.LanguageCode); } if (majorVersion >= 9) { if (parts.Length > 3) { om.ExternalValue = parts[3]; } } omd.Options.Add(om); } if (settings.AddOptionSetSuffix && !omd.Name.ToLower().EndsWith("code")) { omd.Name = $"{omd.Name}Code"; } } else { omd.IsGlobal = true; omd.Name = optionsString.ToLower(); } if (isGlobal) { if (containsValue) { if (eomd == null) { service.Execute(new CreateOptionSetRequest { OptionSet = omd, SolutionUniqueName = settings.Solution.UniqueName }); } else { service.Execute(new UpdateOptionSetRequest { OptionSet = omd, SolutionUniqueName = settings.Solution.UniqueName, MergeLabels = true }); ApplyOptionsUpdate(eomd, omd); } } else { omd.Name = optionsString.ToLower(); if (settings.AddOptionSetSuffix && !omd.Name.EndsWith("code")) { omd.Name = $"{omd.Name}code"; } } } else { ApplyOptionsUpdate(eomd, omd, entity, schemaName); } if (isMultiSelect) { var amd = new MultiSelectPicklistAttributeMetadata { OptionSet = omd }; if (!string.IsNullOrEmpty(sheet.GetValue <string>(rowIndex, startCell + 2))) { amd.DefaultFormValue = sheet.GetValue <int>(rowIndex, startCell + 2); } return(amd); } else { var omd2 = new OptionSetMetadata(); if (isGlobal) { omd2.IsGlobal = true; omd2.DisplayName = omd.DisplayName; omd2.OptionSetType = omd.OptionSetType; omd2.Name = omd.Name.ToLower(); omd2.Description = omd.Description; } else { omd2 = omd; } var amd = new PicklistAttributeMetadata { OptionSet = omd2 }; if (!string.IsNullOrEmpty(sheet.GetValue <string>(rowIndex, startCell + 2))) { int defaultValue = sheet.GetValue <int>(rowIndex, startCell + 2); if (defaultValue != -1) { if (omd.Options.Any(o => o.Value == defaultValue)) { amd.DefaultFormValue = defaultValue; } else { defaultValue = int.Parse($"{settings.Solution.OptionSetPrefix}{defaultValue.ToString().PadLeft(4, '0')}"); if (omd.Options.Any(o => o.Value == defaultValue)) { amd.DefaultFormValue = defaultValue; } } } } return(amd); } }
public static void CreateQuestionMapping(OrganizationServiceProxy service, string name, string type, string values, string desc) { var nameLength = name.Length > 40 ? 40 : name.Length; var uniqueName = name.Substring(0, nameLength); uniqueName = uniqueName.Replace("(", "").Replace(")", "").Replace("(", "").Replace("/", "") .Replace("-", "").Replace(";", "").Replace("?", "").Replace("&", "").Replace(",", "").Replace(":", "").Replace(" ", "").ToLower(); var displaynameLength = name.Length > 50 ? 50 : name.Length; var DisplayName = name.Substring(0, displaynameLength); if (type == "Option Set") { var _values = values.Split(','); // Define the option set to create. OptionSetMetadata setupOptionSetMetadata = new OptionSetMetadata() { // The name will be used to uniquely identify the option set. // Normally you should generate this identifier using the publisher's // prefix and double-check that the name is not in use. Name = publisherPrefix + uniqueName, DisplayName = new Label(DisplayName, _languageCode), Description = new Label(desc, _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, // Define the list of options that populate the option set // The order here determines the order shown in the option set. Options = { // Options accepts any number of OptionMetadata instances, which // are simply pairs of Labels and integer values. new OptionMetadata(new Label(_values[0], _languageCode), null), new OptionMetadata(new Label(_values[1], _languageCode), null), } }; // Wrap the OptionSetMetadata in the appropriate request. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { OptionSet = setupOptionSetMetadata }; // Pass the execute statement to the CRM service. //service.Execute(createOptionSetRequest); Console.WriteLine(DisplayName + " Option Set created"); service.Execute(createOptionSetRequest); } else if (type.StartsWith("Mutli")) { var _values = values.Split(','); var outDoorActivitiesAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = publisherPrefix + uniqueName, LogicalName = publisherPrefix + uniqueName, DisplayName = new Label(DisplayName, _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label(desc, _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label(_values[0], _languageCode), 1), new OptionMetadata(new Label(_values[1], _languageCode), 2) } } }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = outDoorActivitiesAttribute }; service.Execute(createAttributeRequest); Console.WriteLine(DisplayName + " Option Set created"); } else if (type == "Boolean") { var att = CreateBooleanAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Date & Time") { var att = CreateDateTimeAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Multi Text") { var att = CreateMemoAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, 4000); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Text") { var att = CreateStringAttribute(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, 500); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } else if (type == "Whole Integer") { var att = CreateIntegerAttributeMetadata(uniqueName, DisplayName, AttributeRequiredLevel.None, desc, -1000000, 1000000); CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "blu_questionmapping", Attribute = att }; service.Execute(createAttributeRequest); } }
public MultiSelectPicklistAttributeMetadataInfo(MultiSelectPicklistAttributeMetadata amd) : base(amd) { this.amd = amd; }
/// <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(); _productVersion = Version.Parse(((RetrieveVersionResponse)_serviceProxy.Execute(new RetrieveVersionRequest())).Version); //<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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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", LogicalName = "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); //Multi-select attribute requires version 9.0 or higher. if (_productVersion > new Version("9.0")) { // Create a multi-select optionset MultiSelectPicklistAttributeMetadata multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_MultiSelectOptionSet", LogicalName = "new_multiselectoptionset", DisplayName = new Label("Multi-Select OptionSet", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Multi-Select OptionSet description", _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option", _languageCode), null), new OptionMetadata(new Label("Second Option", _languageCode), null), new OptionMetadata(new Label("Third Option", _languageCode), null) } } }; // Add to list addedAttributes.Add(multiSelectOptionSetAttribute); } // 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 status named '{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 ApplyNewValue(Entity dynamicsEntity, AttributeMetadata entityMetadata, object entityDetail, string key, string lookUpKey = null) { switch (entityMetadata.AttributeType) { case AttributeTypeCode.DateTime: DateTime dateField; if (DateTime.TryParse(entityDetail.ToString(), out dateField)) { dynamicsEntity.Attributes[key] = dateField; } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to datetime!"); } break; case AttributeTypeCode.Picklist: PicklistAttributeMetadata picklistAttributeMetadata = entityMetadata as PicklistAttributeMetadata; if (picklistAttributeMetadata != null) { var item = picklistAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Label.LocalizedLabels.FirstOrDefault().Label.ToLower() == entityDetail.ToString().ToLower()); if (item != null) { dynamicsEntity.Attributes[key] = new OptionSetValue(item.Value ?? -1); } else { Logger.LogWarning($"Wasn't able to find lookup field {entityDetail} within Picklist options {key}."); Logger.LogWarning("Adding new field to Option Set"); int maxVal = picklistAttributeMetadata.OptionSet.Options.Max(o => o.Value) ?? 0; int?value = AddOptionSetItem(dynamicsEntity.LogicalName, key, entityDetail, maxVal + 10); if (value != null) { dynamicsEntity.Attributes[key] = new OptionSetValue(value ?? -1); } } } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to Option Set Value!"); } break; case AttributeTypeCode.Virtual: MultiSelectPicklistAttributeMetadata multiPicklistAttributeMetadata = entityMetadata as MultiSelectPicklistAttributeMetadata; if (multiPicklistAttributeMetadata != null) { IEnumerable <string> labels = entityDetail.ToString().Split(';'); var items = multiPicklistAttributeMetadata.OptionSet.Options.Where(o => labels.Contains(o.Label.LocalizedLabels.FirstOrDefault().Label.ToString())); if (items != null) { dynamicsEntity.Attributes[key] = new OptionSetValueCollection(items.Select(i => new OptionSetValue(i.Value ?? -1)).ToList()); } else { Logger.LogWarning($"Wasn't able to find lookup field {entityDetail.ToString()} within Picklist options {key}"); } } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to Multi Select Picklist!"); } break; case AttributeTypeCode.Lookup: var refKey = ((LookupAttributeMetadata)entityMetadata).Targets.FirstOrDefault(); var entities = GetEntityInstances(organizationProxy, refKey, new Dictionary <string, object> { { lookUpKey, entityDetail } }); if (entities != null && entities.Any()) { var entity = entities.First(); dynamicsEntity.Attributes[key] = new EntityReference(entity.LogicalName, entity.Id); } break; case AttributeTypeCode.Money: decimal money; if (decimal.TryParse(entityDetail.ToString(), out money)) { dynamicsEntity.Attributes[key] = new Money(money); } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to decimal!"); } break; case AttributeTypeCode.Double: double dval; if (double.TryParse(entityDetail.ToString(), out dval)) { dynamicsEntity.Attributes[key] = dval; } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to double!"); } break; case AttributeTypeCode.Decimal: decimal decval; if (decimal.TryParse(entityDetail.ToString(), out decval)) { dynamicsEntity.Attributes[key] = decval; } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to decimal!"); } break; case AttributeTypeCode.Memo: case AttributeTypeCode.String: dynamicsEntity.Attributes[key] = entityDetail.ToString(); break; case AttributeTypeCode.Integer: int ival; if (int.TryParse(entityDetail.ToString(), out ival)) { dynamicsEntity.Attributes[key] = ival; } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to Integer!"); } break; case AttributeTypeCode.Boolean: bool bval; if (Boolean.TryParse(entityDetail.ToString(), out bval)) { dynamicsEntity.Attributes[key] = bval; } else { Logger.LogWarning($"Wasn't able to convert property {key} with data {entityDetail} to Boolean!"); } break; case AttributeTypeCode.Customer: refKey = ((LookupAttributeMetadata)entityMetadata).Targets.FirstOrDefault(); entities = GetEntityInstances(organizationProxy, refKey, new Dictionary <string, object> { { lookUpKey, entityDetail } }); if (entities != null && entities.Any()) { var entity = entities.First(); dynamicsEntity.Attributes[key] = new EntityReference(entity.LogicalName, entity.Id); } break; case AttributeTypeCode.Status: case AttributeTypeCode.State: int istate; if (int.TryParse(entityDetail.ToString(), out istate)) { dynamicsEntity.Attributes[key] = new OptionSetValue(istate); } else { var option = ((EnumAttributeMetadata)entityMetadata).OptionSet.Options.Last(o => o.Label.LocalizedLabels.First().Label.ToLower() == entityDetail.ToString().ToLower()); if (option != null) { dynamicsEntity.Attributes[key] = new OptionSetValue(option.Value ?? 1); } } break; default: Logger.LogError($"Not added Attribute {key} of type {entityMetadata.AttributeType} with value {entityDetail} to the entity during creation!"); break; } }