예제 #1
0
        private static string ToLabel(EnumAttributeMetadata attributeMetadata, Condition condition, int languageCode)
        {
            if (condition == null)
            {
                return(null);
            }
            if (attributeMetadata == null)
            {
                return(null);
            }

            var value = Convert.ToInt32(condition.Value);

            var option = attributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Value == value);

            if (option == null)
            {
                return(value.ToString(CultureInfo.InvariantCulture));
            }

            var localizedLabel = option.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == languageCode);

            return(localizedLabel == null
                                ? option.Label.GetLocalizedLabelString()
                                : localizedLabel.Label);
        }
        public OptionSetIntellisenseData(EnumAttributeMetadata enumAttributeMetadata)
        {
            this.IsStateCode  = enumAttributeMetadata is StateAttributeMetadata;
            this.IsStatusCode = enumAttributeMetadata is StatusAttributeMetadata;

            this.OptionSetMetadata = enumAttributeMetadata.OptionSet;
        }
예제 #3
0
        public int getIndexOfLabel(string entityName, string field, string labelText, IOrganizationService context)
        {
            int index = -1;
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = field,
                RetrieveAsIfPublished = true
            };
            RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest);
            EnumAttributeMetadata     attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;

            foreach (OptionMetadata om in attributeMetadata.OptionSet.Options)
            {
                if (om.Label.UserLocalizedLabel.Label.ToString() == labelText)
                {
                    if (om.Value != null)
                    {
                        index = om.Value.Value;
                    }
                }
            }

            return(index);
        }
예제 #4
0
        public string getLabelFromField(Entity entity, string field, IOrganizationService context)
        {
            var    fieldValue = ((OptionSetValue)entity.Attributes[field]).Value.ToString();
            string fieldLabel = "";
            //need to get Option Set display label based on its value.  This requires getting attribute metadata
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entity.LogicalName,
                LogicalName           = field,
                RetrieveAsIfPublished = true
            };

            RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)context.Execute(attributeRequest);
            EnumAttributeMetadata     attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;

            foreach (OptionMetadata om in attributeMetadata.OptionSet.Options)
            {
                if (om.Value == ((OptionSetValue)entity.Attributes[field]).Value)
                {
                    fieldLabel = om.Label.UserLocalizedLabel.Label.ToString();
                }
            }

            return(fieldLabel);
        }
예제 #5
0
        public OptionMetadata[] GetOptionSet(string entityName, string fieldName)
        {
            OptionMetadata[]         optionMetadatas;
            IOrganizationService     orgService       = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = fieldName,
                RetrieveAsIfPublished = false
            };

            RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgService.Execute(attributeRequest);

            if (attributeResponse.AttributeMetadata.AttributeType == Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Boolean)
            {
                BooleanAttributeMetadata boolenAttributeMetadata = (BooleanAttributeMetadata)attributeResponse.AttributeMetadata;
                BooleanOptionSetMetadata boolenOptionSetMetadata = boolenAttributeMetadata.OptionSet;

                OptionMetadata[] options = new OptionMetadata[2];
                options[0]      = boolenOptionSetMetadata.TrueOption;
                options[1]      = boolenOptionSetMetadata.FalseOption;
                optionMetadatas = options;
            }
            else
            {
                EnumAttributeMetadata picklistAttributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;
                OptionSetMetadata     optionSetMetadata         = picklistAttributeMetadata.OptionSet;
                OptionMetadata[]      optionList = optionSetMetadata.Options.ToArray();
                optionMetadatas = optionList;
            }


            return(optionMetadatas);
        }
예제 #6
0
        private List <OptionalValue> GetOptionSet(string entityName, string fieldName, IOrganizationService service)
        {
            RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest();

            retrieveDetails.EntityFilters = EntityFilters.All;
            retrieveDetails.LogicalName   = entityName;

            RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
            EntityMetadata         metadata = retrieveEntityResponseObj.EntityMetadata;
            var attribiuteMetadata          = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, fieldName, StringComparison.OrdinalIgnoreCase));

            if (attribiuteMetadata == null)
            {
                return(new List <OptionalValue>());
            }
            EnumAttributeMetadata picklistMetadata = attribiuteMetadata as EnumAttributeMetadata;
            OptionSetMetadata     options          = picklistMetadata.OptionSet;

            return((from o in options.Options
                    select new OptionalValue
            {
                Value = o.Value,
                Text = o.Label.UserLocalizedLabel.Label
            }).ToList());
        }
예제 #7
0
        private void CleanEnum(CodeTypeDeclaration type, EnumAttributeMetadata enumAttributeMetadata, string className)
        {
            foreach (var field in type.Members.Cast <CodeTypeMember>().OfType <CodeMemberField>())
            {
                if (field.CustomAttributes.Cast <CodeAttributeDeclaration>().Any(x => x.Name == "Description"))
                {
                    return;
                }

                var codeExpression = field.InitExpression as CodePrimitiveExpression;
                if (codeExpression == null)
                {
                    continue;
                }

                var val = (int)codeExpression.Value;

                foreach (CodeAttributeDeclaration att in field.CustomAttributes)
                {
                    att.Name = att.Name.Replace("System.Runtime.Serialization.", "").Replace("EnumMemberAttribute", "EnumMember");
                }

                var option = enumAttributeMetadata.OptionSet.Options.FirstOrDefault(x => x.Value.Value == val);
                if (option == null)
                {
                    continue;
                }

                field.CustomAttributes.Insert(0, new CodeAttributeDeclaration("Description", new CodeAttributeArgument(new CodePrimitiveExpression(option.Label?.LocalizedLabels?.FirstOrDefault()?.Label))));

                var status = option as StatusOptionMetadata;
                if (status != null && enumAttributeMetadata.LogicalName == "statuscode")
                {
                    var parentEnt      = metadata.Entities.First(x => x.LogicalName == enumAttributeMetadata.EntityLogicalName);
                    var stateOptionSet = parentEnt.Attributes.OfType <StateAttributeMetadata>().FirstOrDefault()?.OptionSet;
                    if (stateOptionSet == null)
                    {
                        continue;
                    }

                    var stateOptionSetName = namingService.GetNameForOptionSet(parentEnt, stateOptionSet, Services);
                    if (NestNonGlobalEnums && UseDisplayNames)
                    {
                        stateOptionSetName = stateOptionSetName.Substring(className.Length + 1);
                    }

                    if (stateOptionSet.Options.Any())
                    {
                        var stateOption = stateOptionSet.Options.FirstOrDefault(x => x.Value.Value == status.State.Value);

                        var optionName = namingService.GetNameForOption(stateOptionSet, stateOption, Services);
                        field.CustomAttributes.Insert(0, new CodeAttributeDeclaration("AmbientValue", new CodeAttributeArgument(
                                                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(stateOptionSetName), optionName)
                                                                                          )));
                    }
                }
            }
        }
예제 #8
0
 /// <summary>
 /// Gets the values.
 /// </summary>
 /// <param name="metadata">The metadata.</param>
 /// <returns></returns>
 public IEnumerable <OptionSetValueModel> GetValues(EnumAttributeMetadata metadata)
 {
     return(metadata.OptionSet.Options.Select(metadataOption =>
                                              new OptionSetValueModel()
     {
         Name = GetName(metadataOption.Label),
         Value = metadataOption.Value ?? 0,
         Description = Helpers.GetDescription(metadataOption.Description)
     }));
 }
예제 #9
0
        public static string GetOptionSetValueLabel(string entityName, string fieldName, int optionSetValue, IOrganizationService service)
        {
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();

            retrieveAttributeRequest.EntityLogicalName     = entityName;
            retrieveAttributeRequest.LogicalName           = fieldName;
            retrieveAttributeRequest.RetrieveAsIfPublished = false;
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            EnumAttributeMetadata     enumAttributeMetadata     = (EnumAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            return(enumAttributeMetadata.OptionSet.Options.Where((OptionMetadata x) => x.Value == optionSetValue).FirstOrDefault().Label.UserLocalizedLabel.Label);
        }
예제 #10
0
        private static string ToLabel(EnumAttributeMetadata attributeMetadata, Filter filter, int languageCode)
        {
            var uiname = filter.Extensions.GetExtensionValue("uiname");

            if (!string.IsNullOrWhiteSpace(uiname))
            {
                return(uiname);
            }

            var labels = filter.Conditions.Select(c => ToLabel(attributeMetadata, c, languageCode) ?? c.UiName ?? c.Value as string).ToArray();

            return(string.Join(" - ", labels));
        }
예제 #11
0
        /// <summary>
        /// Gets the option set model.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        /// <param name="nameSpace">The name space.</param>
        /// <returns></returns>
        public OptionSetModel GetOptionSetModel(EnumAttributeMetadata metadata, string nameSpace)
        {
            var optionSetName = metadata.SchemaName;

            if (metadata.OptionSet.IsGlobal == false)
            {
                var entityMetadata = _metadataRepository.GetEntityMetadata(metadata.EntityLogicalName);
                optionSetName = $"{entityMetadata.SchemaName}_{metadata.SchemaName}";
            }

            return(new OptionSetModel()
            {
                OptionSetName = optionSetName,
                Namespace = nameSpace,
                Description = Helpers.GetDescription(metadata.Description)
            });
        }
        public static void UpdateMappingEnum(EnumAttributeMetadata picklist, MappingEnum mappingEnum)
        {
            if (picklist.SchemaName != null)
            {
                mappingEnum.DisplayName = Naming.GetProperVariableName(Naming.GetProperVariableName(picklist.SchemaName));
            }

            mappingEnum.LogicalName = picklist.LogicalName ?? mappingEnum.LogicalName;

            if (picklist.OptionSet != null)
            {
                mappingEnum.Items =
                    picklist.OptionSet.Options.Select(
                        o => new MapperEnumItem
                {
                    Attribute = new CrmPicklistAttribute
                    {
                        DisplayName     = o.Label.UserLocalizedLabel.Label,
                        Value           = o.Value ?? 1,
                        LocalizedLabels = o.Label.LocalizedLabels.Select(label => new LocalizedLabelSerialisable
                        {
                            LanguageCode = label.LanguageCode,
                            Label        = label.Label
                        }).ToArray()
                    },
                    Name = Naming.GetProperVariableName(o.Label.UserLocalizedLabel.Label)
                }
                        ).ToArray();
            }

            Dictionary <string, int> duplicates = new Dictionary <string, int>();

            foreach (var i in mappingEnum.Items)
            {
                if (duplicates.ContainsKey(i.Name))
                {
                    duplicates[i.Name] = duplicates[i.Name] + 1;
                    i.Name            += "_" + duplicates[i.Name];
                }
                else
                {
                    duplicates[i.Name] = 1;
                }
            }
        }
예제 #13
0
        public static List <NameDisplayName> GetPicklistValuesOfPicklistAttributeMetadata(AttributeMetadata attributeMetadata)
        {
            EnumAttributeMetadata picklistAttributeMetadata = attributeMetadata as EnumAttributeMetadata;

            if (picklistAttributeMetadata == null)
            {
                throw new ArgumentException("Type of argument must be PicklistAttributeMetadata", "attributeMetadata");
            }

            List <NameDisplayName> list = new List <NameDisplayName>();

            foreach (var option in picklistAttributeMetadata.OptionSet.Options)
            {
                list.Add(new NameDisplayName(option.Value.Value.ToString(), option.Label.LocalizedLabels[0].Label));
            }

            return(list.OrderBy(t => t.DisplayName).ToList());
        }
        public static MappingEnum GetMappingEnum(EnumAttributeMetadata picklist)
        {
            var enm = new MappingEnum
            {
                DisplayName = Naming.GetProperVariableName(Naming.GetProperVariableName(picklist.SchemaName)),
                LogicalName = picklist.LogicalName,
                Items       =
                    picklist.OptionSet.Options.Select(
                        o => new MapperEnumItem
                {
                    Attribute = new CrmPicklistAttribute
                    {
                        DisplayName     = o.Label.UserLocalizedLabel.Label,
                        Value           = o.Value ?? 1,
                        LocalizedLabels = o.Label.LocalizedLabels.Select(label => new LocalizedLabelSerialisable
                        {
                            LanguageCode = label.LanguageCode,
                            Label        = label.Label
                        }).ToArray()
                    },
                    Name = Naming.GetProperVariableName(o.Label.UserLocalizedLabel.Label)
                }
                        ).ToArray(),
                MetadataId = picklist.MetadataId
            };

            Dictionary <string, int> duplicates = new Dictionary <string, int>();

            foreach (var i in enm.Items)
            {
                if (duplicates.ContainsKey(i.Name))
                {
                    duplicates[i.Name] = duplicates[i.Name] + 1;
                    i.Name            += "_" + duplicates[i.Name];
                }
                else
                {
                    duplicates[i.Name] = 1;
                }
            }

            return(enm);
        }
예제 #15
0
        //</snippetStateModelTransitions.GetValidStatusOptions>

        //<snippetStateModelTransitions.GetOptionSetLabel>
        /// <summary>
        /// Returns a string representing the label of an option in an optionset
        /// </summary>
        /// <param name="attribute">The metadata for an an attribute with options</param>
        /// <param name="value">The value of the option</param>
        /// <returns>The label for the option</returns>
        public String GetOptionSetLabel(EnumAttributeMetadata attribute, int value)
        {
            String label = "";

            foreach (OptionMetadata option in attribute.OptionSet.Options)
            {
                if (option.Value.Value == value)
                {
                    try
                    {
                        label = option.Label.UserLocalizedLabel.Label;
                    }
                    catch (Exception)
                    {
                        label = option.Label.LocalizedLabels[0].Label;
                    };
                }
            }
            return(label);
        }
        private void TransformOptionSets(CodeMemberProperty member, EntityCacheItem entity, AttributeCacheItem attribute)
        {
            AttributeMetadata attributeMetadata = attribute.Metadata;

            if (entity != null && attributeMetadata != null)
            {
                if (attributeMetadata is EnumAttributeMetadata)
                {
                    string typeName;
                    EnumAttributeMetadata enumMetadata = attributeMetadata as EnumAttributeMetadata;
                    OptionSetCacheItem    optionSet    = DynamicsMetadataCache.OptionSets.GetBy(entity.LogicalName, enumMetadata.OptionSet.Name);

                    if (optionSet == null)
                    {
                        optionSet = DynamicsMetadataCache.OptionSets.GetBy("*", enumMetadata.OptionSet.Name);
                    }

                    if (optionSet != null)
                    {
                        typeName = optionSet.GeneratedTypeName;
                    }
                    else
                    {
                        var namingService = (INamingService)serviceProvider.GetService(typeof(INamingService));

                        typeName = namingService.GetNameForOptionSet(entity.Metadata, enumMetadata.OptionSet, serviceProvider);
                    }

                    if (!this.addedEnums.ContainsKey(typeName))
                    {
                        this.addedEnums.Add(typeName, enumMetadata);
                    }

                    FixEnums(member, enumMetadata, typeName);
                }
                else
                {
                    member.Type = new CodeTypeReference("int?");
                }
            }
        }
예제 #17
0
        public static string GetPickListLabel(string entityName, string fieldName, int value, IOrganizationService service)
        {
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = fieldName,
                RetrieveAsIfPublished = true
            };

            RetrieveAttributeResponse response          = (RetrieveAttributeResponse)service.Execute(attributeRequest);
            EnumAttributeMetadata     attributeMetadata = (EnumAttributeMetadata)response.AttributeMetadata;

            foreach (OptionMetadata optionMeta in attributeMetadata.OptionSet.Options)
            {
                if (optionMeta.Value == value)
                {
                    return(optionMeta.Label.UserLocalizedLabel.Label);
                }
            }
            return(string.Empty);
        }
        private void FixEnums(CodeMemberProperty codeProperty, EnumAttributeMetadata listAttribute, string typeName)
        {
            //TODO: refator this method to also work in VB or F#
            codeProperty.Type = new CodeTypeReference(typeName.EndsWith("?") ? typeName : typeName + "?");

            if (codeProperty.HasSet)
            {
                if (codeProperty.SetStatements[1].GetType() == typeof(CodeConditionStatement))
                {
                    ((CodeConditionStatement)codeProperty.SetStatements[1]).FalseStatements[0] = new CodeSnippetStatement
                    {
                        Value =
                            string.Format(
                                "\t\t\t\tthis.SetAttributeValue(\"{0}\", (value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value.Value) : null));",
                                listAttribute.LogicalName)
                    };
                }
                else
                {
                    codeProperty.SetStatements[1] =
                        new CodeSnippetStatement(
                            string.Format(
                                "\t\t\t\t\tthis.SetAttributeValue(\"{0}\", (value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value.Value) : null));",
                                listAttribute.LogicalName));
                }
            }

            if (codeProperty.HasGet)
            {
                codeProperty.GetStatements.Clear();
                codeProperty.GetStatements.Add(new CodeSnippetExpression(
                                                   string.Format(
                                                       "var ret = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>(\"{1}\");" + Environment.NewLine +
                                                       "\t\t\t\treturn (ret!=null ? ({0}?)ret.Value : ({0}?)null);",
                                                       typeName, listAttribute.LogicalName)
                                                   ));
            }
        }
예제 #19
0
        public static MappingEnum Parse(EnumAttributeMetadata picklist)
        {
            var enm = new MappingEnum
            {
                DisplayName = Naming.GetProperVariableName(Naming.GetProperVariableName(picklist.SchemaName)),
                Items       =
                    picklist.OptionSet.Options.Select(
                        o => new MapperEnumItem
                {
                    Attribute = new CrmPicklistAttribute
                    {
                        DisplayName = o.Label.UserLocalizedLabel.Label,
                        Value       = o.Value ?? 1
                    },
                    Name = Naming.GetProperVariableName(o.Label.UserLocalizedLabel.Label)
                }
                        ).ToArray()
            };

            RenameDuplicates(enm);

            return(enm);
        }
예제 #20
0
        public static EnumModel Parse(FieldModel parent, EnumAttributeMetadata metadata)
        {
            if (metadata is null)
            {
                return(null);
            }

            var items =
                metadata?.OptionSet.Options.Select(
                    o => new EnumModelItem
            {
                DisplayName = NameHelper.GetProperVariableName(o.Label.UserLocalizedLabel.Label),
                Value       = o.Value ?? 1,
            }
                    ).ToArray();

            return(new EnumModel(
                       parent,
                       metadata.OptionSet.DisplayName(),
                       metadata?.OptionSet.Name,
                       metadata.OptionSet.IsGlobal ?? false,
                       items));
        }
예제 #21
0
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string ProcessCode_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.ProcessCode_OptionSetValue.Value));
        }
예제 #22
0
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string IsInherited_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.IsInherited_OptionSetValue.Value));
        }
예제 #23
0
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string ComponentState_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.ComponentState_OptionSetValue.Value));
        }
예제 #24
0
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string statuscode_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.statuscode_OptionSetValue.Value));
        }
예제 #25
0
 /// <summary>
 /// Retrieves the current value's text in the user's language.
 /// </summary>
 /// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
 /// <returns></returns>
 public string StatusReason_Text(EnumAttributeMetadata attributeMetadata)
 {
     return(attributeMetadata.GetOptionSetText(this.StatusReason_OptionSetValue.Value));
 }
예제 #26
0
 /// <summary>
 /// Retrieves the current value's text in the user's language.
 /// </summary>
 /// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
 /// <returns></returns>
 public string LeaveType_Text(EnumAttributeMetadata attributeMetadata)
 {
     return(attributeMetadata.GetOptionSetText(this.LeaveType_OptionSetValue.Value));
 }
예제 #27
0
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string LogPhase_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.LogPhase_OptionSetValue.Value));
        }
예제 #28
0
        //</snippetupdateOptionLabelList>
        //<snippetaddOptionLabelsToCache>
        protected void addOptionLabelsToCache(EntityMetadataCollection entityMetadataCollection, Boolean showChanges)
        {
            List <OptionSetOption> changes = new List <OptionSetOption>();

            foreach (EntityMetadata em in entityMetadataCollection)
            {
                foreach (AttributeMetadata am in em.Attributes)
                {
                    switch (am.AttributeType)
                    {
                    case AttributeTypeCode.Boolean:
                        BooleanAttributeMetadata booleanAttribute = (BooleanAttributeMetadata)am;
                        //Labels will not be included if they aren't new
                        if (booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel != null)
                        {
                            changes.Add(new OptionSetOption(
                                            (Guid)booleanAttribute.OptionSet.MetadataId,
                                            0,
                                            booleanAttribute.OptionSet.FalseOption.Label.UserLocalizedLabel.Label)
                                        );
                        }
                        //Labels will not be included if they aren't new
                        if (booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel != null)
                        {
                            changes.Add(new OptionSetOption(
                                            (Guid)booleanAttribute.OptionSet.MetadataId,
                                            1,
                                            booleanAttribute.OptionSet.TrueOption.Label.UserLocalizedLabel.Label));
                        }
                        break;

                    default:
                        EnumAttributeMetadata optionsetAttribute = (EnumAttributeMetadata)am;
                        foreach (OptionMetadata option in optionsetAttribute.OptionSet.Options)
                        {
                            //Labels will not be included if they aren't new
                            if (option.Label.UserLocalizedLabel != null)
                            {
                                changes.Add(new OptionSetOption(
                                                (Guid)optionsetAttribute.OptionSet.MetadataId,
                                                (int)option.Value,
                                                option.Label.UserLocalizedLabel.Label));
                            }
                        }
                        break;
                    }
                }
            }

            _optionLabelList.AddRange(changes);

            if (showChanges)
            {
                if (changes.Count > 0)
                {
                    Console.WriteLine("{0} option labels for {1} entities were added to the cache.", changes.Count, entityMetadataCollection.Count);
                    Console.WriteLine("{0} Option Labels cached", _optionLabelList.Count);
                }
                else
                {
                    Console.WriteLine("No option labels were added to the cache.");
                }
            }
        }
예제 #29
0
  //</snippetStateModelTransitions.GetValidStatusOptions>

  //<snippetStateModelTransitions.GetOptionSetLabel>
  /// <summary>
  /// Returns a string representing the label of an option in an optionset
  /// </summary>
  /// <param name="attribute">The metadata for an an attribute with options</param>
  /// <param name="value">The value of the option</param>
  /// <returns>The label for the option</returns>
  public String GetOptionSetLabel(EnumAttributeMetadata attribute, int value)
   {
    String label = "";
    foreach (OptionMetadata option in attribute.OptionSet.Options)
    {
     if (option.Value.Value == value)
     {
      try
      {
       label = option.Label.UserLocalizedLabel.Label;
      }
      catch (Exception)
      {
       label = option.Label.LocalizedLabels[0].Label;
      };
     }
    }
    return label;
   }
/// <summary>
/// Retrieves the current value's text in the user's language.
/// </summary>
/// <param name="AttributeMetadata">The attribute metadata previously retrieved using the 'GetAttributeMetadata' extension method on the IOrganizationService object.</param>
/// <returns></returns>
        public string AntigenResult_Text(EnumAttributeMetadata AttributeMetadata)
        {
            return(AttributeMetadata.GetOptionSetText(this.AntigenResult_OptionSetValue.Value));
        }
예제 #31
0
        /// <summary>
        /// Appends rows to the specified data table from the specified EntityCollection.
        /// </summary>
        /// <param name="dataTable">The DataTable.</param>
        /// <param name="entities">The EntityCollection.</param>
        /// <param name="recordLimit">The record limit.</param>
        /// <returns>A DataTable with appended rows.</returns>
        protected DataTable AppendRows(DataTable dataTable, EntityCollection entities, int recordLimit)
        {
            Dictionary <string, EntityMetadata> metadata = new Dictionary <string, EntityMetadata>();

            foreach (DataColumn column in dataTable.Columns)
            {
                string entityLogicalName = column.ColumnName.Substring(0, column.ColumnName.IndexOf("."));

                if (!metadata.ContainsKey(entityLogicalName))
                {
                    metadata.Add(entityLogicalName, Dynamics365Entity.Create(entityLogicalName, (Dynamics365Connection)Parent).GetEntityMetadata((Dynamics365Connection)Parent));
                }
            }

            for (int recordIndex = 0; recordIndex < entities.Entities.Count && dataTable.Rows.Count < recordLimit; recordIndex++)
            {
                Entity  record = entities.Entities[recordIndex];
                DataRow row    = dataTable.NewRow();

                foreach (KeyValuePair <string, object> attribute in record.Attributes)
                {
                    string entityLogicalName    = record.LogicalName;
                    string attributeLogicalName = attribute.Key;
                    object attributeValue       = attribute.Value;

                    if (attribute.Value is AliasedValue)
                    {
                        AliasedValue aliasedValue = (AliasedValue)attribute.Value;
                        entityLogicalName    = aliasedValue.EntityLogicalName;
                        attributeLogicalName = aliasedValue.AttributeLogicalName;
                        attributeValue       = aliasedValue.Value;
                    }

                    string nativeColumnName = string.Format("{0}.{1}", entityLogicalName, attributeLogicalName);

                    if (DataTypes == DataTypes.Native)
                    {
                        if (dataTable.Columns.Contains(nativeColumnName))
                        {
                            row[nativeColumnName] = attributeValue;
                        }
                    }
                    else if (DataTypes == DataTypes.Neutral)
                    {
                        AttributeMetadata        attributeMetadata = metadata[entityLogicalName].Attributes.FirstOrDefault(findField => findField.LogicalName == attributeLogicalName);
                        Dynamics365TypeConverter converter         = new Dynamics365TypeConverter(attributeMetadata);

                        if (converter.Dynamics365Type == typeof(EntityReference) || converter.Dynamics365Type == typeof(EntityCollection))
                        {
                            if (LookupBehaviour == LookupBehaviour.Name || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                            {
                                string nameColumn = string.Format("{0}.Name", nativeColumnName);

                                if (dataTable.Columns.Contains(nameColumn))
                                {
                                    if (converter.Dynamics365Type == typeof(EntityReference))
                                    {
                                        row[nameColumn] = ((EntityReference)attributeValue).Name;
                                    }
                                    else if (converter.Dynamics365Type == typeof(EntityCollection))
                                    {
                                        string names = string.Empty;

                                        foreach (Entity entity in ((EntityCollection)attributeValue).Entities)
                                        {
                                            EntityReference party = (EntityReference)entity["partyid"];
                                            names = names == string.Empty ? party.Name : string.Concat(names, PARTYLIST_DELIMITER, party.Name);
                                        }

                                        row[nameColumn] = names;
                                    }
                                }
                            }

                            if (LookupBehaviour == LookupBehaviour.Identifier || LookupBehaviour == LookupBehaviour.NameAndIdentifier || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                            {
                                string identifierColumn = string.Format("{0}.Identifier", nativeColumnName);

                                if (dataTable.Columns.Contains(identifierColumn))
                                {
                                    if (converter.Dynamics365Type == typeof(EntityReference))
                                    {
                                        row[identifierColumn] = ((EntityReference)attributeValue).Id.ToString();
                                    }
                                    else if (converter.Dynamics365Type == typeof(EntityCollection))
                                    {
                                        string identifiers = string.Empty;

                                        foreach (Entity entity in ((EntityCollection)attributeValue).Entities)
                                        {
                                            EntityReference party = (EntityReference)entity["partyid"];
                                            identifiers = identifiers == string.Empty ? party.Id.ToString() : string.Concat(identifiers, PARTYLIST_DELIMITER, party.Id.ToString());
                                        }

                                        row[identifierColumn] = identifiers;
                                    }
                                }
                            }

                            if (LookupBehaviour == LookupBehaviour.Entity || LookupBehaviour == LookupBehaviour.EntityAndNameAndIdentifier)
                            {
                                string entityColumn = string.Format("{0}.Entity", nativeColumnName);

                                if (dataTable.Columns.Contains(entityColumn))
                                {
                                    if (converter.Dynamics365Type == typeof(EntityReference))
                                    {
                                        row[entityColumn] = ((EntityReference)attributeValue).LogicalName;
                                    }
                                    else if (converter.Dynamics365Type == typeof(EntityCollection))
                                    {
                                        string logicalNames = string.Empty;

                                        foreach (Entity entity in ((EntityCollection)attributeValue).Entities)
                                        {
                                            EntityReference party = (EntityReference)entity["partyid"];
                                            logicalNames = logicalNames == string.Empty ? party.LogicalName : string.Concat(logicalNames, PARTYLIST_DELIMITER, party.LogicalName);
                                        }

                                        row[entityColumn] = logicalNames;
                                    }
                                }
                            }
                        }
                        else if (converter.Dynamics365Type == typeof(OptionSetValue))
                        {
                            if (OptionSetBehaviour == OptionSetBehaviour.Name || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                            {
                                string nameColumn = string.Format("{0}.Name", nativeColumnName);

                                if (dataTable.Columns.Contains(nameColumn))
                                {
                                    EnumAttributeMetadata enumMetadata   = (EnumAttributeMetadata)attributeMetadata;
                                    OptionMetadata        optionMetadata = enumMetadata.OptionSet.Options.FirstOrDefault(option => option.Value == ((OptionSetValue)attributeValue).Value);

                                    if (optionMetadata != default(OptionMetadata))
                                    {
                                        row[nameColumn] = optionMetadata.Label.UserLocalizedLabel.Label;
                                    }
                                }
                            }

                            if (OptionSetBehaviour == OptionSetBehaviour.Code || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                            {
                                string codeColumn = string.Format("{0}.Code", nativeColumnName);

                                if (dataTable.Columns.Contains(codeColumn))
                                {
                                    row[codeColumn] = ((OptionSetValue)attributeValue).Value;
                                }
                            }
                        }
                        else if (converter.Dynamics365Type == typeof(OptionSetValueCollection))
                        {
                            if (OptionSetBehaviour == OptionSetBehaviour.Name || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                            {
                                string nameColumn = string.Format("{0}.Name", nativeColumnName);

                                if (dataTable.Columns.Contains(nameColumn))
                                {
                                    List <string>            labels          = new List <string>();
                                    EnumAttributeMetadata    enumMetadata    = (EnumAttributeMetadata)attributeMetadata;
                                    OptionSetValueCollection optionSetValues = (OptionSetValueCollection)attributeValue;

                                    foreach (OptionSetValue optionSetValue in optionSetValues)
                                    {
                                        OptionMetadata optionMetadata = enumMetadata.OptionSet.Options.FirstOrDefault(option => option.Value == optionSetValue.Value);

                                        if (optionMetadata != default(OptionMetadata))
                                        {
                                            labels.Add(optionMetadata.Label.UserLocalizedLabel.Label);
                                        }
                                    }

                                    row[nameColumn] = string.Join(Dynamics365TypeConverter.MULTI_OPTION_SET_DELIMITER, labels.Select(label => label));
                                }
                            }

                            if (OptionSetBehaviour == OptionSetBehaviour.Code || OptionSetBehaviour == OptionSetBehaviour.NameAndCode)
                            {
                                string codeColumn = string.Format("{0}.Code", nativeColumnName);

                                if (dataTable.Columns.Contains(codeColumn))
                                {
                                    OptionSetValueCollection optionSetValues = (OptionSetValueCollection)attributeValue;
                                    row[codeColumn] = string.Join(Dynamics365TypeConverter.MULTI_OPTION_SET_DELIMITER, optionSetValues.Select(optionSet => optionSet.Value.ToString()));
                                }
                            }
                        }
                        else
                        {
                            if (dataTable.Columns.Contains(nativeColumnName))
                            {
                                row[nativeColumnName] = converter.ConvertFrom(null, null, attributeValue);
                            }
                        }
                    }
                }

                dataTable.Rows.Add(row);
            }

            return(dataTable);
        }