コード例 #1
0
        private ActionResult GetData(ViewConfiguration viewConfiguration, string sortExpression, string search, string filter,
                                     string metaFilter, int page, int pageSize = DefaultPageSize, bool applyRecordLevelFilters = true,
                                     bool applyRelatedRecordFilter             = false, string filterRelationshipName = null, string filterEntityName = null,
                                     string filterAttributeName = null, Guid?filterValue = null, bool overrideMaxPageSize = false, IDictionary <string, string> customParameters = null)
        {
            PaginatedGridData data;
            //Search criteria with length 4000+ causes Generic SQL error Bug#371907
            const int maxSearchLength = 3999;
            var       searchCriteria  = search?.Length > maxSearchLength?search.Substring(0, maxSearchLength) : search;

            using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.EntityGridController, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.GetData))
            {
                if (viewConfiguration == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, ResourceManager.GetString("Invalid_Request")));
                }

                if (pageSize < 0)
                {
                    pageSize = DefaultPageSize;
                }

                if (pageSize > DefaultMaxPageSize && !overrideMaxPageSize)
                {
                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(
                                                    "pageSize={0} is greater than the allowed maximum page size of {1}. Page size has been constrained to {1}.",
                                                    pageSize, DefaultMaxPageSize));
                    pageSize = DefaultMaxPageSize;
                }

                var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: viewConfiguration.PortalName);
                var website = HttpContext.GetWebsite();

                var viewDataAdapter = SetViewDataAdapter(viewConfiguration, sortExpression, searchCriteria, filter, metaFilter, page,
                                                         applyRecordLevelFilters, applyRelatedRecordFilter, filterRelationshipName, filterEntityName,
                                                         filterAttributeName, filterValue, customParameters, dataAdapterDependencies, website);

                var result = viewDataAdapter.FetchEntities();


                //If current page doesn't contain any records, but records exist in general, get those records from previous page for further rendering them.
                if (!result.Records.Any() && result.TotalRecordCount > 0)
                {
                    viewDataAdapter = SetViewDataAdapter(viewConfiguration, sortExpression, searchCriteria, filter, metaFilter,
                                                         page - 1, applyRecordLevelFilters, applyRelatedRecordFilter, filterRelationshipName, filterEntityName,
                                                         filterAttributeName, filterValue, customParameters, dataAdapterDependencies, website);

                    result = viewDataAdapter.FetchEntities();
                }

                if (result.EntityPermissionDenied)
                {
                    var permissionResult = new EntityPermissionResult(true);

                    return(Json(permissionResult));
                }


                var serviceContext = dataAdapterDependencies.GetServiceContext();
                var organizationMoneyFormatInfo = new OrganizationMoneyFormatInfo(dataAdapterDependencies);
                var crmLcid = HttpContext.GetCrmLcid();

                EntityRecord[] records;

                if (viewConfiguration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled&& viewConfiguration.EntityName != "entitlement")
                {
                    var crmEntityPermissionProvider = new CrmEntityPermissionProvider();
                    records = result.Records.Select(e => new EntityRecord(e, serviceContext, crmEntityPermissionProvider, viewDataAdapter.EntityMetadata, true, organizationMoneyFormatInfo: organizationMoneyFormatInfo, crmLcid: crmLcid)).ToArray();
                }
                else
                {
                    records = result.Records.Select(e => new EntityRecord(e, viewDataAdapter.EntityMetadata, serviceContext, organizationMoneyFormatInfo, crmLcid)).ToArray();
                }

                records = FilterWebsiteRelatedRecords(records, dataAdapterDependencies.GetWebsite());
                var totalRecordCount = result.TotalRecordCount;

                var disabledActionLinks = new List <DisabledItemActionLink>();

                // Disable Create Related Record Action Links based on Filter Criteria.
                disabledActionLinks.AddRange(DisableActionLinksBasedOnFilterCriteria(serviceContext, viewDataAdapter.EntityMetadata,
                                                                                     viewConfiguration.CreateRelatedRecordActionLinks, records));

                // Disable Item Action Links based on Filter Criteria.
                disabledActionLinks.AddRange(DisableActionLinksBasedOnFilterCriteria(serviceContext, viewDataAdapter.EntityMetadata,
                                                                                     viewConfiguration.ItemActionLinks, records));

                data = new PaginatedGridData(records, totalRecordCount, page, pageSize, disabledActionLinks)
                {
                    CreateActionMetadata = GetCreationActionMetadata(viewConfiguration, dataAdapterDependencies),
                    MoreRecords          = result.MoreRecords.GetValueOrDefault() || (totalRecordCount > (page * pageSize))
                };
            }

            var json = Json(data);

            json.MaxJsonLength = int.MaxValue;

            return(json);
        }
コード例 #2
0
        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;
        }
コード例 #3
0
        public EntityRecord(Entity entity, OrganizationServiceContext serviceContext, CrmEntityPermissionProvider provider, EntityMetadata entityMetadata = null, bool readGranted = false, EntityReference regarding = null, OrganizationMoneyFormatInfo organizationMoneyFormatInfo = null, int?crmLcid = null)
        {
            var entityPermissionResult = provider.TryAssert(serviceContext, entity, entityMetadata, readGranted, regarding);

            CanRead     = entityPermissionResult.CanRead;
            CanWrite    = entityPermissionResult.CanWrite;
            CanDelete   = entityPermissionResult.CanDelete;
            CanAppend   = entityPermissionResult.CanAppend;
            CanAppendTo = entityPermissionResult.CanAppendTo;

            var statecode = entity.GetAttributeValue <OptionSetValue>("statecode");

            if (statecode != null)
            {
                StateCode = statecode.Value;
            }

            var statuscode = entity.GetAttributeValue <OptionSetValue>("statuscode");

            if (statuscode != null)
            {
                StatusCode = statuscode.Value;
            }

            ConvertToEntityRecord(entity, entityMetadata, serviceContext, organizationMoneyFormatInfo, crmLcid);
        }
コード例 #4
0
 public EntityRecord(Entity entity, EntityMetadata entityMetadata = null, OrganizationServiceContext serviceContext = null, OrganizationMoneyFormatInfo organizationMoneyFormatInfo = null, int?crmLcid = null)
 {
     ConvertToEntityRecord(entity, entityMetadata, serviceContext, organizationMoneyFormatInfo, crmLcid);
 }
コード例 #5
0
        /// <summary>
        /// Converts the collection of entity records to a serializable dictionary.
        /// </summary>
        /// <param name="serviceContext">The <see cref="OrganizationServiceContext"/> used to retrieve metadata.</param>
        /// <param name="records">The collection of <see cref="Entity"/> records to convert.</param>
        /// <param name="entityMetadata">The <see cref="EntityMetadata"/> to be used to provide metadata for record and attributes.</param>
        /// <returns>List of a dictionary of records that can be serialized into the expected format the CrmHighchartsLibrary.js requires.</returns>
        private List <Dictionary <string, object> > ConvertRecordsToDictionary(OrganizationServiceContext serviceContext, IEnumerable <Entity> records, EntityMetadata entityMetadata)
        {
            var data = new List <Dictionary <string, object> >();
            var organizationMoneyFormatInfo = new OrganizationMoneyFormatInfo(serviceContext);

            foreach (var record in records)
            {
                var row = new Dictionary <string, object>
                {
                    { "RowId", record.Id.ToString("B", CultureInfo.InvariantCulture).ToUpper(CultureInfo.InvariantCulture) },
                    { "RowType", entityMetadata.ObjectTypeCode.GetValueOrDefault(0).ToString() }
                };

                // DateGrouping require us to also retrieve a datetime value so we can format series labels correctly. Grouping by day for example with a date like 9/23/2016 will result in the value 23 to be stored in the data. The DataDefinition is manually revised to add this aggregate attribute into the fetch so we get the actual date value 9/23/2016 displayed in the chart series.
                KeyValuePair <string, object> groupbyAttribute = new KeyValuePair <string, object>();
                object dategroupValue     = null;
                var    dategroupAttribute = record.Attributes.FirstOrDefault(a => a.Key.EndsWith("_dategroup_value"));
                if (!string.IsNullOrEmpty(dategroupAttribute.Key))
                {
                    var aliasedDateGroupValue = dategroupAttribute.Value as AliasedValue;
                    dategroupValue   = aliasedDateGroupValue == null ? dategroupAttribute.Value : aliasedDateGroupValue.Value;
                    groupbyAttribute = record.Attributes.FirstOrDefault(a =>
                                                                        a.Key != dategroupAttribute.Key
                                                                        &&
                                                                        a.Key.StartsWith(dategroupAttribute.Key.Substring(0, dategroupAttribute.Key.IndexOf("_dategroup_value", StringComparison.InvariantCulture))));
                }

                foreach (var attribute in record.Attributes)
                {
                    var aliasedValue               = attribute.Value as AliasedValue;
                    var value                      = aliasedValue != null ? aliasedValue.Value : attribute.Value;
                    var formattedValue             = string.Empty;
                    var attributeLogicalName       = aliasedValue != null ? aliasedValue.AttributeLogicalName : attribute.Key;
                    var attributeEntityLogicalName = aliasedValue != null ? aliasedValue.EntityLogicalName : entityMetadata.LogicalName;
                    var attributeMetadata          = this.GetAttributeMetadata(attributeLogicalName, attributeEntityLogicalName);

                    if (record.FormattedValues.Contains(attribute.Key))
                    {
                        formattedValue = record.FormattedValues[attribute.Key];
                    }

                    if (attributeMetadata != null && value != null)
                    {
                        switch (attributeMetadata.AttributeType)
                        {
                        case AttributeTypeCode.Customer:
                        case AttributeTypeCode.Lookup:
                        case AttributeTypeCode.Owner:
                            var entityReference = value as EntityReference;
                            if (entityReference != null)
                            {
                                formattedValue = entityReference.Name;
                            }
                            break;

                        case AttributeTypeCode.State:
                        case AttributeTypeCode.Status:
                        case AttributeTypeCode.Picklist:
                            var optionSetValue = value as OptionSetValue;
                            if (optionSetValue != null)
                            {
                                formattedValue =
                                    Adxstudio.Xrm.Core.OrganizationServiceContextExtensions.GetOptionSetValueLabel(attributeMetadata,
                                                                                                                   optionSetValue.Value, this.contextLanguage.IsCrmMultiLanguageEnabled ? this.contextLanguage.ContextLanguage.CrmLcid : this.culture.LCID);
                            }
                            break;

                        case AttributeTypeCode.Money:
                            var money = value as Money;
                            if (money != null)
                            {
                                value = money.Value;
                                var moneyFormatter = new BaseCurrencyMoneyFormatter(organizationMoneyFormatInfo, CultureInfo.CurrentCulture);
                                formattedValue = string.Format(moneyFormatter, "{0}", money);
                            }
                            break;

                        case AttributeTypeCode.DateTime:
                            if (!string.IsNullOrEmpty(dategroupAttribute.Key) && attribute.Key == groupbyAttribute.Key && dategroupValue != null)
                            {
                                value = dategroupValue;
                            }
                            if (value is DateTime)
                            {
                                formattedValue = ((DateTime)value).ToString(this.culture.DateTimeFormat.ShortDatePattern);
                            }
                            break;

                        case AttributeTypeCode.BigInt:
                        case AttributeTypeCode.Integer:
                            if (value is int)
                            {
                                formattedValue = ((int)value).ToString("N", this.culture);
                            }
                            break;

                        case AttributeTypeCode.Decimal:
                            var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
                            if (decimalAttributeMetadata != null && value is decimal)
                            {
                                formattedValue =
                                    ((decimal)value).ToString(string.Format("N{0}", decimalAttributeMetadata.Precision.GetValueOrDefault(2)),
                                                              this.culture);
                            }
                            break;

                        case AttributeTypeCode.Double:
                            var doubleAttributeMetadata = attributeMetadata as DoubleAttributeMetadata;
                            if (doubleAttributeMetadata != null && value is double)
                            {
                                formattedValue =
                                    ((double)value).ToString(string.Format("N{0}", doubleAttributeMetadata.Precision.GetValueOrDefault(2)),
                                                             this.culture);
                            }
                            break;
                        }
                    }

                    if (string.IsNullOrWhiteSpace(formattedValue))
                    {
                        try
                        {
                            formattedValue = value.ToString();
                        }
                        catch
                        {
                            // ignored
                        }
                    }

                    if (!string.IsNullOrEmpty(formattedValue))
                    {
                        formattedValue = formattedValue.Replace("<", "&lt").Replace(">", "&gt");
                    }

                    row.Add(attribute.Key, formattedValue);
                    row.Add(string.Format("{0}_Value", attribute.Key), value);
                }

                data.Add(row);
            }

            return(data);
        }