Example #1
8
        /// <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;
            }
        }
Example #2
0
        private AttributeMetadata CreateNumberAttribute(ExcelWorksheet sheet, int rowIndex, int startCell)
        {
            var namd = new IntegerAttributeMetadata
            {
                MinValue = sheet.GetValue <int>(rowIndex, startCell + 1),
                MaxValue = sheet.GetValue <int>(rowIndex, startCell + 2)
            };

            switch (sheet.GetValue <string>(rowIndex, startCell))
            {
            default:
                namd.Format = IntegerFormat.None;
                break;

            case "Duration":
                namd.Format = IntegerFormat.Duration;
                break;

            case "Timezone":
                namd.Format = IntegerFormat.TimeZone;
                break;

            case "Language code":
                namd.Format = IntegerFormat.Language;
                break;

            case "Locale":
                namd.Format = IntegerFormat.Locale;
                break;
            }

            return(namd);
        }
        public void HandleObfuscation(Entity entity, FieldToBeObfuscated field, IEntityMetadataCache metaData)
        {
            // Get the min and maximum values for the field using the meta data cache
            IntegerAttributeMetadata intMetaData = (IntegerAttributeMetadata)metaData.GetAttribute(entity.LogicalName, field.FieldName);
            int min = intMetaData.MinValue.GetValueOrDefault(0);
            int max = intMetaData.MaxValue.GetValueOrDefault(10);

            entity[field.FieldName] = intScramblerClient.ExecuteScramble((int)entity[field.FieldName], min, max);
        }
        private IntegerAttributeMetadata BuildCreateIntAttribute()
        {
            // Must be an integer attribute.
            var intAttribute = new IntegerAttributeMetadata();

            intAttribute.MaxValue = int.MaxValue;
            intAttribute.MinValue = int.MinValue;
            intAttribute.Format   = IntegerFormat.None;
            return(intAttribute);
        }
Example #5
0
 private AttributeMetadata CloneAttributes(IntegerAttributeMetadata att)
 {
     return(new IntegerAttributeMetadata
     {
         Format = att.Format,
         MaxValue = att.MaxValue,
         MinValue = att.MinValue,
         FormulaDefinition = att.FormulaDefinition
     });
 }
 private object CopyValueInternal(AttributeMetadata oldAttribute, IntegerAttributeMetadata newAttribute, object value)
 {
     int output;
     if (int.TryParse(value.ToString(), out output))
     {
         return output;
     }
     Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Integer");
     return null;
 }
 private AttributeMetadata CloneAttributes(IntegerAttributeMetadata att)
 {
     return new IntegerAttributeMetadata
     {
         Format = att.Format,
         MaxValue = att.MaxValue,
         MinValue = att.MinValue,
         FormulaDefinition = att.FormulaDefinition
     };
 }
        private object CopyValueInternal(AttributeMetadata oldAttribute, IntegerAttributeMetadata newAttribute, object value)
        {
            int output;

            if (int.TryParse(value.ToString(), out output))
            {
                return(output);
            }
            Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Integer");
            return(null);
        }
        private AttributeMetadata integerFieldCreation(string[] row)
        {
            IntegerAttributeMetadata attrMetadata = new IntegerAttributeMetadata(Utils.addOrgPrefix(row[ExcelColumsDefinition.SCHEMANAMEEXCELCOL], organizationPrefix, currentOperationCreate));

            generalFieldCreation(row, attrMetadata);
            int    parseResult;
            string intgerFormatString = row[ExcelColumsDefinition.INTEGERFORMATCOL];

            attrMetadata.Format   = Enum.IsDefined(typeof(IntegerFormat), intgerFormatString) ? (IntegerFormat)Enum.Parse(typeof(IntegerFormat), intgerFormatString, true) : (IntegerFormat?)null;
            attrMetadata.MaxValue = int.TryParse(row[ExcelColumsDefinition.INTEGERMAXVALUECOL], out parseResult) ? parseResult : (int?)null;
            attrMetadata.MinValue = int.TryParse(row[ExcelColumsDefinition.INTEGERMINVALUECOL], out parseResult) ? parseResult : (int?)null;
            return(attrMetadata);
        }
        private IEnumerable <string> checkDifferenceIntegerAttribute(IntegerAttributeMetadata originalAttributeMetadata, IntegerAttributeMetadata readAttributeMetadata)
        {
            List <string> attributeToChange = new List <string>();

            if (originalAttributeMetadata.MinValue != readAttributeMetadata.MinValue)
            {
                originalAttributeMetadata.MinValue = readAttributeMetadata.MinValue;
                attributeToChange.Add("MinValue");
            }
            if (originalAttributeMetadata.MaxValue != readAttributeMetadata.MaxValue)
            {
                originalAttributeMetadata.MaxValue = readAttributeMetadata.MaxValue;
                attributeToChange.Add("MaxValue");
            }
            return(attributeToChange);
        }
Example #11
0
        private AttributeMetadata CreateIntegerAttribute(object[] dataRowValues)
        {
            var metadata = new IntegerAttributeMetadata
            {
                Format   = IntegerFormat.None,
                MinValue = IntegerAttributeMetadata.MinSupportedValue,
                MaxValue = IntegerAttributeMetadata.MaxSupportedValue
            };

            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.IntegerFormat:
                        metadata.Format = (IntegerFormat)EnumUtils.GetSelectedOption(field, value);
                        break;

                    case ConfigurationFile.AttributeFields.MinimumValue:
                        var minValue = Convert.ToInt32(value);
                        if (minValue >= IntegerAttributeMetadata.MinSupportedValue && minValue <= IntegerAttributeMetadata.MaxSupportedValue)
                        {
                            metadata.MinValue = minValue;
                        }
                        break;

                    case ConfigurationFile.AttributeFields.MaximumValue:
                        var maxValue = Convert.ToInt32(value);
                        if (maxValue >= IntegerAttributeMetadata.MinSupportedValue && maxValue <= IntegerAttributeMetadata.MaxSupportedValue)
                        {
                            metadata.MinValue = maxValue;
                        }
                        break;
                    }
                }
                else if (!EnumUtils.IsOptional(field))
                {
                    throw new ArgumentException($"Mandatory data field {EnumUtils.Label(field)} does not contain a value.");
                }
            }
            return(metadata);
        }
        public IntegerAttributeMetadata CreateSmallInteger(string schema, string label, int lang, AttributeRequiredLevel requiredLevel, int size)
        {
            IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
            {
                // Set base properties
                SchemaName    = schema,
                DisplayName   = new Label(label, lang),
                RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                Description   = new Label(label, lang),
                // Set extended properties
                Format   = IntegerFormat.None,
                MaxValue = size,
                MinValue = 0
            };

            return(integerAttribute);
        }
Example #13
0
        public IntegerAttributeMetadata Create(AttributeMetadata baseMetadata, IntegerFormat integetFormat, int?maxvalue, int?minvalue)
        {
            var integerAttribute = new IntegerAttributeMetadata
            {
                // Set base properties
                SchemaName    = baseMetadata.SchemaName,
                DisplayName   = baseMetadata.DisplayName,
                RequiredLevel = baseMetadata.RequiredLevel,
                Description   = baseMetadata.Description,
                // Set extended properties
                Format   = IntegerFormat.None,
                MaxValue = 100,
                MinValue = 0
            };

            return(integerAttribute);
        }
Example #14
0
        private static IntegerAttributeMetadata CreateIntegerAttributeMetadata(string name, string displayName, AttributeRequiredLevel attributeRequiredLevel, string desription, int minValue, int maxValue)
        {
            // Create a date time attribute
            IntegerAttributeMetadata integerAttribute = new IntegerAttributeMetadata
            {
                // 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
                Format   = IntegerFormat.None,
                MaxValue = maxValue,
                MinValue = minValue
            };

            return(integerAttribute);
        }
Example #15
0
        public EntityAttributeMetadataBuilder IntAttribute(string schemaName, string displayName, string description, AttributeRequiredLevel requiredLevel, IntegerFormat format, int min, int max)
        {
            // Define the primary attribute for the entity
            // Create a integer attribute
            int languageCode     = 1033;
            var integerAttribute = new IntegerAttributeMetadata
            {
                // Set base properties
                SchemaName    = schemaName,
                DisplayName   = new Label(schemaName, languageCode),
                RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel),
                Description   = new Label(description, languageCode),
                // Set extended properties
                Format   = format,
                MaxValue = max,
                MinValue = min
            };

            this.Attributes.Add(integerAttribute);
            return(this);
        }
        private object CopyValueInternal(AttributeMetadata oldAttribute, IntegerAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping)
        {
            var unformatted = value.ToString();

            unformatted = migrationMapping.TryGetValue(unformatted, out var mappedValue) ? mappedValue : unformatted;

            // Handle 1.0000
            if (unformatted.Contains("."))
            {
                while (unformatted.EndsWith("0") || unformatted.EndsWith("."))
                {
                    unformatted = unformatted.Substring(0, unformatted.Length - 1);
                }
            }

            if (int.TryParse(unformatted, out var output))
            {
                return(output);
            }
            Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Integer");
            return(null);
        }
        protected override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            IntegerAttributeMetadata attribute = new IntegerAttributeMetadata();

            if (Format.HasValue)
            {
                attribute.Format = IntegerFormat.None;
                if (Format == CrmIntegerAttributeFormat.Duration)
                {
                    attribute.Format = IntegerFormat.Duration;
                }
                if (Format == CrmIntegerAttributeFormat.Language)
                {
                    attribute.Format = IntegerFormat.Language;
                }
                if (Format == CrmIntegerAttributeFormat.Locale)
                {
                    attribute.Format = IntegerFormat.Locale;
                }
                if (Format == CrmIntegerAttributeFormat.TimeZone)
                {
                    attribute.Format = IntegerFormat.TimeZone;
                }
            }

            if (MaxValue.HasValue)
            {
                attribute.MaxValue = MaxValue.Value;
            }
            if (MinValue.HasValue)
            {
                attribute.MinValue = MinValue.Value;
            }

            WriteAttribute(attribute);
        }
Example #18
0
        /// <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();
            }
        }
Example #20
0
        private AttributeMetadata GetAttributeMetadata(string type, string logicalname, string displayname, AttributeRequiredLevel requiredlevel)
        {
            AttributeMetadata attribute = null;

            if (type != null)
            {
                switch (type.ToLower())
                {
                case "boolean":
                    attribute = new BooleanAttributeMetadata
                    {
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Label("True", languageCode), 1),
                            new OptionMetadata(new Label("False", languageCode), 0)
                            )
                    };
                    break;

                case "datetime":
                    // Create a date time attribute
                    attribute = new DateTimeAttributeMetadata
                    {
                        // Set extended properties
                        Format  = DateTimeFormat.DateOnly,
                        ImeMode = ImeMode.Disabled
                    };
                    break;

                case "double":
                    // Create a decimal attribute
                    attribute = new DecimalAttributeMetadata
                    {
                        // Set extended properties
                        MaxValue  = 100,
                        MinValue  = 0,
                        Precision = 1
                    };
                    break;

                case "integer":
                    // Create a integer attribute
                    attribute = new IntegerAttributeMetadata
                    {
                        // Set extended properties
                        Format   = IntegerFormat.None,
                        MaxValue = 100,
                        MinValue = 0
                    };
                    break;

                case "memo":
                    // Create a memo attribute
                    attribute = new MemoAttributeMetadata
                    {
                        // Set extended properties
                        Format    = StringFormat.TextArea,
                        ImeMode   = ImeMode.Disabled,
                        MaxLength = 500
                    };
                    break;

                case "money":
                    // Create a money attribute
                    MoneyAttributeMetadata moneyAttribute = new MoneyAttributeMetadata
                    {
                        // Set extended properties
                        MaxValue        = 1000.00,
                        MinValue        = 0.00,
                        Precision       = 1,
                        PrecisionSource = 1,
                        ImeMode         = ImeMode.Disabled
                    };
                    break;

                case "picklist":
                    // Create a picklist attribute
                    attribute = new PicklistAttributeMetadata
                    {
                        // Set extended properties
                        // Build local picklist options
                        OptionSet = new OptionSetMetadata
                        {
                            IsGlobal      = false,
                            OptionSetType = OptionSetType.Picklist
                        }
                    };
                    break;

                case "string":
                    // Create a string attribute
                    attribute = new StringAttributeMetadata
                    {
                        // Set extended properties
                        MaxLength = 100
                    };
                    break;

                default:
                    throw new ArgumentException(string.Format("Unexpected attribute type: {0}", type));
                }

                // Set base properties
                attribute.SchemaName    = logicalname;
                attribute.DisplayName   = new Label(displayname, languageCode);
                attribute.RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredlevel);
            }

            return(attribute);
        }
 public IntegerAttributeMetadataInfo(IntegerAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
        public void CreateCRMAttribute(DataRow record)
        {
            string result = string.Empty;

            try
            {
                #region # Read From Datatable #
                AttributeMetadata createMetadata = new AttributeMetadata();
                bool isGlobal = false;
                AttributeRequiredLevel requirementLevel = AttributeRequiredLevel.None;
                string reqLevelText      = "";
                int    precisionSource   = 0;
                int    currencyPrecision = 2;
                if (record["RequiredLevel"] != null && !string.IsNullOrEmpty(Convert.ToString(record["RequiredLevel"])))
                {
                    reqLevelText     = Convert.ToString(record["RequiredLevel"]).ToLower();
                    requirementLevel = reqLevelText == "required" ? AttributeRequiredLevel.ApplicationRequired : AttributeRequiredLevel.Recommended;
                }
                reqLevelText = record["Attribute Type"].ToString().ToLower();
                string attributeSchemaName  = record["Attribute Schema Name"].ToString().ToLower();
                string optionSetValues      = record["Option Set Values"].ToString().ToLower();
                string attributeDisplayName = record["Attribute Display Name"].ToString().ToLower();
                string attributeDiscription = record["Description"].ToString().ToLower();
                bool   boolDefaultValue     = record["Default  Value"].ToString().ToLower() == "yes"?true:false;

                Microsoft.Xrm.Sdk.Metadata.StringFormat stringFormat = GetStringFormat(record["String Format"].ToString().ToLower());
                int stringLength = record["String Length"] != null && !string.IsNullOrEmpty(Convert.ToString(record["String Length"])) && Convert.ToInt32(record["String Length"].ToString()) <= 4000? Convert.ToInt32(record["String Length"].ToString()) : 4000;

                Microsoft.Xrm.Sdk.Metadata.DateTimeFormat dateFormat   = record["Date Type Format"] != null && !string.IsNullOrEmpty(record["Date Type Format"].ToString()) ? GetDateFormat(record["Date Type Format"].ToString().ToLower()):DateTimeFormat.DateAndTime;
                Microsoft.Xrm.Sdk.Metadata.IntegerFormat  integerFormt = record["Integer Format"] != null && !string.IsNullOrEmpty(record["Integer Format"].ToString()) ? GetIntegerFormat(record["Integer Format"].ToString().ToLower()) : IntegerFormat.None;

                Double intMinValue = record["Integer Minimum Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Integer Minimum Value"])) && Convert.ToDouble(record["Integer Minimum Value"].ToString()) <= 2147483647 && Convert.ToDouble(record["Integer Minimum Value"].ToString()) >= -2147483647 ? Convert.ToDouble(record["Integer Minimum Value"].ToString()) : -2147483648;
                Double intMaxValue = record["Integer Maximum Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Integer Maximum Value"])) && Convert.ToDouble(record["Integer Maximum Value"].ToString()) <= 2147483647 && Convert.ToDouble(record["Integer Maximum Value"].ToString()) >= -2147483647 ? Convert.ToDouble(record["Integer Maximum Value"].ToString()) : 2147483647;

                int    floatingPrecision = record["Floating Number Precision"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Floating Number Precision"])) ? Convert.ToInt32(record["Floating Number Precision"].ToString()) : 2;
                Double floatMinValue     = record["Float Min Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Float Min Value"])) && Convert.ToDouble(record["Float Min Value"].ToString()) >= 0 && Convert.ToDouble(record["Float Min Value"].ToString()) <= 1000000000 ? Convert.ToDouble(record["Float Min Value"].ToString()) : 0;
                Double floatMaxValue     = record["Float Max Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Float Max Value"])) && Convert.ToDouble(record["Float Max Value"].ToString()) >= 0 && Convert.ToDouble(record["Float Max Value"].ToString()) <= 1000000000 ? Convert.ToDouble(record["Float Max Value"].ToString()) : 1000000000;

                int     decimalPrecision = record["Decimal Precision"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Decimal Precision"])) ? Convert.ToInt32(record["Decimal Precision"].ToString()) : 2;
                Decimal decimalMinValue  = record["Decimal Min Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Decimal Min Value"])) && Convert.ToDecimal(record["Decimal Min Value"].ToString()) >= -100000000000 && Convert.ToDecimal(record["Decimal Min Value"].ToString()) <= 100000000000 ? Convert.ToDecimal(record["Decimal Min Value"].ToString()) : -100000000000;
                Decimal decimalMaxValue  = record["Decimsl Max Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Decimsl Max Value"])) && Convert.ToDecimal(record["Decimsl Max Value"].ToString()) >= -100000000000 && Convert.ToDecimal(record["Decimsl Max Value"].ToString()) <= 100000000000 ? Convert.ToDecimal(record["Decimsl Max Value"].ToString()) : 100000000000;

                Double currencyMinValue = record["Currency Min Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Currency Min Value"])) && Convert.ToDouble(record["Currency Min Value"].ToString()) >= -922337203685477 && Convert.ToDouble(record["Currency Min Value"].ToString()) <= 922337203685477 ? Convert.ToDouble(record["Currency Min Value"].ToString()) : -922337203685477;
                Double currencyMaxValue = record["Currency Max Value"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Currency Max Value"])) && Convert.ToDouble(record["Currency Max Value"].ToString()) >= -922337203685477 && Convert.ToDouble(record["Currency Max Value"].ToString()) <= 922337203685477 ? Convert.ToDouble(record["Currency Max Value"].ToString()) : 922337203685477;

                Microsoft.Xrm.Sdk.Metadata.ImeMode imeMode = GetIMEMode(record["IME Mode"].ToString().ToLower());

                if (record["Currency precision"] != null && !string.IsNullOrEmpty(Convert.ToString(record["Currency precision"]).ToLower()))
                {
                    switch (Convert.ToString(record["Currency precision"]).ToLower().Trim())
                    {
                    case "pricing decimal precision":
                        precisionSource = 1;
                        break;

                    case "currency precision":
                        precisionSource = 2;
                        break;

                    default:
                        currencyPrecision = Convert.ToInt32(Convert.ToString(record["Currency precision"]));
                        break;
                    }
                }

                bool isAuditEnabled       = record["AuditEnable"] != null && record["AuditEnable"].ToString().ToLower() == "yes" ? true : false;
                bool isValidForAdvancFind = record["IsValidForAdvancedFind"] != null && record["IsValidForAdvancedFind"].ToString().ToLower() == "yes" ? true : false;
                #endregion # Read From Datatable #

                switch (reqLevelText.ToLower().Trim())
                {
                case "boolean":
                    // Create a boolean attribute
                    createMetadata = new BooleanAttributeMetadata
                    {
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        // Set extended properties
                        OptionSet = new BooleanOptionSetMetadata(
                            new OptionMetadata(new Microsoft.Xrm.Sdk.Label("Yes", _languageCode), 1),
                            new OptionMetadata(new Microsoft.Xrm.Sdk.Label("No", _languageCode), 0)
                            ),
                        DefaultValue           = boolDefaultValue,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                    };
                    break;

                case "date and time":
                    createMetadata = new DateTimeAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        // Set extended properties
                        Format                 = dateFormat,
                        ImeMode                = imeMode,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                    };
                    break;

                case "multiple line of text":
                    createMetadata = new MemoAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        // Set extended properties
                        ImeMode                = imeMode,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                        MaxLength              = stringLength
                    };
                    break;

                case "whole number":
                    createMetadata = new IntegerAttributeMetadata
                    {
                        // Set base properties
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        // Set extended properties
                        // ImeMode = imeMode,// in crm 2016 ths feature is there
                        // Set extended properties
                        Format                 = IntegerFormat.None,
                        MaxValue               = Convert.ToInt32(intMaxValue),
                        MinValue               = Convert.ToInt32(intMinValue),
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind)
                    };
                    break;

                case "floating point number":
                    createMetadata = new DoubleAttributeMetadata
                    {
                        SchemaName             = attributeSchemaName,
                        DisplayName            = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel          = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description            = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        MaxValue               = floatMaxValue,
                        MinValue               = floatMinValue,
                        Precision              = floatingPrecision,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                        ImeMode = imeMode
                    };
                    break;

                case "decimal number":
                    createMetadata = new DecimalAttributeMetadata
                    {
                        SchemaName             = attributeSchemaName,
                        DisplayName            = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel          = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description            = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        MaxValue               = decimalMaxValue,
                        MinValue               = decimalMinValue,
                        Precision              = decimalPrecision,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                        ImeMode = imeMode
                    };
                    break;

                case "currency":
                    createMetadata = new MoneyAttributeMetadata
                    {
                        SchemaName      = attributeSchemaName,
                        DisplayName     = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel   = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description     = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        MaxValue        = currencyMaxValue,
                        MinValue        = currencyMinValue,
                        Precision       = currencyPrecision,
                        PrecisionSource = precisionSource,
                        ImeMode         = imeMode
                    };
                    break;

                case "option set":

                    OptionMetadataCollection optionMetadataCollection = GetOptionMetadata(optionSetValues);
                    OptionSetMetadata        Optionmedata             = new OptionSetMetadata();
                    if (optionMetadataCollection != null && optionMetadataCollection.Count() > 0)
                    {
                        Optionmedata.Options.AddRange(optionMetadataCollection);
                    }
                    Optionmedata.IsGlobal      = isGlobal;
                    Optionmedata.OptionSetType = OptionSetType.Picklist;

                    createMetadata = new PicklistAttributeMetadata
                    {
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        OptionSet     = Optionmedata
                    };
                    break;

                case "single line of text":
                    createMetadata = new StringAttributeMetadata
                    {
                        SchemaName    = attributeSchemaName,
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(attributeDisplayName, _languageCode),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(requirementLevel),
                        Description   = new Microsoft.Xrm.Sdk.Label(attributeDiscription, _languageCode),
                        // Set extended properties
                        ImeMode                = imeMode,
                        IsAuditEnabled         = new BooleanManagedProperty(isAuditEnabled),
                        IsValidForAdvancedFind = new BooleanManagedProperty(isValidForAdvancFind),
                        MaxLength              = stringLength
                    };
                    break;
                }
                CreateAttributeRequest request = new CreateAttributeRequest
                {
                    Attribute  = createMetadata,
                    EntityName = ApplicationSetting.SelectedEntity.LogicalName
                };
                try
                {
                    Service.Execute(request);
                    result = "Success";
                }
                catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    result = ex.Message;
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
        }
Example #23
0
        public static AttributeMetadata SetMetadataType(string type, string prefix, string name)
        {
            AttributeMetadata value = new AttributeMetadata();

            switch (type)
            {
            case "Single Line of Text":
                value = new StringAttributeMetadata();
                ((StringAttributeMetadata)value).Format    = Microsoft.Xrm.Sdk.Metadata.StringFormat.Text;
                ((StringAttributeMetadata)value).MaxLength = 100;
                break;

            case "Two Options":
                value = new BooleanAttributeMetadata();
                ((BooleanAttributeMetadata)value).OptionSet = new BooleanOptionSetMetadata(new OptionMetadata(
                                                                                               new Microsoft.Xrm.Sdk.Label("Yes", 1033), 10000),
                                                                                           new OptionMetadata(new Microsoft.Xrm.Sdk.Label("No", 1033), 10001));
                ((BooleanAttributeMetadata)value).DefaultValue = false;
                break;

            case "Whole Number":
                value = new IntegerAttributeMetadata();
                ((IntegerAttributeMetadata)value).Format   = Microsoft.Xrm.Sdk.Metadata.IntegerFormat.None;
                ((IntegerAttributeMetadata)value).MinValue = -2147483648;
                ((IntegerAttributeMetadata)value).MaxValue = 2147483647;
                break;

            case "Floating Point Number":
                value = new DoubleAttributeMetadata();
                ((DoubleAttributeMetadata)value).Precision = 2;
                ((DoubleAttributeMetadata)value).MinValue  = 0.00;
                ((DoubleAttributeMetadata)value).MaxValue  = 1000000000.00;
                break;

            case "Decimal Number":
                value = new DecimalAttributeMetadata();
                ((DecimalAttributeMetadata)value).Precision = 2;
                ((DecimalAttributeMetadata)value).MinValue  = (decimal)0.00;
                ((DecimalAttributeMetadata)value).MaxValue  = (decimal)1000000000.00;
                break;

            case "Currency":
                value = new MoneyAttributeMetadata();
                ((MoneyAttributeMetadata)value).Precision       = 4;
                ((MoneyAttributeMetadata)value).PrecisionSource = 2;
                ((MoneyAttributeMetadata)value).MinValue        = 0.0000;
                ((MoneyAttributeMetadata)value).MaxValue        = 1000000000.0000;
                break;

            case "Multiple Lines of Text":
                value = new MemoAttributeMetadata();
                ((MemoAttributeMetadata)value).MaxLength = 2000;
                break;

            case "Date and Time":
                value = new DateTimeAttributeMetadata();
                ((DateTimeAttributeMetadata)value).Format = Microsoft.Xrm.Sdk.Metadata.DateTimeFormat.DateOnly;
                break;
            }
            value.SchemaName     = prefix + "_" + name.ToLower();
            value.DisplayName    = new Microsoft.Xrm.Sdk.Label(name, 1033);
            value.IsAuditEnabled = new BooleanManagedProperty(true);
            return(value);
        }
Example #24
0
        public void CreateAttribute(CrmServiceClient service, string entityname, List <DxEntityAttribute> entityAttributes)
        {
            #region Attribute Metadata
            StringAttributeMetadata   dxStringAttributeMetadata   = null;
            DecimalAttributeMetadata  dxDecimalAttributeMetadata  = null;
            IntegerAttributeMetadata  dxIntegerAttributeMetadata  = null;
            MoneyAttributeMetadata    dxMoneyAttributeMetadata    = null;
            DateTimeAttributeMetadata dxDateTimeAttributeMetadata = null;
            #endregion
            AttributeMetadata attributeMetadata = null;

            foreach (DxEntityAttribute dxEntityAttribute in entityAttributes)
            {
                switch (dxEntityAttribute.PType)
                {
                case 1:
                    dxStringAttributeMetadata = new StringAttributeMetadata
                    {
                        SchemaName = String.Format("{0}_{1}", entityname.Substring(0, entityname.IndexOf("_")),
                                                   dxEntityAttribute.PSchemaName.ToLower().Trim()),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                        MaxLength     = dxEntityAttribute.StringAttribute.PMaxLength,
                        FormatName    = dxEntityAttribute.StringAttribute.PStringFormatName,
                        DisplayName   =
                            new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDisplayName, 3082),
                        Description =
                            new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDescription, 3082),
                    };
                    attributeMetadata = dxStringAttributeMetadata;
                    break;

                case 2:
                    dxDecimalAttributeMetadata = new DecimalAttributeMetadata
                    {
                        SchemaName = String.Format("{0}_{1}", entityname.Substring(0, entityname.IndexOf("_")),
                                                   dxEntityAttribute.PSchemaName.ToLower().Trim()),
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDisplayName, 3082),
                        Description   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDescription, 3082),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                        MaxValue  = dxEntityAttribute.DecimalAttribute.PMaxValue,
                        MinValue  = dxEntityAttribute.DecimalAttribute.PMinValue,
                        Precision = dxEntityAttribute.DecimalAttribute.PPrecision
                    };
                    attributeMetadata = dxDecimalAttributeMetadata;
                    break;

                case 3:
                    dxIntegerAttributeMetadata = new IntegerAttributeMetadata
                    {
                        SchemaName = String.Format("{0}_{1}", entityname.Substring(0, entityname.IndexOf("_")),
                                                   dxEntityAttribute.PSchemaName.ToLower().Trim()),
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDisplayName, 3082),
                        Description   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDescription, 3082),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                        MaxValue = dxEntityAttribute.IntegerAttribute.PMaxValue,
                        MinValue = dxEntityAttribute.IntegerAttribute.PMinValue,
                        Format   = dxEntityAttribute.IntegerAttribute.PFormat
                    };
                    attributeMetadata = dxIntegerAttributeMetadata;
                    break;

                case 4:
                    dxMoneyAttributeMetadata = new MoneyAttributeMetadata
                    {
                        SchemaName = String.Format("{0}_{1}", entityname.Substring(0, entityname.IndexOf("_")),
                                                   dxEntityAttribute.PSchemaName.ToLower().Trim()),
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDisplayName, 3082),
                        Description   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDescription, 3082),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                        MaxValue        = dxEntityAttribute.MoneyAttribute.PMaxValue,
                        MinValue        = dxEntityAttribute.MoneyAttribute.PMinValue,
                        Precision       = dxEntityAttribute.MoneyAttribute.PPrecision,
                        PrecisionSource = dxEntityAttribute.MoneyAttribute.PPrecisionSource,
                        ImeMode         = dxEntityAttribute.MoneyAttribute.PImeMode
                    };

                    attributeMetadata = dxMoneyAttributeMetadata;
                    break;

                case 5:
                    dxDateTimeAttributeMetadata = new DateTimeAttributeMetadata
                    {
                        SchemaName = String.Format("{0}_{1}", entityname.Substring(0, entityname.IndexOf("_")),
                                                   dxEntityAttribute.PSchemaName.ToLower().Trim()),
                        DisplayName   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDisplayName, 3082),
                        Description   = new Microsoft.Xrm.Sdk.Label(dxEntityAttribute.PDescription, 3082),
                        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

                        Format  = dxEntityAttribute.DateTimeAttribute.PFormat,
                        ImeMode = dxEntityAttribute.DateTimeAttribute.PImeMode
                    };
                    attributeMetadata = dxDateTimeAttributeMetadata;
                    break;
                }

                CreateAttributeRequest createBankNameAttributeRequest = new CreateAttributeRequest
                {
                    EntityName = entityname,
                    Attribute  = attributeMetadata,
                };

                service.OrganizationServiceProxy.Execute(createBankNameAttributeRequest);
            }
        }
        private IEnumerable <string> checkDifferenceAttributeMetadata(AttributeMetadata originalAttributeMetadata, AttributeMetadata readAttributeMetadata)
        {
            List <string> attributesToUpdate = checkGlobalDifferenceAttributeMetadata(originalAttributeMetadata, readAttributeMetadata);

            switch (originalAttributeMetadata.AttributeType)
            {
            case AttributeTypeCode.Integer:
                IntegerAttributeMetadata intattrMetadata = originalAttributeMetadata as IntegerAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceIntegerAttribute(intattrMetadata, readAttributeMetadata as IntegerAttributeMetadata));
                originalAttributeMetadata = intattrMetadata;
                break;

            case AttributeTypeCode.DateTime:
                DateTimeAttributeMetadata dateattrMetadata = originalAttributeMetadata as DateTimeAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDateTimeAttribute(dateattrMetadata, readAttributeMetadata as DateTimeAttributeMetadata));
                originalAttributeMetadata = dateattrMetadata;
                break;

            case AttributeTypeCode.String:
                StringAttributeMetadata strattrMetadata = originalAttributeMetadata as StringAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceStringAttribute(strattrMetadata, readAttributeMetadata as StringAttributeMetadata));
                originalAttributeMetadata = strattrMetadata;
                break;

            case AttributeTypeCode.Picklist:
                PicklistAttributeMetadata pklattrMetadata = originalAttributeMetadata as PicklistAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferencePicklistAttribute(pklattrMetadata, readAttributeMetadata as PicklistAttributeMetadata));
                originalAttributeMetadata = pklattrMetadata;
                break;

            case AttributeTypeCode.Memo:
                MemoAttributeMetadata memattrMetadata = originalAttributeMetadata as MemoAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceMemoAttribute(memattrMetadata, readAttributeMetadata as MemoAttributeMetadata));
                originalAttributeMetadata = memattrMetadata;
                break;

            case AttributeTypeCode.Double:
                DoubleAttributeMetadata dblattrMetadata = originalAttributeMetadata as DoubleAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDoubleAttribute(dblattrMetadata, readAttributeMetadata as DoubleAttributeMetadata));
                originalAttributeMetadata = dblattrMetadata;
                break;

            case AttributeTypeCode.Decimal:
                DecimalAttributeMetadata dcmattrMetadata = originalAttributeMetadata as DecimalAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceDecimalAttribute(dcmattrMetadata, readAttributeMetadata as DecimalAttributeMetadata));
                originalAttributeMetadata = dcmattrMetadata;
                break;

            case AttributeTypeCode.Boolean:
                BooleanAttributeMetadata blnattrMetadata = originalAttributeMetadata as BooleanAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceBooleanAttribute(blnattrMetadata, readAttributeMetadata as BooleanAttributeMetadata));
                originalAttributeMetadata = blnattrMetadata;
                break;

            case AttributeTypeCode.Money:
                MoneyAttributeMetadata mnyattrMetadata = originalAttributeMetadata as MoneyAttributeMetadata;
                attributesToUpdate.AddRange(checkDifferenceMoneyAttribute(mnyattrMetadata, readAttributeMetadata as MoneyAttributeMetadata));
                originalAttributeMetadata = mnyattrMetadata;
                break;
            }
            return(attributesToUpdate);
        }
Example #26
0
        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);
        }
 private IntegerAttributeMetadata CreateIntAttributeMetadata(AttributeTemplate attributeTemplate)
 {
     var integerAttributeMetadata = new IntegerAttributeMetadata
     {
         MinValue = attributeTemplate.MinLength == default(int)
             ? DefaultConfiguration.DefaultIntMinValue
             : attributeTemplate.MinLength,
         MaxValue = attributeTemplate.MaxLength == default(int)
             ? DefaultConfiguration.DefaultIntMaxValue
             : attributeTemplate.MaxLength,
         Format = attributeTemplate.IntegerFormat == default(IntegerFormat?)
             ? DefaultConfiguration.DefaultIntegerFormat
             : attributeTemplate.IntegerFormat
     };
     return integerAttributeMetadata;
 }
Example #28
0
        public void CreateOrUpdateIntegerAttribute(string schemaName, string displayName, string description,
            bool isRequired, bool audit, bool searchable,
            string recordType, int minimum, int maximum)
        {
            IntegerAttributeMetadata metadata;
            if (FieldExists(schemaName, recordType))
                metadata = (IntegerAttributeMetadata) GetFieldMetadata(schemaName, recordType);
            else
                metadata = new IntegerAttributeMetadata();

            SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable);

            metadata.MinValue = minimum;
            metadata.MaxValue = maximum;

            CreateOrUpdateAttribute(schemaName, recordType, metadata);
        }
 private static UpdateFormulaResponse UpdateInternal(IntegerAttributeMetadata  att, AttributeMetadata from, AttributeMetadata to) { return UpdateForumlaDefinition(att, from, to); }
 public IntegerAttributeMetadataInfo(IntegerAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
Example #31
0
 private static UpdateFormulaResponse UpdateInternal(IntegerAttributeMetadata att, AttributeMetadata from, AttributeMetadata to)
 {
     return(UpdateForumlaDefinition(att, from, to));
 }