/// <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; } }
/// <summary> /// Procedure: InsertGlobalOptionSet /// Handles: Inserts Values to existing optionset /// Created By: Steve Weinberger /// Created Date: 06/07/2016 /// Changes By: /// Changes Date: /// Changes Made: /// </summary> public void InsertGlobalOptionSet(IOrganizationService service, string solutionName, string schema, string label, int lang, string[] optionLabels) { string globalOptionSetName = schema; int _insertedOptionValue; OptionMetadataCollection options = new OptionMetadataCollection(); foreach (string o in optionLabels) { InsertOptionValueRequest req = new InsertOptionValueRequest() { SolutionUniqueName = solutionName, OptionSetName = globalOptionSetName, Label = new Label(o, lang) }; //InsertOptionValueResponse res = (InsertOptionValueResponse)service.Execute(req); _insertedOptionValue = ((InsertOptionValueResponse)service.Execute(req)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", req.Label.LocalizedLabels[0].Label, _insertedOptionValue); } //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", globalOptionSetName) }; service.Execute(pxReq2); Console.WriteLine("Global OptionSet inserted: {0}", schema); }
private int InsertOptionSetValue(string label, int?value) { var request = new InsertOptionValueRequest { Label = new Label(label, LanguageCode) }; if (value.HasValue) { request.Value = value; } if (isGlobalOptionSet) { request.OptionSetName = optionSetName; } else { request.EntityLogicalName = EntityLogicalName; request.AttributeLogicalName = AttributeLogicalName; } Log.Debug("Adding option '{label}' ({request})", label, Newtonsoft.Json.JsonConvert.SerializeObject(request)); var response = (InsertOptionValueResponse)CrmServiceClient.Execute(request); return(response.NewOptionValue); }
/// <summary> /// Processes the global option sets /// </summary> /// <param name="dictionary">The <see cref="String"/> array that contains the global option set values.</param> /// <param name="key">The option set name to be created or updated.</param> private void ProcessGlobalPicklists(string[] dictionary, string key) { if (dictionary.Length > 0) { try { RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = key }; RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)this.CrmAdapter.OrganizationService.Execute(retrieveOptionSetRequest); OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); foreach (string label in dictionary) { var option = optionList.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label == label); if (option == null) { InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = key, Label = new Label(label, retrievedOptionSetMetadata.DisplayName.UserLocalizedLabel.LanguageCode) }; this.CrmAdapter.OrganizationService.Execute(insertOptionValueRequest); } } } catch (FaultException ex) { throw new AdapterException(ex.Message, ex) { ExceptionId = ErrorCodes.CrmPlatformException }; } } }
public void addOptionCreateRequest(string[] row, List <CrmOperation> crmOp) { InsertOptionValueRequest insertOptionValueRequest; int result; if (optionMetadata.optionData.IsGlobal.Value) { insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = optionMetadata.optionData.Name, Label = new Label(row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL], languageCode), Value = int.TryParse(row[ExcelColumsDefinition.OPTIONSETVALUEEXCELCOL], out result) ? result : (int?)null }; } else { insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = optionMetadata.parentAttribute.LogicalName, EntityLogicalName = optionMetadata.parentAttribute.EntityLogicalName, Label = new Label(row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL], languageCode), Value = int.TryParse(row[ExcelColumsDefinition.OPTIONSETVALUEEXCELCOL], out result) ? result : (int?)null }; } crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.create, CrmOperation.CrmOperationTarget.optionSet, insertOptionValueRequest, string.Format("Insert OptionSet {0}", row[ExcelColumsDefinition.OPTIONSETLABELEXCELCOL]))); }
public bool InsertOptionValue(bool globalOptionSet, string attributeName, string entityName, string optionText, int optionValue, int languageCode) { if (globalOptionSet) { InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = attributeName, Value = optionValue, Label = new Label(optionText, languageCode) }; int insertOptionValue = ((InsertOptionValueResponse)service.Execute(insertOptionValueRequest)).NewOptionValue; } else { // Create a request. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = attributeName, EntityLogicalName = entityName, Value = optionValue, Label = new Label(optionText, languageCode) }; int insertOptionValue = ((InsertOptionValueResponse)service.Execute(insertOptionValueRequest)).NewOptionValue; } return(true); }
public void When_calling_insert_option_set_value_for_local_optionset_optionmetadata_contains_it() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { EntityLogicalName = Account.EntityLogicalName, AttributeLogicalName = "new_custom", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.DoesNotThrow(() => service.Execute(req)); //Check the optionsetmetadata was updated var key = string.Format("{0}#{1}", req.EntityLogicalName, req.AttributeLogicalName); Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key)); var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.NotEqual(null, option); Assert.Equal("Yeah! This is a fake label!", option.Label.LocalizedLabels[0].Label); }
public void Should_also_update_entity_metadata_when_not_using_global_option_set() { var label = "dummy label"; var attributeName = "statuscode"; var ctx = new XrmFakedContext(); var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata() { LogicalName = attributeName }; entityMetadata.SetAttributeCollection(new List <AttributeMetadata>() { enumAttribute }); ctx.InitializeMetadata(entityMetadata); var req = new InsertOptionValueRequest() { EntityLogicalName = Contact.EntityLogicalName, AttributeLogicalName = attributeName, Label = new Label(label, 0) }; var service = ctx.GetOrganizationService(); service.Execute(req); //Check the optionsetmetadata was updated var key = $"{Contact.EntityLogicalName}#{attributeName}"; Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key)); var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.Equal(label, option.Label.LocalizedLabels[0].Label); // Get a list of Option Set values for the Status Reason fields from its metadata RetrieveAttributeRequest attReq = new RetrieveAttributeRequest { EntityLogicalName = "contact", LogicalName = "statuscode", RetrieveAsIfPublished = true }; RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq); StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata; Assert.NotNull(statusAttributeMetadata.OptionSet); Assert.NotNull(statusAttributeMetadata.OptionSet.Options); Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Count(o => o.Label.LocalizedLabels[0].Label == label)); }
protected static void addOptionToCustomEntityOptionSet(CrmServiceClient service) { var insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = _customAttributeSchemaName.ToLower(), EntityLogicalName = _customEntitySchemaName.ToLower(), Label = new Label("Fifth Option", _languageCode) }; service.Execute(insertOptionValueRequest); }
public void When_calling_insert_option_set_value_without_optionsetname_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws<Exception>(() => service.Execute(req)); }
public void When_calling_insert_option_set_value_without_optionsetname_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws <Exception>(() => service.Execute(req)); }
/// <summary> /// Get a request to add to the batch. /// </summary> /// <param name="option">The option for the request.</param> /// <param name="operation">The operation we are doing.</param> /// <returns>The request created.</returns> private static OrganizationRequest GetRequest(EntityItem option, Operation operation) { OrganizationRequest request = null; switch (operation) { case Operation.Insert: request = new InsertOptionValueRequest { OptionSetName = option.Parent.GlobalName, EntityLogicalName = option.Parent.Global ? null : option.Parent.Parent.LogicalName, AttributeLogicalName = option.Parent.Global ? null : option.Parent.LogicalName, Value = option.Value, Label = option.Label, Description = option.Description }; break; case Operation.Update: request = new UpdateOptionValueRequest { OptionSetName = option.Parent.GlobalName, EntityLogicalName = option.Parent.Global ? null : option.Parent.Parent.LogicalName, AttributeLogicalName = option.Parent.Global ? null : option.Parent.LogicalName, Value = option.Value, Label = option.Label, Description = option.Description }; break; case Operation.Delete: request = new DeleteOptionValueRequest { OptionSetName = option.GlobalName, EntityLogicalName = option.Global ? null : option.Parent.LogicalName, AttributeLogicalName = option.Global ? null : option.LogicalName, Value = option.Value }; break; default: break; } return(request); }
/// <summary> /// Global OptionSet의 Options 값을 Insert or Update /// </summary> /// <param name="dto"></param> /// <returns></returns> private OrganizationResponse InsertOrUpdateForOptionSetOptions(DtoOptionSet dto) { try { OrganizationResponse response = null; OptionMetadata[] options = RetrieveGlobalOptionSetOptions(dto.SchemaName); // Add a label and value to Global OptionSet foreach (var o in dto.Options) { var optionCnt = options.Where(a => a.Value == o.Value).Count(); if (optionCnt == 0) { InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = dto.SchemaName, Value = o.Value, // optional value - if ommited one will get assigned automatically Label = new Label(o.Label, _languageCode), Description = new Label(o.Description ?? string.Empty, _languageCode) }; response = _orgService.Execute(insertOptionValueRequest); // int retVal = ((InsertOptionValueResponse)_orgService.Execute(insertOptionValueRequest)).NewOptionValue; } else // (optionCnt > 0) { UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = dto.SchemaName, Value = o.Value, // optional value - if ommited one will get assigned automatically Label = new Label(o.Label, _languageCode), Description = new Label(o.Description ?? string.Empty, _languageCode) }; response = _orgService.Execute(updateOptionValueRequest); } } return(response); } catch (Exception) { throw; } }
private IEnumerable <IExtensibleDataObject> pickListOptionCreation(string[] row, PicklistAttributeMetadata attr) { List <IExtensibleDataObject> opList = new List <IExtensibleDataObject>(); int result; string optionString = row[ExcelColumsDefinition.PICKLISTREF]; if (optionString != string.Empty && optionString != ExcelDataAccess.voidOptionSetString) { foreach (string optionLine in optionString.Split(ExcelDataAccess.optionSetSeparator)) { InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest(); string[] optValueName = optionLine.Split(new Char[1] { ExcelDataAccess.optionSetNumberSeparator }, 2); if (optValueName.Count() == 2) { if (attr.OptionSet.IsGlobal != null && attr.OptionSet.IsGlobal.Value) { insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = attr.OptionSet.Name, Label = new Label(optValueName[1], languageCode), Value = int.TryParse(optValueName[0], out result) ? result : (int?)null }; } else { insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = attr.SchemaName.ToLower(), EntityLogicalName = entityLocialName, Label = new Label(optValueName[1], languageCode), Value = int.TryParse(optValueName[0], out result) ? result : (int?)null }; } opList.Add(insertOptionValueRequest); } } } return(opList); }
private int?AddOptionSetItem(string logicalName, string key, object entityDetail, int optionValue) { try { var insertOptionValueRequest = new InsertOptionValueRequest { EntityLogicalName = logicalName, AttributeLogicalName = key, Label = new Label(entityDetail.ToString(), 1033), Value = optionValue }; return(((InsertOptionValueResponse)organizationProxy.Execute(insertOptionValueRequest)).NewOptionValue); } catch (Exception ex) { return(null); } }
private int?AddOptionSetItem(string logicalName, string key, object entityDetail, int optionValue) { try { var insertOptionValueRequest = new InsertOptionValueRequest { EntityLogicalName = logicalName, AttributeLogicalName = key, Label = new Label(entityDetail.ToString(), 1033), Value = optionValue }; return(((InsertOptionValueResponse)organizationProxy.Execute(insertOptionValueRequest)).NewOptionValue); } catch (Exception exception) { Logger.LogError("GetDynamicsEntityProperties: " + exception.Message + exception.InnerException ?? "; Inner " + exception.InnerException.Message); return(null); } }
public void When_calling_insert_option_set_value_for_global_optionset_optionmetadata_contains_it() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { OptionSetName = "GlobalOptionSet", Label = new Label("Yeah! This is a fake label!", 0) }; service.Execute(req); //Check the optionsetmetadata was updated Assert.True(ctx.OptionSetValuesMetadata.ContainsKey("GlobalOptionSet")); var option = ctx.OptionSetValuesMetadata["GlobalOptionSet"].Options.FirstOrDefault(); Assert.NotEqual(null, option); Assert.Equal("Yeah! This is a fake label!", option.Label.LocalizedLabels[0].Label); }
public void When_calling_insert_option_set_value_without_entityname_or_attributename_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { EntityLogicalName = "Not empty", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws<Exception>(() => service.Execute(req)); req = new InsertOptionValueRequest() { AttributeLogicalName = "Not empty", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws<Exception>(() => service.Execute(req)); }
public void When_calling_insert_option_set_value_without_entityname_or_attributename_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { EntityLogicalName = "Not empty", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws <Exception>(() => service.Execute(req)); req = new InsertOptionValueRequest() { AttributeLogicalName = "Not empty", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws <Exception>(() => service.Execute(req)); }
public void When_calling_insert_option_set_value_for_global_optionset_optionmetadata_contains_it() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { OptionSetName = "GlobalOptionSet", Label = new Label("Yeah! This is a fake label!", 0) }; Assert.DoesNotThrow(() => service.Execute(req)); //Check the optionsetmetadata was updated Assert.True(ctx.OptionSetValuesMetadata.ContainsKey("GlobalOptionSet")); var option = ctx.OptionSetValuesMetadata["GlobalOptionSet"].Options.FirstOrDefault(); Assert.NotEqual(null, option); Assert.Equal("Yeah! This is a fake label!", option.Label.LocalizedLabels[0].Label); }
/// <summary> /// Create a global option set. /// Set the options for that option set. /// Create a new reference to that option set on an entity. /// Update the option set's properties. /// Check the global option set for dependencies. /// Delete the option set. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkwithGlobalOptionSets1> //<snippetWorkwithGlobalOptionSets2> #region How to create global option set // Define the request object and pass to the service. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest); //</snippetWorkwithGlobalOptionSets2> #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set //<snippetWorkwithGlobalOptionSets3> // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. CreateAttributeRequest createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; _serviceProxy.Execute(createRequest); //</snippetWorkwithGlobalOptionSets3> Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set //<snippetWorkwithGlobalOptionSets4> // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; _serviceProxy.Execute(updateOptionSetRequest); //Publish the OptionSet PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq1); //</snippetWorkwithGlobalOptionSets4> Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set //<snippetWorkwithGlobalOptionSets5> // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq2); //</snippetWorkwithGlobalOptionSets5> Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name //<snippetWorkwithGlobalOptionSets6> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); //</snippetWorkwithGlobalOptionSets6> #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist //<snippetWorkwithGlobalOptionSets7> // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; _serviceProxy.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq3); //</snippetWorkwithGlobalOptionSets7> Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set //<snippetWorkwithGlobalOptionSets8> // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. OptionSetName = _globalOptionSetName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq4); //</snippetWorkwithGlobalOptionSets8> Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets //<snippetWorkwithGlobalOptionSets9> // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } //</snippetWorkwithGlobalOptionSets9> #endregion How to retrieve all global option sets //</snippetWorkwithGlobalOptionSets1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
public void Reproduce_issue_278() { string attributeName = "statuscode"; string label = "A faked label"; XrmFakedContext fakedContext = new XrmFakedContext { ProxyTypesAssembly = (Assembly.GetAssembly(typeof(Contact))) }; var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata() { LogicalName = attributeName }; entityMetadata.SetAttributeCollection(new List <AttributeMetadata>() { enumAttribute }); var req = new InsertOptionValueRequest() { EntityLogicalName = Contact.EntityLogicalName, AttributeLogicalName = attributeName, Label = new Label(label, 0) }; fakedContext.InitializeMetadata(entityMetadata); var fakedService = fakedContext.GetFakedOrganizationService(); fakedService.Execute(req); //Check the optionsetmetadata was updated var key = string.Format("{0}#{1}", Contact.EntityLogicalName, attributeName); Assert.True(fakedContext.OptionSetValuesMetadata.ContainsKey(key)); var option = fakedContext.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.Equal(label, option.Label.LocalizedLabels[0].Label); // Get a list of Option Set values for the Status Reason fields from its metadata RetrieveAttributeRequest attReq = new RetrieveAttributeRequest(); attReq.EntityLogicalName = "contact"; attReq.LogicalName = "statuscode"; attReq.RetrieveAsIfPublished = true; RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)fakedService.Execute(attReq); // Cast as StatusAttributeMetadata StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata; Assert.Equal(label, statusAttributeMetadata.OptionSet.Options.First().Label.LocalizedLabels[0].Label); //Assert.Equal(label, statusAttributeMetadata.OptionSet.Options.First().Label.UserLocalizedLabel.Label); This one is null when using the above Label constructor }
public void CreateOrUpdateSharedOptionSet(string schemaName, string displayName, IEnumerable<KeyValuePair<int, string>> options) { if (SharedOptionSetExists(schemaName)) { var optionSetMetadata = GetSharedOptionSet(schemaName); optionSetMetadata.DisplayName = new Label(displayName, 1033); var updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = optionSetMetadata }; Execute(updateOptionSetRequest); if (options.Any()) { var existingOptions = OptionSetToKeyValues(optionSetMetadata.Options); var optionSet = options.ToArray(); foreach (var option in existingOptions) { if (!optionSet.Any(o => o.Key == option.Key)) { var request = new DeleteOptionValueRequest { OptionSetName = schemaName, Value = option.Key }; Execute(request); } else if (optionSet.Any(o => o.Key == option.Key && o.Value != option.Value)) { var newValue = optionSet.Single(o => o.Key == option.Key); var request = new UpdateOptionValueRequest { OptionSetName = schemaName, Value = option.Key, Label = new Label(newValue.Value, 1033) }; Execute(request); } } foreach (var option in optionSet) { if (!existingOptions.Any(o => o.Key == option.Key)) { var request = new InsertOptionValueRequest { OptionSetName = schemaName, Value = option.Key, Label = new Label(option.Value, 1033) }; Execute(request); } } } } else { var optionSetMetadata = new OptionSetMetadata(); optionSetMetadata.Name = schemaName; optionSetMetadata.DisplayName = new Label(displayName, 1033); optionSetMetadata.IsGlobal = true; optionSetMetadata.Options.AddRange( options.Select(o => new OptionMetadata(new Label(o.Value, 1033), o.Key)).ToList()); var request = new CreateOptionSetRequest {OptionSet = optionSetMetadata}; Execute(request); } RefreshSharedOptionValues(schemaName); }
public void UpdatePicklistOptions(string fieldName, string recordType, IEnumerable<KeyValuePair<int, string>> optionSet) { if (optionSet.Any()) { var existingOptions = GetPicklistKeyValues(recordType, fieldName); var itemUpdated = false; foreach (var option in existingOptions) { if (!optionSet.Any(o => o.Key == option.Key)) { var request = new DeleteOptionValueRequest { AttributeLogicalName = fieldName, EntityLogicalName = recordType, Value = option.Key }; Execute(request); itemUpdated = true; } else if (optionSet.Any(o => o.Key == option.Key && o.Value != option.Value)) { var newValue = optionSet.Single(o => o.Key == option.Key); var request = new UpdateOptionValueRequest { AttributeLogicalName = fieldName, EntityLogicalName = recordType, Value = option.Key, Label = new Label(newValue.Value, 1033) }; Execute(request); itemUpdated = true; } } foreach (var option in optionSet) { if (!existingOptions.Any(o => o.Key == option.Key)) { var request = new InsertOptionValueRequest { AttributeLogicalName = fieldName, EntityLogicalName = recordType, Value = option.Key, Label = new Label(option.Value, 1033) }; Execute(request); itemUpdated = true; } } if (itemUpdated) RefreshFieldMetadata(fieldName, recordType); } }
private void SaveGlobalOptionSet() { WorkAsync("Saving global optionset...", (w, e) => { var req = new RetrieveOptionSetRequest() { Name = ((Item)cboOptionSets.SelectedItem).Value, }; var resp = (RetrieveOptionSetResponse)Service.Execute(req); OptionSetMetadata md = (OptionSetMetadata)resp.OptionSetMetadata; //foreach (var option in md.Options) //{ // var delReq = new DeleteOptionValueRequest() // { // OptionSetName = md.Name, // Value = option.Value.Value // }; // Service.Execute(delReq); //} var data = (BindingList<Item>)dgvOptions.DataSource; var execMultiReq = new ExecuteMultipleRequest() { Settings = new Microsoft.Xrm.Sdk.ExecuteMultipleSettings() { ContinueOnError = true, ReturnResponses = false }, Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection() }; foreach (var item in data) { var exists = (from o in md.Options where o.Value.Value == int.Parse(item.Value) select true).FirstOrDefault(); if (exists) { var upReq = new UpdateOptionValueRequest() { OptionSetName = md.Name, Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033), Value = int.Parse(item.Value) }; execMultiReq.Requests.Add(upReq); } else { var addReq = new InsertOptionValueRequest() { OptionSetName = md.Name, Label = new Microsoft.Xrm.Sdk.Label(item.Name, 1033), Value = int.Parse(item.Value) }; execMultiReq.Requests.Add(addReq); } } foreach (var item in md.Options) { var exists = (from d in data where int.Parse(d.Value) == item.Value.Value select true).FirstOrDefault(); if (!exists) { var delReq = new DeleteOptionValueRequest() { OptionSetName = md.Name, Value = item.Value.Value }; execMultiReq.Requests.Add(delReq); } } Service.Execute(execMultiReq); w.ReportProgress(50, "Publishing global optionset..."); PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", md.Name) }; Service.Execute(pxReq1); }, e => { }, e => { SetWorkingMessage(e.UserState.ToString()); } ); }
/// <summary> /// Create a global option set. /// Set the options for that option set. /// Create a new reference to that option set on an entity. /// Update the option set's properties. /// Check the global option set for dependencies. /// Delete the option set. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); #region How to create global option set // Define the request object and pass to the service. CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)_serviceProxy.Execute(createOptionSetRequest); #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. CreateAttributeRequest createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; _serviceProxy.Execute(createRequest); Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; _serviceProxy.Execute(updateOptionSetRequest); //Publish the OptionSet PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq1); Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq2); Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; _serviceProxy.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq3); Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. OptionSetName = _globalOptionSetName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; _serviceProxy.Execute(pxReq4); Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)_serviceProxy.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } #endregion How to retrieve all global option sets DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Processes the non-global option sets /// </summary> /// <param name="dictionary">The <C>Dictionary</C> that contains the name value pairs for the option set.</param> /// <param name="entityName">The name of the <C>Entity</C> that the option set belongs to.</param> private void ProcessPickLists(Dictionary <string, object> dictionary, string entityName) { if (dictionary == null) { return; } OrganizationResponse langRes = null; foreach (string attributeName in dictionary.Keys) { string[] values = dictionary[attributeName] as string[]; if (values.Length < 1) { continue; } RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest(); attribReq.EntityLogicalName = entityName; attribReq.LogicalName = attributeName; attribReq.RetrieveAsIfPublished = true; OrganizationRequest langReq = new OrganizationRequest("RetrieveAvailableLanguages"); // Get the attribute metadata for the state attribute. RetrieveAttributeResponse metadataRespone = null; try { metadataRespone = (RetrieveAttributeResponse)this.CrmAdapter.OrganizationService.Execute(attribReq); if (langRes == null) { langRes = this.CrmAdapter.OrganizationService.Execute(langReq); } } catch (Exception e) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.MetadataClientPicklistExceptionMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataRetrieval }; } if (metadataRespone != null) { PicklistAttributeMetadata picklistAttrib = metadataRespone.AttributeMetadata as PicklistAttributeMetadata; int optionNumber = 200000; InsertOptionValueRequest insertRequest = new InsertOptionValueRequest(); insertRequest.AttributeLogicalName = picklistAttrib.LogicalName; insertRequest.EntityLogicalName = entityName; insertRequest.Label = new Label(); insertRequest.Value = new int?(); foreach (string picklistName in values) { try { var option = picklistAttrib.OptionSet.Options.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label.Replace(NotInErp, string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant() || opt.Label.UserLocalizedLabel.Label.Replace("*", string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant()); optionNumber += picklistAttrib.OptionSet.Options.Count(); // Add new values if (option == null) { insertRequest.Value = optionNumber++; insertRequest.Label = CreateSingleLabel(picklistName, metadataRespone.AttributeMetadata.DisplayName.UserLocalizedLabel.LanguageCode); this.CrmAdapter.OrganizationService.Execute(insertRequest); } else if (option.Label.UserLocalizedLabel.Label != picklistName) { // Update existing values if they are different this.CrmAdapter.OrganizationService.Execute(new UpdateOptionValueRequest() { AttributeLogicalName = picklistAttrib.LogicalName, EntityLogicalName = entityName, Label = CreateSingleLabel(picklistName, option.Label.UserLocalizedLabel.LanguageCode), MergeLabels = false, Value = option.Value.Value }); } } catch (FaultException e) { if (e.Message.Contains("because another picklist or status option for this attribute already exists")) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ValueExistsMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } else { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.AddingValueExceptionMessage, picklistName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } } } } } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // Define the request object and pass to the service. var createOptionSetRequest = new CreateOptionSetRequest { // Create a global option set (OptionSetMetadata). OptionSet = new OptionSetMetadata { Name = _globalOptionSetName, DisplayName = new Label("Example Option Set", _languageCode), IsGlobal = true, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("Open", _languageCode), null), new OptionMetadata(new Label("Suspended", _languageCode), null), new OptionMetadata(new Label("Cancelled", _languageCode), null), new OptionMetadata(new Label("Closed", _languageCode), null) } } }; // Execute the request. CreateOptionSetResponse optionsResp = (CreateOptionSetResponse)service.Execute(createOptionSetRequest); //</snippetWorkwithGlobalOptionSets2> #endregion How to create global option set // Store the option set's id as it will be needed to find all the // dependent components. _optionSetId = optionsResp.OptionSetId; Console.WriteLine("The global option set has been created."); #region How to create a picklist linked to the global option set //<snippetWorkwithGlobalOptionSets3> // Create a Picklist linked to the option set. // Specify which entity will own the picklist, and create it. var createRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = new PicklistAttributeMetadata { SchemaName = "sample_examplepicklist", LogicalName = "sample_examplepicklist", DisplayName = new Label("Example Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), // In order to relate the picklist to the global option set, be sure // to specify the two attributes below appropriately. // Failing to do so will lead to errors. OptionSet = new OptionSetMetadata { IsGlobal = true, Name = _globalOptionSetName } } }; service.Execute(createRequest); //</snippetWorkwithGlobalOptionSets3> Console.WriteLine("Referring picklist attribute created."); #endregion How to create a picklist linked to the global option set #region How to update a global option set //<snippetWorkwithGlobalOptionSets4> // Use UpdateOptionSetRequest to update the basic information of an option // set. Updating option set values requires different messages (see below). var updateOptionSetRequest = new UpdateOptionSetRequest { OptionSet = new OptionSetMetadata { DisplayName = new Label("Updated Option Set", _languageCode), Name = _globalOptionSetName, IsGlobal = true } }; service.Execute(updateOptionSetRequest); //Publish the OptionSet var pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.Execute(pxReq1); //</snippetWorkwithGlobalOptionSets4> Console.WriteLine("Option Set display name changed."); #endregion How to update a global option set properties #region How to insert a new option item in a global option set //<snippetWorkwithGlobalOptionSets5> // Use InsertOptionValueRequest to insert a new option into a // global option set. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { OptionSetName = _globalOptionSetName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request and store the newly inserted option value // for cleanup, used in the later part of this sample. _insertedOptionValue = ((InsertOptionValueResponse)service.Execute( insertOptionValueRequest)).NewOptionValue; //Publish the OptionSet PublishXmlRequest pxReq2 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.Execute(pxReq2); //</snippetWorkwithGlobalOptionSets5> Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, _insertedOptionValue); #endregion How to insert a new option item in a global option set #region How to retrieve a global option set by it's name //<snippetWorkwithGlobalOptionSets6> // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)service.Execute( retrieveOptionSetRequest); Console.WriteLine("Retrieved {0}.", retrieveOptionSetRequest.Name); // Access the retrieved OptionSetMetadata. OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray(); //</snippetWorkwithGlobalOptionSets6> #endregion How to retrieve a global option set by it's name #region How to update an option item in a picklist //<snippetWorkwithGlobalOptionSets7> // In order to change labels on option set values (or delete) option set // values, you must use UpdateOptionValueRequest // (or DeleteOptionValueRequest). UpdateOptionValueRequest updateOptionValueRequest = new UpdateOptionValueRequest { OptionSetName = _globalOptionSetName, // Update the second option value. Value = optionList[1].Value.Value, Label = new Label("Updated Option 1", _languageCode) }; service.Execute(updateOptionValueRequest); //Publish the OptionSet PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.Execute(pxReq3); //</snippetWorkwithGlobalOptionSets7> Console.WriteLine("Option Set option label changed."); #endregion How to update an option item in a picklist #region How to change the order of options of a global option set //<snippetWorkwithGlobalOptionSets8> // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. OptionSetName = _globalOptionSetName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request service.Execute(orderOptionRequest); //Publish the OptionSet PublishXmlRequest pxReq4 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) }; service.Execute(pxReq4); //</snippetWorkwithGlobalOptionSets8> Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set #region How to retrieve all global option sets //<snippetWorkwithGlobalOptionSets9> // Use RetrieveAllOptionSetsRequest to retrieve all global option sets. // Create the request. RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest = new RetrieveAllOptionSetsRequest(); // Execute the request RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse = (RetrieveAllOptionSetsResponse)service.Execute( retrieveAllOptionSetsRequest); // Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to // work with all retrieved option sets. if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0) { Console.WriteLine("All the global option sets retrieved as below:"); int count = 1; foreach (OptionSetMetadataBase optionSetMetadata in retrieveAllOptionSetsResponse.OptionSetMetadata) { Console.WriteLine("{0} {1}", count++, (optionSetMetadata.DisplayName.LocalizedLabels.Count > 0) ? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty); } } #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public void Should_store_user_localized_label() { var label = "fake"; var attributeName = "statuscode"; var ctx = new XrmFakedContext(); LocalizedLabel localizedLabel1 = new LocalizedLabel(label, 10); LocalizedLabel localizedLabel2 = new LocalizedLabel("falso", 10); LocalizedLabel[] localizedLabels = new LocalizedLabel[] { localizedLabel1, localizedLabel2 }; var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata() { LogicalName = attributeName }; entityMetadata.SetAttributeCollection(new List <AttributeMetadata>() { enumAttribute }); ctx.InitializeMetadata(entityMetadata); var req = new InsertOptionValueRequest() { EntityLogicalName = Contact.EntityLogicalName, AttributeLogicalName = attributeName, Label = new Label(localizedLabel1, localizedLabels) }; var service = ctx.GetOrganizationService(); service.Execute(req); //Check the optionsetmetadata was updated var key = $"{Contact.EntityLogicalName}#{attributeName}"; Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key)); var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.Equal(label, option.Label.LocalizedLabels[0].Label); // Get a list of Option Set values for the Status Reason fields from its metadata RetrieveAttributeRequest attReq = new RetrieveAttributeRequest { EntityLogicalName = "contact", LogicalName = "statuscode", RetrieveAsIfPublished = true }; RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq); StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata; Assert.NotNull(statusAttributeMetadata.OptionSet); Assert.NotNull(statusAttributeMetadata.OptionSet.Options); Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Count(o => o.Label.LocalizedLabels[0].Label == label)); foreach (var optionMetadata in statusAttributeMetadata.OptionSet.Options) { Console.WriteLine("Key " + optionMetadata.Value + " Value: " + optionMetadata.Label.UserLocalizedLabel.Label); } }
[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> /// Processes the non-global option sets /// </summary> /// <param name="dictionary">The <C>Dictionary</C> that contains the name value pairs for the option set.</param> /// <param name="entityName">The name of the <C>Entity</C> that the option set belongs to.</param> private void ProcessPickLists(Dictionary<string, object> dictionary, string entityName) { if (dictionary == null) { return; } OrganizationResponse langRes = null; foreach (string attributeName in dictionary.Keys) { string[] values = dictionary[attributeName] as string[]; if (values.Length < 1) { continue; } RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest(); attribReq.EntityLogicalName = entityName; attribReq.LogicalName = attributeName; attribReq.RetrieveAsIfPublished = true; OrganizationRequest langReq = new OrganizationRequest("RetrieveAvailableLanguages"); // Get the attribute metadata for the state attribute. RetrieveAttributeResponse metadataRespone = null; try { metadataRespone = (RetrieveAttributeResponse)this.CrmAdapter.OrganizationService.Execute(attribReq); if (langRes == null) { langRes = this.CrmAdapter.OrganizationService.Execute(langReq); } } catch (Exception e) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.MetadataClientPicklistExceptionMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataRetrieval }; } if (metadataRespone != null) { PicklistAttributeMetadata picklistAttrib = metadataRespone.AttributeMetadata as PicklistAttributeMetadata; int optionNumber = 200000; InsertOptionValueRequest insertRequest = new InsertOptionValueRequest(); insertRequest.AttributeLogicalName = picklistAttrib.LogicalName; insertRequest.EntityLogicalName = entityName; insertRequest.Label = new Label(); insertRequest.Value = new int?(); foreach (string picklistName in values) { try { var option = picklistAttrib.OptionSet.Options.FirstOrDefault(opt => opt.Label.UserLocalizedLabel.Label.Replace(NotInErp, string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant() || opt.Label.UserLocalizedLabel.Label.Replace("*", string.Empty).Trim().ToUpperInvariant() == picklistName.ToUpperInvariant()); optionNumber += picklistAttrib.OptionSet.Options.Count(); // Add new values if (option == null) { insertRequest.Value = optionNumber++; insertRequest.Label = CreateSingleLabel(picklistName, metadataRespone.AttributeMetadata.DisplayName.UserLocalizedLabel.LanguageCode); this.CrmAdapter.OrganizationService.Execute(insertRequest); } else if (option.Label.UserLocalizedLabel.Label != picklistName) { // Update existing values if they are different this.CrmAdapter.OrganizationService.Execute(new UpdateOptionValueRequest() { AttributeLogicalName = picklistAttrib.LogicalName, EntityLogicalName = entityName, Label = CreateSingleLabel(picklistName, option.Label.UserLocalizedLabel.LanguageCode), MergeLabels = false, Value = option.Value.Value }); } } catch (FaultException e) { if (e.Message.Contains("because another picklist or status option for this attribute already exists")) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ValueExistsMessage, entityName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } else { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.AddingValueExceptionMessage, picklistName, e.Message), e) { ExceptionId = ErrorCodes.PicklistMetadataCreation }; } } } } } }
/// <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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // 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", // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // 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", // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // 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; } }
protected void addOptionToCustomEntityOptionSet() { InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = _customAttributeSchemaName.ToLower(), EntityLogicalName = _customEntitySchemaName.ToLower(), Label = new Label("Fifth Option", _languageCode) }; _service.Execute(insertOptionValueRequest); }