private IEnumerable <string> checkDifferenceDoubleAttribute(DoubleAttributeMetadata originalAttributeMetadata, DoubleAttributeMetadata readAttributeMetadata)
        {
            List <string> attributeToChange = new List <string>();

            if (originalAttributeMetadata.Precision != readAttributeMetadata.Precision)
            {
                originalAttributeMetadata.Precision = readAttributeMetadata.Precision;
                attributeToChange.Add("Precision");
            }
            if (originalAttributeMetadata.MinValue != readAttributeMetadata.MinValue)
            {
                originalAttributeMetadata.MinValue = readAttributeMetadata.MinValue;
                attributeToChange.Add("Min Value");
            }
            if (originalAttributeMetadata.MaxValue != readAttributeMetadata.MaxValue)
            {
                originalAttributeMetadata.MaxValue = readAttributeMetadata.MaxValue;
                attributeToChange.Add("Max Value");
            }
            if (originalAttributeMetadata.ImeMode != readAttributeMetadata.ImeMode)
            {
                originalAttributeMetadata.ImeMode = readAttributeMetadata.ImeMode;
                attributeToChange.Add("ImeMode");
            }
            return(attributeToChange);
        }
        public void HandleObfuscation(Entity entity, FieldToBeObfuscated field, IEntityMetadataCache metaData)
        {
            entity.ThrowArgumentNullExceptionIfNull(nameof(entity));
            field.ThrowArgumentNullExceptionIfNull(nameof(field));
            metaData.ThrowArgumentNullExceptionIfNull(nameof(metaData));

            // Get the min and maximum values for the field using the meta data cache
            DoubleAttributeMetadata doubleMetaData = (DoubleAttributeMetadata)metaData.GetAttribute(entity.LogicalName, field.FieldName);

            int min = (int)doubleMetaData.MinValue.GetValueOrDefault(0);
            int max = (int)doubleMetaData.MaxValue.GetValueOrDefault(10);

            if (field.CanBeFormatted)
            {
                Dictionary <string, object> metadataParameters = new Dictionary <string, object>
                {
                    { "min", min },
                    { "max", max }
                };

                entity[field.FieldName] = formattingClient.CreateFormattedValue((double)entity[field.FieldName], field, metadataParameters);
                return;
            }

            entity[field.FieldName] = doubleScramblerClient.ExecuteScramble((double)entity[field.FieldName], min, max);
        }
        /// <summary>
        /// Sets the double max size and max and min values, according to the specified sql precision and scale arguments.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static bool SetFromSqlPrecisionAndScale(this DoubleAttributeMetadata metadata, int precision, int scale)
        {
            if (precision < scale)
            {
                throw new ArgumentOutOfRangeException("precision must be equal to or greater than scale.");
            }

            if (scale < DoubleAttributeMetadata.MinSupportedPrecision || scale > DoubleAttributeMetadata.MaxSupportedPrecision)
            {
                throw new ArgumentOutOfRangeException("scale is not within min and max crm values.");
            }

            var crmMaxValueLengthWithoutPrecision = Math.Max(Math.Truncate(Math.Abs(DoubleAttributeMetadata.MaxSupportedValue)).ToString().Length, Math.Truncate(Math.Abs(DoubleAttributeMetadata.MinSupportedValue)).ToString().Length);

            if (precision - scale > crmMaxValueLengthWithoutPrecision)
            {
                throw new ArgumentOutOfRangeException("The precision is greater than the maximum value crm will allow.");
            }

            metadata.Precision = scale;

            // need to set appropriate min and max values.
            // If the precision is equal to the max precision allowed, then set min and max values allowed.
            if (precision == crmMaxValueLengthWithoutPrecision)
            {
                metadata.MinValue = (double)DoubleAttributeMetadata.MinSupportedValue;
                metadata.MaxValue = (double)DoubleAttributeMetadata.MaxSupportedValue;
            }
            else
            {
                // the min value should be a series of 9's to the specified precision and scale.
                var maxNumberBuilder = new StringBuilder();
                for (int i = 0; i < precision - scale; i++)
                {
                    maxNumberBuilder.Append("9");
                }
                if (scale > 0)
                {
                    maxNumberBuilder.Append(".");
                    for (int i = 0; i < scale; i++)
                    {
                        maxNumberBuilder.Append("9");
                    }
                }

                double maxNumber;
                if (!double.TryParse(maxNumberBuilder.ToString(), out maxNumber))
                {
                    throw new FormatException(string.Format("Unable to parse {0} as a double.", maxNumberBuilder.ToString()));
                }

                metadata.MaxValue = maxNumber;
                metadata.MinValue = -maxNumber;
            }

            return(true);
        }
 private object CopyValueInternal(AttributeMetadata oldAttribute, DoubleAttributeMetadata newAttribute, object value)
 {
     double output;
     if (double.TryParse(value.ToString(), out output))
     {
         return output;
     }
     Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double");
     return null;
 }
Exemple #5
0
 private AttributeMetadata CloneAttributes(DoubleAttributeMetadata att)
 {
     return(new DoubleAttributeMetadata
     {
         ImeMode = att.ImeMode,
         MaxValue = att.MaxValue,
         MinValue = att.MinValue,
         Precision = att.Precision
     });
 }
Exemple #6
0
        private AttributeMetadata CreateFloatAttribute(ExcelWorksheet sheet, int rowIndex, int startCell)
        {
            var famd = new DoubleAttributeMetadata
            {
                Precision = sheet.GetValue <int>(rowIndex, startCell),
                MinValue  = sheet.GetValue <double>(rowIndex, startCell + 1),
                MaxValue  = sheet.GetValue <double>(rowIndex, startCell + 2)
            };

            return(famd);
        }
        private object CopyValueInternal(AttributeMetadata oldAttribute, DoubleAttributeMetadata newAttribute, object value)
        {
            double output;

            if (double.TryParse(value.ToString(), out output))
            {
                return(output);
            }
            Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double");
            return(null);
        }
        private object CopyValueInternal(AttributeMetadata oldAttribute, DoubleAttributeMetadata newAttribute, object value, Dictionary <string, string> migrationMapping)
        {
            var copy = value.ToString();

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

            if (double.TryParse(copy, out var output))
            {
                return(output);
            }
            Trace("Unable to convert value \"" + value + "\" of type \"" + value.GetType().Name + "\" to Double");
            return(null);
        }
        private AttributeMetadata doubleFieldCreation(string[] row)
        {
            DoubleAttributeMetadata attrMetadata = new DoubleAttributeMetadata(Utils.addOrgPrefix(row[ExcelColumsDefinition.SCHEMANAMEEXCELCOL], organizationPrefix, currentOperationCreate));

            generalFieldCreation(row, attrMetadata);
            double doubleResult;
            int    parseResult;

            attrMetadata.Precision = int.TryParse(row[ExcelColumsDefinition.DOUBLEPRECISION], out parseResult) ? parseResult : (int?)null;
            attrMetadata.MaxValue  = double.TryParse(row[ExcelColumsDefinition.DOUBLEMAXVALUE], out doubleResult) ? doubleResult : (double?)null;
            attrMetadata.MinValue  = double.TryParse(row[ExcelColumsDefinition.DOUBLEMINVALUE], out doubleResult) ? doubleResult : (double?)null;
            string imeModeFormatString = row[ExcelColumsDefinition.DOUBLEIMEMODE];

            attrMetadata.ImeMode = Enum.IsDefined(typeof(ImeMode), imeModeFormatString) ? (ImeMode)Enum.Parse(typeof(ImeMode), imeModeFormatString, true) : (ImeMode?)null;
            return(attrMetadata);
        }
        private DoubleAttributeMetadata BuildCreateFloatAttribute()
        {
            var doubleAttribute = new DoubleAttributeMetadata();
            int doublePrecision = doubleAttribute.DefaultSqlPrecision();
            int doubleScale     = doubleAttribute.DefaultSqlScale();
            var dataType        = this.CurrentColumnDefinition.DataType;

            if (dataType.Arguments != null && dataType.Arguments.Any())
            {
                // first is scale, second is precision.
                var argsCount = dataType.Arguments.Count();
                if (argsCount > 2)
                {
                    throw new InvalidOperationException("Datatype can have a maximum of 2 size arguments.");
                }

                if (argsCount >= 1)
                {
                    var sqlPrecisionArg = dataType.Arguments.First();
                    ((IVisitableBuilder)sqlPrecisionArg).Accept(this);
                    if (CurrentNumericLiteralValue != null)
                    {
                        doublePrecision            = Convert.ToInt32(CurrentNumericLiteralValue);
                        CurrentNumericLiteralValue = null;
                    }
                }

                if (argsCount >= 2)
                {
                    int?sqlScale    = null;
                    var sqlScaleArg = dataType.Arguments.Skip(1).Take(1).Single();
                    ((IVisitableBuilder)sqlScaleArg).Accept(this);
                    if (CurrentNumericLiteralValue != null)
                    {
                        sqlScale = Convert.ToInt32(CurrentNumericLiteralValue);
                        CurrentNumericLiteralValue = null;
                    }
                    doubleScale = sqlScale.Value;
                }
            }

            doubleAttribute.SetFromSqlPrecisionAndScale(doublePrecision, doubleScale);
            return(doubleAttribute);
        }
        /// <summary>
        /// Gets the sql precision for the crm double attribute.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static bool IsSqlPrecisionSupported(this DoubleAttributeMetadata metadata, int precision, int scale)
        {
            if (precision < scale)
            {
                throw new ArgumentOutOfRangeException("precision must be equal to or greater than scale.");
            }

            if (scale < DoubleAttributeMetadata.MinSupportedPrecision || scale > DoubleAttributeMetadata.MaxSupportedPrecision)
            {
                return(false);
            }
            int crmMaxValueLengthWithoutPrecision = Math.Max(DoubleAttributeMetadata.MinSupportedValue.ToString().Length, DoubleAttributeMetadata.MaxSupportedValue.ToString().Length);

            if (precision - scale > crmMaxValueLengthWithoutPrecision)
            {
                return(false);
            }
            return(true);
        }
        protected override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            DoubleAttributeMetadata attribute = new DoubleAttributeMetadata();

            if (ImeType.HasValue)
            {
                attribute.ImeMode = ImeMode.Auto;
                if (ImeType == CrmImeType.Active)
                {
                    attribute.ImeMode = ImeMode.Active;
                }
                if (ImeType == CrmImeType.Disabled)
                {
                    attribute.ImeMode = ImeMode.Disabled;
                }
                if (ImeType == CrmImeType.Inactive)
                {
                    attribute.ImeMode = ImeMode.Inactive;
                }
            }

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

            WriteAttribute(attribute);
        }
Exemple #13
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);
        }
        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;
            }
        }
        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);
        }
        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);
        }
        /// <summary>
        /// Gets the default sql scale for the crm double attribute.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static int DefaultSqlScale(this DoubleAttributeMetadata metadata)
        {
            int scale = DoubleAttributeMetadata.MinSupportedPrecision;

            return(scale);
        }
 public DoubleAttributeMetadataInfo(DoubleAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
        /// <summary>
        /// Gets the default sql precision for the crm double attribute.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static int DefaultSqlPrecision(this DoubleAttributeMetadata metadata)
        {
            var precision = Math.Max(Math.Truncate(Math.Abs(DoubleAttributeMetadata.MaxSupportedValue)).ToString().Length, Math.Truncate(Math.Abs(DoubleAttributeMetadata.MinSupportedValue)).ToString().Length);

            return(precision + DefaultSqlScale(metadata));
        }
 public DoubleAttributeMetadataInfo(DoubleAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
        /// <summary>
        /// Gets the sql precision for the crm double attribute.
        /// </summary>
        /// <param name="metadata"></param>
        /// <returns></returns>
        public static int MaxSupportedSqlPrecision(this DoubleAttributeMetadata metadata)
        {
            var crmPrecision = Math.Max(Math.Truncate(Math.Abs(DoubleAttributeMetadata.MaxSupportedValue)).ToString().Length, Math.Truncate(Math.Abs(DoubleAttributeMetadata.MinSupportedValue)).ToString().Length);

            return(crmPrecision + DoubleAttributeMetadata.MaxSupportedPrecision);
        }
        private DoubleAttributeMetadata CreateFloatAttributeMetadata(AttributeTemplate attributeTemplate)
        {
            var floatAttributeMetadata = new DoubleAttributeMetadata
            {
                MinValue = -100000000000.00,
                MaxValue = 100000000000.00,
                Precision = 2
            };

            return floatAttributeMetadata;
        }
 private AttributeMetadata CloneAttributes(DoubleAttributeMetadata att)
 {
     return new DoubleAttributeMetadata
     {
         ImeMode = att.ImeMode,
         MaxValue = att.MaxValue,
         MinValue = att.MinValue,
         Precision = att.Precision
     };
 }