/// <summary> /// Create and configure the organization service proxy. /// Create few types of attributes. /// Insert status in the existing status list. /// Retrieve attribute. /// Update attribute. /// Update existing state value. /// Optionally delete/revert any attributes /// that were created/changed for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetWorkWithAttributes1> #region How to create attributes //<snippetWorkWithAttributes2> // Create storage for new attributes being created addedAttributes = new List<AttributeMetadata>(); // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute DateTimeAttributeMetadata dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute DecimalAttributeMetadata decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute StringAttributeMetadata stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. _serviceProxy.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } //</snippetWorkWithAttributes2> #endregion How to create attributes #region How to insert status //<snippetWorkWithAttributes3> // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. InsertStatusValueRequest insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)_serviceProxy.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); //</snippetWorkWithAttributes3> #endregion How to insert status #region How to retrieve attribute //<snippetWorkWithAttributes4> // Create the request RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); //</snippetWorkWithAttributes4> #endregion How to retrieve attribute #region How to update attribute //<snippetWorkWithAttributes5> // Modify the retrieved attribute AttributeMetadata retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest UpdateAttributeRequest updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); //</snippetWorkWithAttributes5> #endregion How to update attribute #region How to update state value //<snippetWorkWithAttributes6> // Modify the state value label from Active to Open. // Create the request. UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. _serviceProxy.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); //</snippetWorkWithAttributes6> #endregion How to update state value #region How to insert a new option item in a local option set //<snippetWorkWithAttributes7> // Create a request. InsertOptionValueRequest insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)_serviceProxy.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); //</snippetWorkWithAttributes7> #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set //<snippetWorkWithAttributes8> // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)_serviceProxy.Execute( retrieveAttributeRequest); // Access the retrieved attribute. PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. OrderOptionRequest orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request _serviceProxy.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); //</snippetWorkWithAttributes8> #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. _serviceProxy.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); //</snippetWorkWithAttributes1> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private AttributeMetadata CreateBooleanAttribute(ExcelWorksheet sheet, int rowIndex, int startCell) { var amd = new BooleanAttributeMetadata { OptionSet = new BooleanOptionSetMetadata(), }; var stringValues = sheet.GetValue <string>(rowIndex, startCell); if (string.IsNullOrEmpty(stringValues)) { throw new Exception("Boolean values cannot be null"); } foreach (var optionRow in stringValues.Split('\n')) { var parts = optionRow.Split(':'); if (parts[0] == "0") { amd.OptionSet.FalseOption = new OptionMetadata(new Label(parts[1], settings.LanguageCode), int.Parse(parts[0])); } else if (parts[0] == "1") { amd.OptionSet.TrueOption = new OptionMetadata(new Label(parts[1], settings.LanguageCode), int.Parse(parts[0])); } } if (!string.IsNullOrEmpty(sheet.GetValue <string>(rowIndex, startCell + 1))) { amd.DefaultValue = sheet.GetValue <string>(rowIndex, startCell + 1) == "True"; } return(amd); }
private void CreateBooleanField(JToken field) { var entitySchemaName = JSONUtil.GetText(field, "entity"); var displayName = JSONUtil.GetText(field, "displayname"); var fieldSchemaName = JSONUtil.GetText(field, "schemaname"); CreateAttributeRequest req = new CreateAttributeRequest(); req.EntityName = entitySchemaName; var am = new BooleanAttributeMetadata(); am.SchemaName = fieldSchemaName; am.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None); am.DisplayName = new Label(displayName, 1033); am.Description = new Label("", 1033); am.OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("Yes", 1033), 1), new OptionMetadata(new Label("No", 1033), 0)); req.Attribute = am; this._cdsConnection.Execute(req); }
private CodeTypeDeclaration GenerateConstantTwoOptions(BooleanAttributeMetadata booleanAttribute) { CodeTypeDeclaration booleanOptionSet = new CodeTypeDeclaration(booleanAttribute.SchemaName) { IsClass = true, Attributes = MemberAttributes.Static | MemberAttributes.Public }; if (generateXmlDocumentation) { CustomizationService.AddMissingXmlDocumentation(booleanAttribute.SchemaName, booleanOptionSet.Comments); } var values = EnumItem.ToUniqueValues(booleanAttribute.OptionSet); foreach (var value in values) { CodeMemberField codeMemberField = new CodeMemberField(typeof(bool), value.Value) { InitExpression = new CodePrimitiveExpression(value.Key == 1), Attributes = MemberAttributes.Const | MemberAttributes.Public }; if (generateXmlDocumentation) { CustomizationService.AddMissingXmlDocumentation(value.Description, codeMemberField.Comments); } booleanOptionSet.Members.Add(codeMemberField); } return(booleanOptionSet); }
public static AttributeCardModel ToCard(this AttributeMetadata attribute) { AttributeCardModel attributeCard = new AttributeCardModel(attribute.DisplayName.UserLocalizedLabel.Label, attribute.LogicalName); if (attribute is PicklistAttributeMetadata) { PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)attribute; if (picklistAttributeMetadata != null) { var options = new List <OptionAttributeModel>(); foreach (var option_ in picklistAttributeMetadata?.OptionSet?.Options) { var optionAttributeModel = new OptionAttributeModel(option_.Label.UserLocalizedLabel.Label, option_.Value.Value); options.Add(optionAttributeModel); } attributeCard.Properties = options; } } else if (attribute is BooleanAttributeMetadata) { BooleanAttributeMetadata booleanOptionSetMetadata = (BooleanAttributeMetadata)attribute; if (booleanOptionSetMetadata != null) { var options = new List <OptionAttributeModel>(); options.Add(new OptionAttributeModel(booleanOptionSetMetadata?.OptionSet.TrueOption.Label.UserLocalizedLabel.Label, true)); options.Add(new OptionAttributeModel(booleanOptionSetMetadata?.OptionSet.FalseOption.Label.UserLocalizedLabel.Label, false)); attributeCard.Properties = options; } } return(attributeCard); }
public OptionMetadata[] GetOptionSet(string entityName, string fieldName) { OptionMetadata[] optionMetadatas; IOrganizationService orgService = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService); RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = fieldName, RetrieveAsIfPublished = false }; RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgService.Execute(attributeRequest); if (attributeResponse.AttributeMetadata.AttributeType == Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Boolean) { BooleanAttributeMetadata boolenAttributeMetadata = (BooleanAttributeMetadata)attributeResponse.AttributeMetadata; BooleanOptionSetMetadata boolenOptionSetMetadata = boolenAttributeMetadata.OptionSet; OptionMetadata[] options = new OptionMetadata[2]; options[0] = boolenOptionSetMetadata.TrueOption; options[1] = boolenOptionSetMetadata.FalseOption; optionMetadatas = options; } else { EnumAttributeMetadata picklistAttributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata; OptionSetMetadata optionSetMetadata = picklistAttributeMetadata.OptionSet; OptionMetadata[] optionList = optionSetMetadata.Options.ToArray(); optionMetadatas = optionList; } return(optionMetadatas); }
/// <summary> /// Get the string representation of the options from attribute metadata /// </summary> /// <param name="attributeMetadata">The attribute metadata</param> /// <returns>The string representation of the options from attribute metadata</returns> public static string GetOptions(AttributeMetadata attributeMetadata) { Dictionary <int, string> options = new Dictionary <int, string>(); switch (attributeMetadata.AttributeType) { case AttributeTypeCode.Boolean: BooleanAttributeMetadata booleanAttributeMetadata = (BooleanAttributeMetadata)attributeMetadata; options.Add(1, booleanAttributeMetadata.OptionSet.TrueOption == null ? "Yes" : Utils.ToValidIdentifier(booleanAttributeMetadata.OptionSet.TrueOption.Label.UserLocalizedLabel.Label)); options.Add(0, booleanAttributeMetadata.OptionSet.FalseOption == null ? "No" : Utils.ToValidIdentifier(booleanAttributeMetadata.OptionSet.FalseOption.Label.UserLocalizedLabel.Label)); break; case AttributeTypeCode.Picklist: options = Utils.ToUniqueValues(((PicklistAttributeMetadata)attributeMetadata).OptionSet.Options); break; case AttributeTypeCode.State: options = Utils.ToUniqueValues(((StateAttributeMetadata)attributeMetadata).OptionSet.Options); break; case AttributeTypeCode.Status: options = Utils.ToUniqueValues(((StatusAttributeMetadata)attributeMetadata).OptionSet.Options); break; case AttributeTypeCode.Virtual: if (attributeMetadata is MultiSelectPicklistAttributeMetadata) { options = Utils.ToUniqueValues(((MultiSelectPicklistAttributeMetadata)attributeMetadata).OptionSet.Options); } break; } return(string.Join(",\n", options.Select(o => string.Format(" {0} = {1}", o.Value, o.Key.ToString(CultureInfo.InvariantCulture))).ToArray())); }
private object CopyValueInternal(PicklistAttributeMetadata oldAttribute, BooleanAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping) { var copy = ((OptionSetValue)value).Value.ToString(); copy = migrationMapping.TryGetValue(copy, out var mappedValue) ? mappedValue : copy; return(GetBooleanValue(value, copy)); }
private AttributeMetadata CloneAttributes(BooleanAttributeMetadata att) { return(new BooleanAttributeMetadata { DefaultValue = att.DefaultValue, FormulaDefinition = att.FormulaDefinition, OptionSet = new BooleanOptionSetMetadata(att.OptionSet.TrueOption, att.OptionSet.FalseOption) }); }
private AttributeMetadata CloneAttributes(BooleanAttributeMetadata att) { return new BooleanAttributeMetadata { DefaultValue = att.DefaultValue, FormulaDefinition = att.FormulaDefinition, OptionSet = new BooleanOptionSetMetadata(att.OptionSet.TrueOption, att.OptionSet.FalseOption) }; }
private AttributeMetadata booleanFieldCreation(string[] row) { bool parseresult; BooleanAttributeMetadata attrMetadata = new BooleanAttributeMetadata(Utils.addOrgPrefix(row[ExcelColumsDefinition.SCHEMANAMEEXCELCOL], organizationPrefix, currentOperationCreate)); generalFieldCreation(row, attrMetadata); attrMetadata.DefaultValue = Boolean.TryParse(row[ExcelColumsDefinition.BOOLEANDEFAULTVALUE], out parseresult) ? parseresult : false; attrMetadata.OptionSet = new BooleanOptionSetMetadata(); attrMetadata.OptionSet.TrueOption = row[ExcelColumsDefinition.BOOLEANTRUEOPTION] != string.Empty ? new OptionMetadata(new Label(row[ExcelColumsDefinition.BOOLEANTRUEOPTION], languageCode), 1) : new OptionMetadata(new Label(string.Empty, languageCode), 1); attrMetadata.OptionSet.FalseOption = row[ExcelColumsDefinition.BOOLEANFALSEOPTION] != string.Empty ? new OptionMetadata(new Label(row[ExcelColumsDefinition.BOOLEANFALSEOPTION], languageCode), 0) : new OptionMetadata(new Label(string.Empty, languageCode), 0); return(attrMetadata); }
public static MappingBool Parse(BooleanAttributeMetadata twoOption) { var enm = new MappingBool(); enm.DisplayName = Naming.GetProperVariableName(Naming.GetProperVariableName(twoOption.SchemaName)); enm.Items = new MapperEnumItem[2]; enm.Items[0] = MapBoolOption(twoOption.OptionSet.TrueOption); enm.Items[1] = MapBoolOption(twoOption.OptionSet.FalseOption); RenameDuplicates(enm); return(enm); }
private object CopyValueInternal(BooleanAttributeMetadata oldAttribute, PicklistAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping) { var copy = value.ToString(); copy = migrationMapping.TryGetValue(copy, out var mappedValue) ? mappedValue : null; if (string.IsNullOrWhiteSpace(copy)) { Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to OptionSetValue"); return(null); } return(new OptionSetValue(int.Parse(copy))); }
protected override void ExecuteCmdlet() { base.ExecuteCmdlet(); BooleanAttributeMetadata attribute = _attribute as BooleanAttributeMetadata; if (DefaultValue.HasValue) { attribute.DefaultValue = DefaultValue.Value; } WriteAttribute(attribute); }
private AttributeMetadata CreateBooleanAttribute(object[] dataRowValues) { var metadata = new BooleanAttributeMetadata { OptionSet = new BooleanOptionSetMetadata { TrueOption = new OptionMetadata(new Label("Yes", LcId), 1), FalseOption = new OptionMetadata(new Label("No", LcId), 0) }, DefaultValue = false }; foreach (var column in Columns) { var value = dataRowValues[column.Position - 1]; var field = (ConfigurationFile.AttributeFields)column.TargetField; if (value != null && !string.IsNullOrEmpty(value as string)) { switch (field) { case ConfigurationFile.AttributeFields.DefaultValue: metadata.DefaultValue = Convert.ToBoolean(value); break; case ConfigurationFile.AttributeFields.Options: var options = ParseOptions(value as string); foreach (var option in options) { if (option.Value == 0) { metadata.OptionSet.FalseOption.Label = option.Label; } else if (option.Value == 1) { metadata.OptionSet.TrueOption.Label = option.Label; } } break; } } else if (!EnumUtils.IsOptional(field)) { throw new ArgumentException($"Mandatory data field {EnumUtils.Label(field)} does not contain a value."); } } return(metadata); }
public BooleanOptionSetMetadata GetBooleanTextOnValue(string entityName, string attributeName) { RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)Service.Execute(retrieveAttributeRequest); BooleanAttributeMetadata attributeMetadata = (BooleanAttributeMetadata)retrieveAttributeResponse?.AttributeMetadata; if (attributeMetadata == null) { return(null); } return(attributeMetadata?.OptionSet); }
private BooleanAttributeMetadata BuildCreateBooleanAttribute() { var optionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", DefaultLanguageCode), 1), new OptionMetadata(new Label("False", DefaultLanguageCode), 0) ); var boolAttribute = new BooleanAttributeMetadata(optionSet); // Set default value. if (this.CurrentColumnDefinition.Default != null) { ((IVisitableBuilder)this.CurrentColumnDefinition.Default).Accept(this); boolAttribute.DefaultValue = this.CurrentDefaultBooleanAttributeValue; this.CurrentDefaultBooleanAttributeValue = null; } return(boolAttribute); }
private object CopyValueInternal(AttributeMetadata oldAttribute, BooleanAttributeMetadata newAttribute, object value) { bool output; if (bool.TryParse(value.ToString(), out output)) { return output; } try { return Convert.ToBoolean(value); } catch { // Failed to convert. Give Up } Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double"); return null; }
/// <summary> /// Creates Boolean field for the Entity. /// </summary> /// <param name="SchemaName">The Schema Name</param> /// <param name="DisplayName">The field Display Name</param> /// <param name="trueValue">Truth Value Label</param> /// <param name="falseValue">False Value Label</param> /// <param name="addedAttributes">Pass by reference (ref addedAttributes)</param> /// <returns></returns> static void createFieldBoolean(string SchemaName, string DisplayName, string trueValue, string falseValue, ref List <AttributeMetadata> addedAttributes) { var CreatedBooleanAttributeMetadata = new BooleanAttributeMetadata() { SchemaName = "new_" + SchemaName, LogicalName = "new_" + SchemaName, DisplayName = new Label(DisplayName + "*", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("MSVProperties CRM - " + DisplayName, _languageCode), IsValidForForm = true, IsValidForGrid = true, OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label(trueValue, 1033), 1), new OptionMetadata(new Label(falseValue, 1033), 0) ), }; addedAttributes.Add(CreatedBooleanAttributeMetadata); }
public BooleanAttributeMetadata CreateBoolean(string schema, string label, int lang, AttributeRequiredLevel requiredLevel) { // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = schema, DisplayName = new Label(label, lang), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(label, lang), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", lang), 1), new OptionMetadata(new Label("False", lang), 0) ) }; return(boolAttribute); }
private object CopyValueInternal(AttributeMetadata oldAttribute, BooleanAttributeMetadata newAttribute, object value) { bool output; if (bool.TryParse(value.ToString(), out output)) { return(output); } try { return(Convert.ToBoolean(value)); } catch { // Failed to convert. Give Up } Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double"); return(null); }
public BooleanAttributeMetadata Create(AttributeMetadata baseMetadata, string trueLabel = "Yes", string falseLabel = "No", int labelLanguage = Global.LANGUAGE) { var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = baseMetadata.SchemaName, DisplayName = baseMetadata.DisplayName, RequiredLevel = baseMetadata.RequiredLevel, Description = baseMetadata.Description, // Set extended properties OptionSet = new BooleanOptionSetMetadata { TrueOption = new OptionMetadata(new Label(trueLabel, labelLanguage), 1), FalseOption = new OptionMetadata(new Label(falseLabel, labelLanguage), 0) } }; return(boolAttribute); }
private static BooleanAttributeMetadata CreateBooleanAttribute(string name, string displayName, AttributeRequiredLevel attributeRequiredLevel, string desription) { // Create a boolean attribute BooleanAttributeMetadata boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = publisherPrefix + name, LogicalName = publisherPrefix + name, DisplayName = new Label(displayName, _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(attributeRequiredLevel), Description = new Label(desription, _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; return(boolAttribute); }
private IEnumerable <string> checkDifferenceBooleanAttribute(BooleanAttributeMetadata originalAttributeMetadata, BooleanAttributeMetadata readAttributeMetadata) { List <string> attributeToChange = new List <string>(); if (originalAttributeMetadata.DefaultValue != readAttributeMetadata.DefaultValue) { originalAttributeMetadata.DefaultValue = readAttributeMetadata.DefaultValue; attributeToChange.Add("DefaultValue"); } if (Utils.getLocalizedLabel(originalAttributeMetadata.OptionSet.TrueOption.Label.LocalizedLabels, languageCode) != Utils.getLocalizedLabel(readAttributeMetadata.OptionSet.TrueOption.Label.LocalizedLabels, languageCode)) { Utils.setLocalizedLabel(originalAttributeMetadata.OptionSet.TrueOption.Label.LocalizedLabels, languageCode, Utils.getLocalizedLabel(readAttributeMetadata.OptionSet.TrueOption.Label.LocalizedLabels, languageCode)); attributeToChange.Add("True Option"); } if (Utils.getLocalizedLabel(originalAttributeMetadata.OptionSet.FalseOption.Label.LocalizedLabels, languageCode) != Utils.getLocalizedLabel(readAttributeMetadata.OptionSet.FalseOption.Label.LocalizedLabels, languageCode)) { Utils.setLocalizedLabel(originalAttributeMetadata.OptionSet.FalseOption.Label.LocalizedLabels, languageCode, Utils.getLocalizedLabel(readAttributeMetadata.OptionSet.FalseOption.Label.LocalizedLabels, languageCode)); attributeToChange.Add("False Option"); } return(attributeToChange); }
public EntityAttributeMetadataBuilder BooleanAttribute(string schemaName, string displayName, string description, AttributeRequiredLevel requiredLevel, string trueLabel, int trueValue, string falseLabel, int falseValue) { int languageCode = 1033; // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = schemaName, DisplayName = new Label(displayName, languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(description, languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label(trueLabel, languageCode), trueValue), new OptionMetadata(new Label(falseLabel, languageCode), falseValue) ) }; this.Attributes.Add(boolAttribute); return(this); }
protected override void ExecuteCmdlet() { base.ExecuteCmdlet(); BooleanAttributeMetadata attribute = new BooleanAttributeMetadata(); if (DefaultValue.HasValue) { attribute.DefaultValue = DefaultValue.Value; } if (TrueValue != null) { attribute.OptionSet.TrueOption = new OptionMetadata(new Label(TrueValue.DisplayName, CrmContext.Language), TrueValue.Value); } if (FalseValue != null) { attribute.OptionSet.FalseOption = new OptionMetadata(new Label(FalseValue.DisplayName, CrmContext.Language), FalseValue.Value); } WriteAttribute(attribute); }
public EntityAttributeMetadataBuilder BooleanAttribute(string schemaName, AttributeRequiredLevel requiredLevel, int maxLength, StringFormat format, string displayName, string description) { int languageCode = 1033; // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = schemaName, DisplayName = new Label(displayName, languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(description, languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", languageCode), 1), new OptionMetadata(new Label("False", languageCode), 0) ) }; this.Attributes.Add(boolAttribute); return this; }
public static Guid AddAttribute() { BooleanAttributeMetadata booleanAttribute = new BooleanAttributeMetadata { SchemaName = "new_Boolean", LogicalName = "new_boolean", DisplayName = new Label("Sample Boolean", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", 1003), OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", 1033), 1), new OptionMetadata(new Label("False", 1033), 0)) }; CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest { EntityName = "testaccount", Attribute = booleanAttribute }; var response = service.Execute(createAttributeRequest); return(new Guid()); }
public EntityAttributeMetadataBuilder BooleanAttribute(string schemaName, AttributeRequiredLevel requiredLevel, int maxLength, StringFormat format, string displayName, string description) { int languageCode = 1033; // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = schemaName, DisplayName = new Label(displayName, languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(description, languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", languageCode), 1), new OptionMetadata(new Label("False", languageCode), 0) ) }; this.Attributes.Add(boolAttribute); return(this); }
public BooleanAttributeMetadataInfo(BooleanAttributeMetadata amd) : base(amd) { this.amd = amd; }
public void CreateOrUpdateBooleanAttribute(string schemaName, string displayName, string description, bool isRequired, bool audit, bool searchable, string recordType) { var optionSet = new BooleanOptionSetMetadata(); optionSet.FalseOption = new OptionMetadata(new Label("No", 1033), 0); optionSet.TrueOption = new OptionMetadata(new Label("Yes", 1033), 1); BooleanAttributeMetadata metadata; if (FieldExists(schemaName, recordType)) metadata = (BooleanAttributeMetadata) GetFieldMetadata(schemaName, recordType); else metadata = new BooleanAttributeMetadata(); SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable); metadata.OptionSet = optionSet; CreateOrUpdateAttribute(schemaName, recordType, metadata); }
// ReSharper restore UnusedParameter.Local private static UpdateFormulaResponse UpdateInternal(BooleanAttributeMetadata att, AttributeMetadata from, AttributeMetadata to) { return UpdateForumlaDefinition(att, from, to); }
private CodeTypeDeclaration GenerateEnumTwoOptions(BooleanAttributeMetadata booleanAttribute) { return(GenerateEnumOptions(booleanAttribute.SchemaName, EnumItem.ToUniqueValues(booleanAttribute.OptionSet))); }
private static AttributeMetadata CreateAttributeMetadata(Type propertyType) { if (typeof(string) == propertyType) { return(new StringAttributeMetadata()); } else if (typeof(EntityReference).IsAssignableFrom(propertyType)) { return(new LookupAttributeMetadata()); } #if FAKE_XRM_EASY || FAKE_XRM_EASY_2013 || FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 else if (typeof(Microsoft.Xrm.Client.CrmEntityReference).IsAssignableFrom(propertyType)) { return(new LookupAttributeMetadata()); } #endif else if (typeof(OptionSetValue).IsAssignableFrom(propertyType)) { return(new PicklistAttributeMetadata()); } else if (typeof(Money).IsAssignableFrom(propertyType)) { return(new MoneyAttributeMetadata()); } else if (propertyType.IsGenericType) { Type genericType = propertyType.GetGenericArguments().FirstOrDefault(); if (propertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (typeof(int) == genericType) { return(new IntegerAttributeMetadata()); } else if (typeof(double) == genericType) { return(new DoubleAttributeMetadata()); } else if (typeof(bool) == genericType) { return(new BooleanAttributeMetadata()); } else if (typeof(decimal) == genericType) { return(new DecimalAttributeMetadata()); } else if (typeof(DateTime) == genericType) { return(new DateTimeAttributeMetadata()); } else if (typeof(Guid) == genericType) { return(new LookupAttributeMetadata()); } else if (typeof(long) == genericType) { return(new BigIntAttributeMetadata()); } else if (typeof(Enum).IsAssignableFrom(genericType)) { return(new StateAttributeMetadata()); } else { throw new Exception($"Type {propertyType.Name}{genericType.Name} has not been mapped to an AttributeMetadata."); } } else if (propertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { var partyList = new LookupAttributeMetadata(); partyList.SetSealedPropertyValue("AttributeType", AttributeTypeCode.PartyList); return(partyList); } else { throw new Exception($"Type {propertyType.Name}{genericType.Name} has not been mapped to an AttributeMetadata."); } } else if (typeof(BooleanManagedProperty) == propertyType) { var booleanManaged = new BooleanAttributeMetadata(); booleanManaged.SetSealedPropertyValue("AttributeType", AttributeTypeCode.ManagedProperty); return(booleanManaged); } #if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013 else if (typeof(Guid) == propertyType) { return(new UniqueIdentifierAttributeMetadata()); } #endif #if !FAKE_XRM_EASY else if (typeof(byte[]) == propertyType) { return(new ImageAttributeMetadata()); } #endif #if FAKE_XRM_EASY_9 else if (typeof(OptionSetValueCollection).IsAssignableFrom(propertyType)) { return(new MultiSelectPicklistAttributeMetadata()); } #endif else { throw new Exception($"Type {propertyType.Name} has not been mapped to an AttributeMetadata."); } }
private RetrieveAttributeResponse ExecuteInternal(RetrieveAttributeRequest request) { var response = new RetrieveAttributeResponse(); var entityType = CrmServiceUtility.GetEarlyBoundProxyAssembly().GetTypes().FirstOrDefault(t => t.GetCustomAttribute <EntityLogicalNameAttribute>(true)?.LogicalName == request.EntityLogicalName); var propertyTypes = entityType?.GetProperties() .Where(p => p.GetCustomAttribute <AttributeLogicalNameAttribute>()?.LogicalName == request.LogicalName ).Select(p => p.PropertyType.IsGenericType ? p.PropertyType.GenericTypeArguments.First() : p.PropertyType).ToList(); var propertyType = propertyTypes?.Count == 1 ? propertyTypes[0] : propertyTypes?.FirstOrDefault(p => p != typeof(OptionSetValue) && p != typeof(EntityReference)); // Handle OptionSets/EntityReferences that may have multiple properties if (propertyType == null) { throw new Exception($"Unable to find a property for Entity {request.EntityLogicalName} and property {request.LogicalName} in {CrmServiceUtility.GetEarlyBoundProxyAssembly().FullName}"); } AttributeMetadata metadata; if (propertyType.IsEnum || propertyTypes.Any(p => p == typeof(OptionSetValue))) { metadata = CreateOptionSetAttributeMetadata(request, propertyType); } else if (propertyType == typeof(string)) { metadata = new StringAttributeMetadata(request.LogicalName); } else if (propertyTypes.Any(p => p == typeof(EntityReference))) { metadata = new LookupAttributeMetadata { LogicalName = request.LogicalName }; } #if !XRM_2013 else if (propertyType == typeof(Guid)) { metadata = new UniqueIdentifierAttributeMetadata { LogicalName = request.LogicalName }; } #endif else if (propertyType == typeof(bool)) { metadata = new BooleanAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(Money)) { metadata = new MoneyAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(int)) { metadata = new IntegerAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(long)) { metadata = new BigIntAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(DateTime)) { metadata = new DateTimeAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(double)) { metadata = new DoubleAttributeMetadata { LogicalName = request.LogicalName }; } else if (propertyType == typeof(decimal)) { metadata = new DecimalAttributeMetadata { LogicalName = request.LogicalName }; } else { throw new NotImplementedException($"Attribute Type of {propertyType.FullName} is not implemented."); } response.Results["AttributeMetadata"] = metadata; return(response); }
/// <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; } }
[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(); } }
private BooleanAttributeMetadata CreateBoolAttributeMetadata(AttributeTemplate attributeTemplate) { var yesValue = DefaultConfiguration.YesDefaultValue; var noValue = DefaultConfiguration.NoDefaultValue; if (attributeTemplate.OptionSetList != null && attributeTemplate.OptionSetList.Count == 2) { yesValue = attributeTemplate.OptionSetList[0].Label; noValue = attributeTemplate.OptionSetList[1].Label; } var booleanAttributeMetadata = new BooleanAttributeMetadata { OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(GetLabelWithLocalized(yesValue), 1), new OptionMetadata(GetLabelWithLocalized(noValue), 0) ), DefaultValue = attributeTemplate.BooleanDefaultValue == default(bool?) ? DefaultConfiguration.DefaultBooleanDefaultValue : attributeTemplate.BooleanDefaultValue }; return booleanAttributeMetadata; }