private static DateTimeFormat GetDateFormat(string dateFormat)
        {
            Microsoft.Xrm.Sdk.Metadata.DateTimeFormat format = Microsoft.Xrm.Sdk.Metadata.DateTimeFormat.DateAndTime;
            switch (dateFormat)
            {
            case "date only":
                format = Microsoft.Xrm.Sdk.Metadata.DateTimeFormat.DateOnly;
                break;

            case "date and time":
                format = Microsoft.Xrm.Sdk.Metadata.DateTimeFormat.DateAndTime;
                break;
            }
            return(format);
        }
        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;
            }
        }
        protected void ConvertToEntityRecord(Entity entity, EntityMetadata entityMetadata = null, OrganizationServiceContext serviceContext = null, OrganizationMoneyFormatInfo organizationMoneyFormatInfo = null, int?crmLcid = null)
        {
            var recordAttributes    = new List <EntityRecordAttribute>();
            var attributes          = entity.Attributes;
            var formattedAttributes = entity.FormattedValues;

            if (serviceContext == null)
            {
                serviceContext = PortalCrmConfigurationManager.CreateServiceContext();
            }

            organizationMoneyFormatInfo = organizationMoneyFormatInfo ?? new OrganizationMoneyFormatInfo(serviceContext);
            var recordMoneyFormatInfo = new EntityRecordMoneyFormatInfo(serviceContext, entity);

            foreach (var attribute in attributes)
            {
                var               aliasedValue      = attribute.Value as AliasedValue;
                var               value             = aliasedValue != null ? aliasedValue.Value : attribute.Value;
                var               type              = value.GetType().ToString();
                var               formattedValue    = string.Empty;
                var               displayValue      = value;
                DateTimeFormat    format            = DateTimeFormat.DateAndTime;
                DateTimeBehavior  behavior          = null;
                AttributeMetadata attributeMetadata = null;

                if (formattedAttributes.Contains(attribute.Key))
                {
                    formattedValue = formattedAttributes[attribute.Key];
                    displayValue   = formattedValue;
                }

                if (aliasedValue != null)
                {
                    var aliasedEntityMetadata = serviceContext.GetEntityMetadata(aliasedValue.EntityLogicalName, EntityFilters.Attributes);

                    if (aliasedEntityMetadata != null)
                    {
                        attributeMetadata = aliasedEntityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == aliasedValue.AttributeLogicalName);
                    }
                }
                else
                {
                    if (entityMetadata != null)
                    {
                        attributeMetadata = entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute.Key);
                    }
                }

                if (attributeMetadata != null)
                {
                    switch (attributeMetadata.AttributeType)
                    {
                    case AttributeTypeCode.State:
                    case AttributeTypeCode.Status:
                    case AttributeTypeCode.Picklist:
                        var optionSetValue = (OptionSetValue)value;
                        formattedValue = Adxstudio.Xrm.Core.OrganizationServiceContextExtensions.GetOptionSetValueLabel(attributeMetadata,
                                                                                                                        optionSetValue.Value, crmLcid.GetValueOrDefault(CultureInfo.CurrentCulture.LCID));
                        displayValue = formattedValue;
                        break;

                    case AttributeTypeCode.Customer:
                    case AttributeTypeCode.Lookup:
                    case AttributeTypeCode.Owner:
                        var entityReference = value as EntityReference;
                        if (entityReference != null)
                        {
                            displayValue = entityReference.Name ?? string.Empty;
                        }
                        break;

                    case AttributeTypeCode.DateTime:
                        var datetimeAttributeMetadata = attributeMetadata as DateTimeAttributeMetadata;
                        behavior = datetimeAttributeMetadata.DateTimeBehavior;
                        format   = datetimeAttributeMetadata.Format.GetValueOrDefault(DateTimeFormat.DateAndTime);
                        if (datetimeAttributeMetadata != null)
                        {
                            if (format != DateTimeFormat.DateOnly && behavior == DateTimeBehavior.UserLocal)
                            {
                                // Don't use the formatted value, as the connection user's timezone is used to format the datetime value. Use the UTC value for display.
                                var date = (DateTime)value;
                                displayValue = date.ToString(DateTimeClientFormat);
                            }
                            if (behavior == DateTimeBehavior.TimeZoneIndependent || behavior == DateTimeBehavior.DateOnly)
                            {
                                // JSON serialization converts the time from server local to UTC automatically
                                // to avoid this we can convert to UTC before serialization
                                value = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
                            }
                        }
                        break;

                    case AttributeTypeCode.BigInt:
                    case AttributeTypeCode.Integer:
                        displayValue = string.Format("{0}", value);
                        break;

                    case AttributeTypeCode.Decimal:
                        var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
                        if (decimalAttributeMetadata != null && value is decimal)
                        {
                            displayValue = ((decimal)value).ToString("N{0}".FormatWith(decimalAttributeMetadata.Precision.GetValueOrDefault(2)));
                        }
                        break;

                    case AttributeTypeCode.Money:
                        var moneyAttributeMetadata = attributeMetadata as MoneyAttributeMetadata;
                        if (moneyAttributeMetadata != null && value is Money)
                        {
                            var moneyFormatter = new MoneyFormatter(organizationMoneyFormatInfo, recordMoneyFormatInfo, moneyAttributeMetadata);

                            displayValue = string.Format(moneyFormatter, "{0}", (Money)value);
                        }
                        break;
                    }
                }
                else
                {
                    if (attribute.Value is EntityReference)
                    {
                        var entityReference = (EntityReference)attribute.Value;
                        if (entityReference != null)
                        {
                            displayValue = entityReference.Name ?? string.Empty;
                        }
                    }
                    else if (attribute.Value is DateTime)
                    {
                        format = DateTimeFormat.DateAndTime;
                        var dtAttributeValue = (DateTime)attribute.Value;
                        // Don't use the formatted value, as the connection user's timezone is used to format the datetime value. Use the UTC value for display.
                        if (dtAttributeValue.Kind == DateTimeKind.Utc)                         // Indicates this is not a date only attribute
                        {
                            var date = (DateTime)value;
                            displayValue = date.ToString(DateTimeClientFormat);
                            behavior     = DateTimeBehavior.UserLocal;
                        }
                        // This below logic fails in one condition: when DateTimeBehavior = TimeZoneIndependent and DateTimeFormat = DateAndTime with value having ex: 20-01-2017 12:00 AM
                        else if (dtAttributeValue.TimeOfDay.TotalSeconds == 0)
                        {
                            behavior = DateTimeBehavior.DateOnly;
                            format   = DateTimeFormat.DateOnly;
                            value    = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
                        }
                        else
                        {
                            behavior = DateTimeBehavior.TimeZoneIndependent;
                            // JSON serialization converts the time from server local to UTC automatically
                            // to avoid this we can convert to UTC before serialization
                            value = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
                        }
                    }
                }

                recordAttributes.Add(new EntityRecordAttribute
                {
                    Name              = attribute.Key,
                    Value             = value,
                    FormattedValue    = formattedValue,
                    DisplayValue      = displayValue,
                    DateTimeBehavior  = behavior,
                    DateTimeFormat    = format.ToString(),
                    Type              = type,
                    AttributeMetadata = attributeMetadata
                });
            }

            Id         = entity.Id;
            EntityName = entity.LogicalName;
            Attributes = recordAttributes;
        }