public DateTimeBehaviorAttribute(DateTimeBehavior behavior)
 {
     Behavior = behavior;
 }
        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;
        }
Exemple #3
0
        protected virtual async Task <DateTimeBehavior> GetDateTimeBehaviorAttributeAsync(string entityLogicalName,
                                                                                          string attributeLogicalName)
        {
            _logger.LogDebug("Starting {WebApiOperationName} {Entity}.{Attribute}",
                             "GetDateTimeBehavior",
                             entityLogicalName,
                             attributeLogicalName);

            var watch = Stopwatch.StartNew();

            // TODO: FIXME - Direct build query with out extensions used WebApiMetadata for disable IoC loop!!!
            //var query = string.Format(CultureInfo.InvariantCulture, CheckAttributeDateOnlyRequest, entityLogicalName,
            //    attributeLogicalName);

            var request = new OrganizationRequest <JObject>()
            {
                RequestBindingPath =
                    $"EntityDefinitions(LogicalName='{entityLogicalName}')/Attributes(LogicalName='{attributeLogicalName}')/Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",

                Parameters =
                {
                    // {"$select", "LogicalName,Format,DateTimeBehavior"},
                    { "$select", "LogicalName,Format,DateTimeBehavior" },
                    // {
                    //     "$filter",
                    //     "DateTimeBehavior ne null and Format eq Microsoft.Dynamics.CRM.DateTimeFormat'DateOnly'"
                    // }
                }
            };

            DateTimeBehavior behavior = default;

            try
            {
                var result = await GetCrmClient()
                             .ExecuteAsync(request, CancellationToken.None)
                             .ConfigureAwait(false);

                var stringValue = result["DateTimeBehavior"]?["Value"]?.ToString();
                if (Enum.TryParse(typeof(DateTimeBehavior), stringValue, true, out var parsedValue))
                {
                    behavior = (DateTimeBehavior)parsedValue;
                }
            }
            catch (Exception)
            {
                throw;
            }
            // catch (WebApiException ex)
            // {
            //     // if (Equals(ex.StatusCode, HttpStatusCode.NotFound))
            //     // {
            //     //     isDateOnly = false;
            //     // }
            //     // else
            //     // {
            //     //     throw;
            //     // }
            // }
            finally
            {
                watch.Stop();
                _logger.LogInformation(
                    "Complete {WebApiOperationName} {EntityName}.{AttributeName} - {DateTimeBehavior} in {Elapsed:0.0} ms",
                    "GetDateTimeBehavior",
                    entityLogicalName, attributeLogicalName, behavior, watch.Elapsed.TotalMilliseconds);
            }

            return(behavior);
        }
Exemple #4
0
        ///////////////////////////////////////////////////////////////////////

        public static ReturnCode DataReaderToArray(
            Interpreter interpreter,
            IDataReader reader,
            string varName,
            DateTimeBehavior dateTimeBehavior,
            DateTimeKind dateTimeKind,
            string dateTimeFormat,
            string nullValue,
            int limit,
            bool allowNull,
            bool pairs,
            bool names,
            ref int count,
            ref Result error
            )
        {
            if (interpreter == null)
            {
                error = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (reader == null)
            {
                error = "invalid data reader";
                return(ReturnCode.Error);
            }

            ReturnCode code;

            //
            // NOTE: Make sure to reset the rows variable if it already exists.
            //
            bool   badRequest = false;
            Result localError = null;

            if (((interpreter.DoesVariableExist(
                      VariableFlags.NoElement, null, varName, ref badRequest,
                      ref localError) != ReturnCode.Ok) && !badRequest) ||
                (!badRequest && interpreter.ResetVariable(
                     VariableFlags.NoElement, varName,
                     ref error) == ReturnCode.Ok))
            {
                //
                // NOTE: Get the column names.
                //
                StringList nameList = null;

                GetDataReaderFieldNames(reader, false, ref nameList);

                //
                // NOTE: Create the script array variable by setting the
                //       columns names.
                //
                code = interpreter.SetVariableValue2(
                    VariableFlags.None, varName, Vars.ResultSet.Names,
                    nameList.ToString(), ref error);

                if (code == ReturnCode.Ok)
                {
                    //
                    // NOTE: This is incremented inside the loop prior to be
                    //       used as an array element index; therefore, we will
                    //       never have a row zero that contains valid data.
                    //
                    int rowIndex = 0;

                    //
                    // NOTE: Now, read the rows of data and populate the
                    //       rows array.
                    //
                    while (reader.Read())
                    {
                        //
                        // NOTE: This list will contain the column names and
                        //       values for this row.  Including the column
                        //       names here as well as in the header row helps
                        //       us to detect when a given column value is null
                        //       (missing) for a row and retains semantic
                        //       compatibility with the upcoming TDBC standard.
                        //
                        StringList nameValueList = null;

                        GetDataReaderFieldValues(
                            reader, dateTimeBehavior, dateTimeKind,
                            dateTimeFormat, nullValue, false, allowNull, pairs,
                            names, ref nameValueList);

                        rowIndex++;

                        code = interpreter.SetVariableValue2(
                            VariableFlags.None, varName, rowIndex.ToString(),
                            nameValueList.ToString(), ref error);

                        if (code != ReturnCode.Ok)
                        {
                            break;
                        }

                        //
                        // NOTE: Have we reached the limit for the number of
                        //       rows we want to return, if any?
                        //
                        if ((limit != 0) && (--limit == 0))
                        {
                            break;
                        }
                    }

                    //
                    // NOTE: If we succeeded, set the overall row count now
                    //       that we know what it is.
                    //
                    if (code == ReturnCode.Ok)
                    {
                        code = interpreter.SetVariableValue2(
                            VariableFlags.None, varName,
                            Vars.ResultSet.Count, rowIndex.ToString(),
                            ref error);

                        if (code == ReturnCode.Ok)
                        {
                            count = rowIndex;
                        }
                    }
                }
            }
            else
            {
                //
                // NOTE: The rows variable name is invalid (i.e. it refers
                //       to an array element) OR it already exists and we
                //       failed to reset it.
                //
                if (badRequest)
                {
                    error = localError;
                }

                code = ReturnCode.Error;
            }

            return(code);
        }
Exemple #5
0
        ///////////////////////////////////////////////////////////////////////

        public static ReturnCode DataReaderToList(
            Interpreter interpreter,
            IDataReader reader,
            DateTimeBehavior dateTimeBehavior,
            DateTimeKind dateTimeKind,
            string dateTimeFormat,
            string nullValue,
            int limit,
            bool nested,
            bool allowNull,
            bool pairs,
            bool names,
            ref StringList list,
            ref int count,
            ref Result error
            )
        {
            if (interpreter == null)
            {
                error = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (reader == null)
            {
                error = "invalid data reader";
                return(ReturnCode.Error);
            }

            //
            // NOTE: Now, read the rows of data and populate the
            //       rows array.
            //
            int localCount = 0;

            while (reader.Read())
            {
                localCount++;

                if (nested)
                {
                    //
                    // NOTE: Add the column values for this row to a new list
                    //       for this row only and then add list that entire
                    //       row list to the result list as one item.
                    //
                    StringList row = null;

                    GetDataReaderFieldValues(
                        reader, dateTimeBehavior, dateTimeKind, dateTimeFormat,
                        nullValue, false, allowNull, pairs, names, ref row);

                    if (list == null)
                    {
                        list = new StringList();
                    }

                    list.Add(row.ToString());
                }
                else
                {
                    //
                    // NOTE: Add the column values for this row directly
                    //       to the result list.
                    //
                    GetDataReaderFieldValues(
                        reader, dateTimeBehavior, dateTimeKind, dateTimeFormat,
                        nullValue, false, allowNull, pairs, names, ref list);
                }

                //
                // NOTE: Have we reached the limit for the number of rows we
                //       want to return, if any?
                //
                if ((limit != 0) && (--limit == 0))
                {
                    break;
                }
            }

            count = localCount;
            return(ReturnCode.Ok);
        }
Exemple #6
0
        ///////////////////////////////////////////////////////////////////////

        private static void GetDataReaderFieldValues(
            IDataReader reader,
            DateTimeBehavior dateTimeBehavior,
            DateTimeKind dateTimeKind,
            string dateTimeFormat,
            string nullValue,
            bool clear,
            bool allowNull,
            bool pairs,
            bool names,
            ref StringList list
            )
        {
            if (reader == null)
            {
                return;
            }

            int fieldCount = reader.FieldCount;

            if (clear || (list == null))
            {
                list = new StringList();
            }

            for (int index = 0; index < fieldCount; index++)
            {
                object value = reader.GetValue(index);

                if (allowNull ||
                    ((value != null) && (value != DBNull.Value)))
                {
                    if (pairs)
                    {
                        StringList element = new StringList();

                        if (names)
                        {
                            element.Add(reader.GetName(index));
                        }

                        element.Add(MarshalOps.FixupDataValue(
                                        value, dateTimeBehavior, dateTimeKind,
                                        dateTimeFormat, nullValue));

                        list.Add(element.ToString());
                    }
                    else
                    {
                        if (names)
                        {
                            list.Add(reader.GetName(index));
                        }

                        list.Add(MarshalOps.FixupDataValue(
                                     value, dateTimeBehavior, dateTimeKind,
                                     dateTimeFormat, nullValue));
                    }
                }
            }
        }
Exemple #7
0
 /// <summary>
 ///   Initializes a new instance of the DateTimeTextBox class by explicitly assigning its Behavior field. </summary>
 /// <param name="behavior">
 ///   The <see cref="DateTimeBehavior" /> object to associate the textbox with. </param>
 public DateTimeTextBox(DateTimeBehavior behavior)
     :
     base(behavior)
 {
 }
Exemple #8
0
 /// <summary>
 ///   Initializes a new instance of the DateTimeTextBox class by assigning its Behavior field
 ///   to an instance of <see cref="DateTimeBehavior" />. </summary>
 public DateTimeTextBox()
     :
     base(null)
 {
     m_behavior = new DateTimeBehavior(this);
 }