Esempio n. 1
0
        private OptionMetadataCollection GetStatusCodeOptionsSetTextOnValue(string entityName, string attributeName)
        {
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityName,
                LogicalName           = attributeName,
                RetrieveAsIfPublished = true
            };
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)Service.Execute(retrieveAttributeRequest);
            StatusAttributeMetadata   attributeMetadata         = (StatusAttributeMetadata)retrieveAttributeResponse?.AttributeMetadata;

            if (attributeMetadata == null)
            {
                return(null);
            }
            return(attributeMetadata?.OptionSet?.Options);
        }
Esempio n. 2
0
        public static string GetOptionSetTextGivenValue(this Entity entity, IOrganizationService service, string entityName, string attributeName, int selectedValue)
        {
            try
            {
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest {
                    EntityLogicalName = entityName, LogicalName = attributeName, RetrieveAsIfPublished = true
                };
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                OptionMetadata[]          optionList;

                if (attributeName == "statecode")
                {
                    StateAttributeMetadata retrievedPicklistAttributeMetadata = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else if (attributeName == "statuscode")
                {
                    StatusAttributeMetadata retrievedPicklistAttributeMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else
                {
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }

                string selectedOptionValue = "";
                if (selectedValue != null)
                {
                    foreach (OptionMetadata oMD in optionList)
                    {
                        if (oMD.Value == selectedValue)
                        {
                            selectedOptionValue = oMD.Label.UserLocalizedLabel.Label;
                            break;
                        }
                    }
                }
                return(selectedOptionValue);
            }
            catch (System.ServiceModel.FaultException ex1)
            {
                string strEr = ex1.InnerException.Data.ToString();
                return("");
            }
        }
        /// <summary>
        /// Retrieves the Option set metadata options
        /// </summary>
        /// <param name="retrieveAttributeResponse">Attribute Response</param>
        /// <returns>Option set metadata options</returns>
        private static OptionSetMetadata RetrieveAttributeType(RetrieveAttributeResponseWrapper retrieveAttributeResponse)
        {
            if (retrieveAttributeResponse != null && retrieveAttributeResponse.AttributeMetadata != null)
            {
                switch (retrieveAttributeResponse.AttributeMetadata.AttributeTypeName.Value)
                {
                case "StatusType":
                    StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    return(statusAttributeMetadata.OptionSet);

                case "PicklistType":
                    PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
                    return(picklistAttributeMetadata.OptionSet);
                }
            }

            return(null);
        }
Esempio n. 4
0
        public static string GetDropDownValue(string entityName, string attributeName, int attributeValue)
        {
            string DropDownText = string.Empty;

            OrganizationServiceProxy serviceProxy = CrmHelper.Connect();

            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName = entityName,
                LogicalName       = attributeName
            };

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

            // Handle Picklist options
            if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Picklist)
            {
                PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata;
                foreach (OptionMetadata option in picklist.OptionSet.Options)
                {
                    if (option.Value == attributeValue)
                    {
                        DropDownText = option.Label.UserLocalizedLabel.Label;
                        break;
                    }
                }
            }

            // Handle Status options
            else if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Status)
            {
                StatusAttributeMetadata status = (StatusAttributeMetadata)attributeResponse.AttributeMetadata;
                foreach (StatusOptionMetadata option in status.OptionSet.Options)
                {
                    if (option.Value == attributeValue)
                    {
                        DropDownText = option.Label.UserLocalizedLabel.Label;
                        break;
                    }
                }
            }
            return(DropDownText);
        }
Esempio n. 5
0
        public string GetEntityStatusLabel(string entityLogicalName, int statusCode)
        {
            // Create the attribute request (define which entities attribute
            //  information we want to get) entity.LogicalName is our current
            //  name of our entity (ex: contact, account, etc.)
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName     = entityLogicalName,
                LogicalName           = "statuscode",
                RetrieveAsIfPublished = true
            };

            // Execute the request to get the attribute information
            RetrieveAttributeResponse attributeResponse =
                (RetrieveAttributeResponse)XrmContext.Execute(attributeRequest);
            AttributeMetadata attrMetadata =
                (AttributeMetadata)attributeResponse.AttributeMetadata;

            // Cast the AttributeMetadata to StatusAttribute data
            StatusAttributeMetadata statusAttrMetadata =
                (StatusAttributeMetadata)attrMetadata;

            // Get the status code label by comparing all of the status code values
            //  possible for the status code drop down list. Once we get a match on
            //  the value we take the label for that value

            // For every status code value within all of our status codes values
            //  (all of the values in the drop down list)
            foreach (StatusOptionMetadata statusMeta in
                     statusAttrMetadata.OptionSet.Options)
            {
                // Check to see if our current value matches
                if (statusMeta.Value == statusCode)
                {
                    // If our numeric value matches, set the string to our status code
                    //  label
                    return(statusMeta.Label.UserLocalizedLabel.Label);
                }
            }

            // if we got this far, something didn't add up.
            return(string.Empty);
        }
Esempio n. 6
0
        /// <summary>
        /// Get PickList Metadata
        /// </summary>
        /// <param name="entityLogicalName"></param>
        /// <param name="logicalName"></param>
        /// <returns></returns>
        private static OptionMetadataCollection _GetPicklistMetaData(string entityLogicalName, string logicalName)
        {
            var result = new OptionMetadataCollection();

            RetrieveAttributeRequest request = new RetrieveAttributeRequest();

            request.EntityLogicalName     = entityLogicalName;
            request.LogicalName           = logicalName; // get the reference type
            request.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse response;

            try
            {
                using (OrganizationService svc = new OrganizationService(new CrmConnection("Crm")))
                {
                    response = (RetrieveAttributeResponse)svc.Execute(request);
                }

                if (response.AttributeMetadata is StatusAttributeMetadata)
                {
                    StatusAttributeMetadata  picklist = (StatusAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection omd      = picklist.OptionSet.Options;
                    result = omd;
                }
                else
                {
                    PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)response.AttributeMetadata;
                    OptionMetadataCollection  omd      = picklist.OptionSet.Options;
                    result = omd;
                }
                return(result);
            }
            catch (Exception ex)
            {
                Util.WriteErrorToLog("_GetPicklistMetaData", new Dictionary <string, string>()
                {
                    { "entityLogicalName", entityLogicalName },
                    { "logicalName", logicalName }
                }, ex);
                throw ex;
            }
        }
        public void OptionSetBeanTest03()
        {
            LocalizedLabel lLabel = new LocalizedLabel("Option1", 1041);

            StatusAttributeMetadata meta = new StatusAttributeMetadata();
            meta.OptionSet = new OptionSetMetadata()
            {
                Name = "optionSet",
                DisplayName = new Label("optiondisplay", LANG_CODE),
                Options =
                {
                     new OptionMetadata(new Label(lLabel, null), 1)
                }
            };

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.True(cls.HasOptionSet());
            Assert.AreEqual("Option1", cls.GetValue(1), "ラベルあり");
        }
        public void OptionSetBeanTest03()
        {
            LocalizedLabel lLabel = new LocalizedLabel("Option1", 1041);

            StatusAttributeMetadata meta = new StatusAttributeMetadata();

            meta.OptionSet = new OptionSetMetadata()
            {
                Name        = "optionSet",
                DisplayName = new Label("optiondisplay", LANG_CODE),
                Options     =
                {
                    new OptionMetadata(new Label(lLabel, null), 1)
                }
            };

            OptionSetBean cls = new OptionSetBean(meta);

            Assert.True(cls.HasOptionSet());
            Assert.AreEqual("Option1", cls.GetValue(1), "ラベルあり");
        }
        private void GenerateStateEnums(StateAttributeMetadata stateAttr, StatusAttributeMetadata statusAttr)
        {
            WriteLine(",");
            WriteLine();
            WriteLine("'StateCodes': {");

            var options = GetStateOptionItems(statusAttr, stateAttr, this._listStringMap);

            WriteLine();

            bool first = true;

            // Формируем значения
            foreach (var item in options)
            {
                WriteCommaIfNotFirstLine(ref first);

                Write(item.MakeStringJS());
            }

            WriteLine();
            Write("}");
        }
        private void WriteStateStatusEnums()
        {
            StateAttributeMetadata  stateAttr  = null;
            StatusAttributeMetadata statusAttr = null;

            foreach (AttributeMetadata attrib in _entityMetadata.Attributes.OrderBy(attr => attr.LogicalName))
            {
                if (attrib is StatusAttributeMetadata)
                {
                    statusAttr = attrib as StatusAttributeMetadata;
                }
                else if (attrib is StateAttributeMetadata)
                {
                    stateAttr = attrib as StateAttributeMetadata;
                }
            }

            if (stateAttr != null && statusAttr != null)
            {
                GenerateStateEnums(stateAttr, statusAttr);

                GenerateStatusEnums(statusAttr, stateAttr);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// フィールドのオプションセットを取得する。
        /// </summary>
        /// <param name="attr"></param>
        public OptionSetBean(AttributeMetadata attr)
        {
            valueMap = new Dictionary <int, Label>();
            PicklistAttributeMetadata picklistAttr = attr as PicklistAttributeMetadata;
            StateAttributeMetadata    stateAttr    = attr as StateAttributeMetadata;
            StatusAttributeMetadata   statusAttr   = attr as StatusAttributeMetadata;

            // オプションセットを取得する。
            OptionSetMetadata option = null;

            if (picklistAttr != null)
            {
                option = picklistAttr.OptionSet;
            }
            else if (stateAttr != null)
            {
                option = stateAttr.OptionSet;
            }
            else if (statusAttr != null)
            {
                option = statusAttr.OptionSet;
            }
            else
            {
                return;
            }


            foreach (OptionMetadata opt in option.Options)
            {
                if (opt.Value != null)
                {
                    valueMap.Add((int)opt.Value, opt.Label);
                }
            }
        }
Esempio n. 12
0
        public void CreateOrUpdateStatusAttribute(string schemaName, string displayName, string description,
            bool isRequired, bool audit, bool searchable,
            string recordType)
        {
            StatusAttributeMetadata metadata;
            if (FieldExists(schemaName, recordType))
                metadata = (StatusAttributeMetadata) GetFieldMetadata(schemaName, recordType);
            else
                metadata = new StatusAttributeMetadata();
            SetCommon(metadata, schemaName, displayName, description, isRequired, audit, searchable);

            CreateOrUpdateAttribute(schemaName, recordType, metadata);

            if (GetEntityMetadata(recordType).PrimaryNameAttribute == schemaName)
                RefreshEntityMetadata(recordType);
        }
Esempio n. 13
0
        public void Reproduce_issue_278()
        {
            string attributeName = "statuscode";
            string label         = "A faked label";

            XrmFakedContext fakedContext = new XrmFakedContext
            {
                ProxyTypesAssembly = (Assembly.GetAssembly(typeof(Contact)))
            };

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };

            StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata()
            {
                LogicalName = attributeName
            };

            entityMetadata.SetAttributeCollection(new List <AttributeMetadata>()
            {
                enumAttribute
            });

            var req = new InsertOptionValueRequest()
            {
                EntityLogicalName    = Contact.EntityLogicalName,
                AttributeLogicalName = attributeName,
                Label = new Label(label, 0)
            };

            fakedContext.InitializeMetadata(entityMetadata);

            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedService.Execute(req);


            //Check the optionsetmetadata was updated
            var key = string.Format("{0}#{1}", Contact.EntityLogicalName, attributeName);

            Assert.True(fakedContext.OptionSetValuesMetadata.ContainsKey(key));

            var option = fakedContext.OptionSetValuesMetadata[key].Options.FirstOrDefault();

            Assert.Equal(label, option.Label.LocalizedLabels[0].Label);

            // Get a list of Option Set values for the Status Reason fields from its metadata
            RetrieveAttributeRequest attReq = new RetrieveAttributeRequest();

            attReq.EntityLogicalName     = "contact";
            attReq.LogicalName           = "statuscode";
            attReq.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)fakedService.Execute(attReq);

            // Cast as StatusAttributeMetadata
            StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata;

            Assert.Equal(label, statusAttributeMetadata.OptionSet.Options.First().Label.LocalizedLabels[0].Label);
            //Assert.Equal(label, statusAttributeMetadata.OptionSet.Options.First().Label.UserLocalizedLabel.Label); This one is null when using the above Label constructor
        }
 // ReSharper disable once UnusedParameter.Local
 private AttributeMetadata CloneAttributes(StatusAttributeMetadata att)
 {
     return new StatusAttributeMetadata();
 }
Esempio n. 15
0
        public static DataTable GetDropDownOptions(string entityName, string attributeName)
        {
            OrganizationServiceProxy serviceProxy = CrmHelper.Connect();

            DataTable options = new DataTable();

            options.Columns.Add("Value");
            options.Columns.Add("Name");

            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName = entityName,
                LogicalName       = attributeName
            };

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

            // Handle Picklist options
            if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Picklist)
            {
                PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata;
                foreach (OptionMetadata option in picklist.OptionSet.Options)
                {
                    DataRow optionDataRow = options.NewRow();
                    optionDataRow["Value"] = option.Value.Value;
                    optionDataRow["Name"]  = option.Label.UserLocalizedLabel.Label;

                    options.Rows.Add(optionDataRow);
                }
            }

            // Handle Status options (Active State only)
            else if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.Status)
            {
                StatusAttributeMetadata status = (StatusAttributeMetadata)attributeResponse.AttributeMetadata;
                foreach (StatusOptionMetadata option in status.OptionSet.Options)
                {
                    //if (option.State.Value == 0) // Active State
                    //{
                    DataRow optionDataRow = options.NewRow();
                    optionDataRow["Value"] = option.Value.Value;
                    optionDataRow["Name"]  = option.Label.UserLocalizedLabel.Label;

                    options.Rows.Add(optionDataRow);
                    //}
                }
            }
            // Handle Status options (Active State only)
            else if (attributeResponse.AttributeMetadata.AttributeType == AttributeTypeCode.EntityName)
            {
                EntityNameAttributeMetadata name = (EntityNameAttributeMetadata)attributeResponse.AttributeMetadata;
                foreach (OptionMetadata option in name.OptionSet.Options)
                {
                    DataRow optionDataRow = options.NewRow();
                    optionDataRow["Value"] = option.Value.Value;
                    optionDataRow["Name"]  = option.Label.UserLocalizedLabel.Label;

                    options.Rows.Add(optionDataRow);
                }
            }
            return(options);
        }
 public StatusAttributeMetadataInfo(StatusAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
        public void MapAttributes(Entity entity, object[] data)
        {
            foreach (var dataMapping in this.mappings)
            {
                AttributeMetadata attributeMetadata = this.attributeMetadataDictionary[dataMapping.Target];
                object            obj = data[this.columnMetadataDictionary[dataMapping.Source].ColumnIndex];

                if (obj == null || string.IsNullOrEmpty(obj.ToString()))
                {
                    entity.Attributes.Add(dataMapping.Target, null);
                    continue;
                }

                switch (attributeMetadata.AttributeType.Value)
                {
                case AttributeTypeCode.BigInt:
                    long longValue = Convert.ToInt64(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, longValue);
                    break;

                case AttributeTypeCode.Boolean:
                    bool booleanValue = Convert.ToBoolean(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, booleanValue);
                    break;

                case AttributeTypeCode.Customer:
                    LookupAttributeMetadata customerMetadata = attributeMetadata as LookupAttributeMetadata;
                    Guid customerId = new Guid(obj.ToString());
                    //entity.Attributes.Add(customerMetadata.LogicalName, new EntityReference(customerMetadata.)
                    throw new Exception("Direct Customer Attribute Mapping not supported!");

                case AttributeTypeCode.DateTime:
                    if (obj.GetType() == typeof(DateTime))
                    {
                        entity.Attributes.Add(dataMapping.Target, (DateTime)obj);
                    }
                    else
                    {
                        DateTime?dt = DateTimeHelper.ConvertStringToDateTime(obj.ToString(), dataMapping.ValueFormat);
                        if (dt != null)
                        {
                            entity.Attributes.Add(attributeMetadata.LogicalName, dt);
                        }
                        else
                        {
                            throw new Exception("Could not convert value " + obj.ToString() + " to datetime. Please correct value or check valueformat!");
                        }
                    }
                    break;

                case AttributeTypeCode.Decimal:
                    try
                    {
                        decimal decimalValue = Convert.ToDecimal(obj.ToString());
                        entity.Attributes.Add(dataMapping.Target, decimalValue);
                    }
                    catch (FormatException)
                    {
                        throw new FormatException("Could not convert value '" + obj.ToString() + "' to decimal.");
                    }
                    break;

                case AttributeTypeCode.Double:
                    double doubleValue = Convert.ToDouble(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, doubleValue);
                    break;

                case AttributeTypeCode.Integer:
                    int intValue = Convert.ToInt32(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, intValue);
                    break;

                case AttributeTypeCode.Owner:
                case AttributeTypeCode.Lookup:
                    LookupAttributeMetadata lookupMetadata = attributeMetadata as LookupAttributeMetadata;
                    Guid lookupId = new Guid(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, new EntityReference(lookupMetadata.Targets[0], lookupId));
                    break;

                case AttributeTypeCode.Money:
                    decimal moneyValue = Convert.ToDecimal(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, new Money(moneyValue));
                    break;

                case AttributeTypeCode.Memo:
                case AttributeTypeCode.String:
                    string stringValue = obj.ToString();
                    if (string.IsNullOrEmpty(stringValue))
                    {
                        stringValue = null;
                    }
                    entity.Attributes.Add(dataMapping.Target, stringValue);
                    break;

                case AttributeTypeCode.Status:
                case AttributeTypeCode.Picklist:
                    IntegrationTool.Module.WriteToDynamicsCrm.SDK.PicklistMapping picklistMapping = this.picklistMappings.Where(t => t.LogicalName == dataMapping.Target).First();
                    int optionValue = -1;
                    switch (picklistMapping.MappingType)
                    {
                    case SDK.Enums.PicklistMappingType.Automatic:
                        optionValue = Convert.ToInt32(obj.ToString());
                        break;

                    case SDK.Enums.PicklistMappingType.Manual:
                        var mapping = picklistMapping.Mapping.Where(t => t.Source == obj.ToString()).FirstOrDefault();
                        if (mapping == null && !String.IsNullOrEmpty(obj.ToString()))
                        {
                            switch (picklistMapping.MappingNotFound)
                            {
                            case SDK.Enums.MappingNotFoundType.FailImport:
                                throw new Exception("Could not map picklist " + dataMapping.Target + ": Mapping for source-value " + obj.ToString() + " could not be found!");

                            case SDK.Enums.MappingNotFoundType.Ignore:
                                // Ignore simply does nothing
                                break;

                            case SDK.Enums.MappingNotFoundType.SetDefaultValue:
                                optionValue = Convert.ToInt32(picklistMapping.DefaultValue);
                                break;
                            }
                        }
                        if (mapping != null)
                        {
                            optionValue = Convert.ToInt32(mapping.Target);
                        }
                        break;
                    }

                    if (optionValue != -1)
                    {
                        if (dataMapping.Target == "statuscode")
                        {
                            StatusAttributeMetadata statusAttributeMetadata = attributeMetadata as StatusAttributeMetadata;
                            var statusOptionMetadata = statusAttributeMetadata.OptionSet.Options.Where(t => t.Value == optionValue).First() as StatusOptionMetadata;
                            entity.Attributes.Add("statecode", new OptionSetValue(statusOptionMetadata.State.Value));
                        }
                        entity.Attributes.Add(dataMapping.Target, new OptionSetValue(optionValue));
                    }
                    break;

                case AttributeTypeCode.Uniqueidentifier:
                    Guid id = new Guid(obj.ToString());
                    entity.Attributes.Add(dataMapping.Target, id);
                    break;

                default:
                    throw new Exception("Could not convert attribute with type " + attributeMetadata.AttributeType.Value.ToString());
                }
            }
        }
Esempio n. 18
0
        public void Should_store_user_localized_label()
        {
            var label         = "fake";
            var attributeName = "statuscode";
            var ctx           = new XrmFakedContext();

            LocalizedLabel localizedLabel1 = new LocalizedLabel(label, 10);
            LocalizedLabel localizedLabel2 = new LocalizedLabel("falso", 10);

            LocalizedLabel[] localizedLabels = new LocalizedLabel[] { localizedLabel1, localizedLabel2 };

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };

            StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata()
            {
                LogicalName = attributeName
            };

            entityMetadata.SetAttributeCollection(new List <AttributeMetadata>()
            {
                enumAttribute
            });

            ctx.InitializeMetadata(entityMetadata);

            var req = new InsertOptionValueRequest()
            {
                EntityLogicalName    = Contact.EntityLogicalName,
                AttributeLogicalName = attributeName,
                Label = new Label(localizedLabel1, localizedLabels)
            };

            var service = ctx.GetOrganizationService();

            service.Execute(req);

            //Check the optionsetmetadata was updated
            var key = $"{Contact.EntityLogicalName}#{attributeName}";

            Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key));

            var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault();

            Assert.Equal(label, option.Label.LocalizedLabels[0].Label);

            // Get a list of Option Set values for the Status Reason fields from its metadata
            RetrieveAttributeRequest attReq = new RetrieveAttributeRequest
            {
                EntityLogicalName     = "contact",
                LogicalName           = "statuscode",
                RetrieveAsIfPublished = true
            };

            RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq);

            StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata;

            Assert.NotNull(statusAttributeMetadata.OptionSet);
            Assert.NotNull(statusAttributeMetadata.OptionSet.Options);
            Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Count(o => o.Label.LocalizedLabels[0].Label == label));

            foreach (var optionMetadata in statusAttributeMetadata.OptionSet.Options)
            {
                Console.WriteLine("Key " + optionMetadata.Value + "                    Value: " + optionMetadata.Label.UserLocalizedLabel.Label);
            }
        }
Esempio n. 19
0
        public static IEnumerable <EntityMetadata> FromEarlyBoundEntities(Assembly earlyBoundEntitiesAssembly)
        {
            List <EntityMetadata> entityMetadatas = new List <EntityMetadata>();

            foreach (var earlyBoundEntity in earlyBoundEntitiesAssembly.GetTypes())
            {
                EntityLogicalNameAttribute entityLogicalNameAttribute = GetCustomAttribute <EntityLogicalNameAttribute>(earlyBoundEntity);
                if (entityLogicalNameAttribute == null)
                {
                    continue;
                }
                EntityMetadata metadata = new EntityMetadata();
                metadata.LogicalName = entityLogicalNameAttribute.LogicalName;

                FieldInfo entityTypeCode = earlyBoundEntity.GetField("EntityTypeCode", BindingFlags.Static | BindingFlags.Public);
                if (entityTypeCode != null)
                {
                    metadata.SetFieldValue("_objectTypeCode", entityTypeCode.GetValue(null));
                }

                List <AttributeMetadata> attributeMetadatas = new List <AttributeMetadata>();
                List <ManyToManyRelationshipMetadata> manyToManyRelationshipMetadatas = new List <ManyToManyRelationshipMetadata>();
                List <OneToManyRelationshipMetadata>  oneToManyRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();
                List <OneToManyRelationshipMetadata>  manyToOneRelationshipMetadatas  = new List <OneToManyRelationshipMetadata>();

                var idProperty = earlyBoundEntity.GetProperty("Id");
                AttributeLogicalNameAttribute attributeLogicalNameAttribute;
                if (idProperty != null && (attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(idProperty)) != null)
                {
                    metadata.SetFieldValue("_primaryIdAttribute", attributeLogicalNameAttribute.LogicalName);
                }

                var properties = earlyBoundEntity.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                 .Where(x => x.Name != "Id" && Attribute.IsDefined(x, typeof(AttributeLogicalNameAttribute)) ||
                                        Attribute.IsDefined(x, typeof(RelationshipSchemaNameAttribute)));

                foreach (var property in properties)
                {
                    RelationshipSchemaNameAttribute relationshipSchemaNameAttribute = GetCustomAttribute <RelationshipSchemaNameAttribute>(property);
                    attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(property);

                    if (relationshipSchemaNameAttribute == null)
                    {
#if !FAKE_XRM_EASY
                        if (property.PropertyType == typeof(byte[]))
                        {
                            metadata.SetFieldValue("_primaryImageAttribute", attributeLogicalNameAttribute.LogicalName);
                        }
#endif
                        AttributeMetadata attributeMetadata;
                        if (attributeLogicalNameAttribute.LogicalName == "statecode")
                        {
                            attributeMetadata = new StateAttributeMetadata();
                        }
                        else if (attributeLogicalNameAttribute.LogicalName == "statuscode")
                        {
                            attributeMetadata = new StatusAttributeMetadata();
                        }
                        else if (attributeLogicalNameAttribute.LogicalName == metadata.PrimaryIdAttribute)
                        {
                            attributeMetadata = new AttributeMetadata();
                            attributeMetadata.SetSealedPropertyValue("AttributeType", AttributeTypeCode.Uniqueidentifier);
                        }
                        else
                        {
                            attributeMetadata = CreateAttributeMetadata(property.PropertyType);
                        }

                        attributeMetadata.SetFieldValue("_entityLogicalName", entityLogicalNameAttribute.LogicalName);
                        attributeMetadata.SetFieldValue("_logicalName", attributeLogicalNameAttribute.LogicalName);

                        attributeMetadatas.Add(attributeMetadata);
                    }
                    else
                    {
                        if (property.PropertyType.Name == "IEnumerable`1")
                        {
                            PropertyInfo peerProperty = property.PropertyType.GetGenericArguments()[0].GetProperties().SingleOrDefault(x => x.PropertyType == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName);
                            if (peerProperty == null || peerProperty.PropertyType.Name == "IEnumerable`1") // N:N relationship
                            {
                                ManyToManyRelationshipMetadata relationshipMetadata = new ManyToManyRelationshipMetadata();
                                relationshipMetadata.SchemaName = relationshipSchemaNameAttribute.SchemaName;

                                manyToManyRelationshipMetadatas.Add(relationshipMetadata);
                            }
                            else // 1:N relationship
                            {
                                AddOneToManyRelationshipMetadata(earlyBoundEntity, property, property.PropertyType.GetGenericArguments()[0], peerProperty, oneToManyRelationshipMetadatas);
                            }
                        }
                        else //N:1 Property
                        {
                            AddOneToManyRelationshipMetadata(property.PropertyType, property.PropertyType.GetProperties().SingleOrDefault(x => x.PropertyType.GetGenericArguments().SingleOrDefault() == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName), earlyBoundEntity, property, manyToOneRelationshipMetadatas);
                        }
                    }
                }
                if (attributeMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("Attributes", attributeMetadatas.ToArray());
                }
                if (manyToManyRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("ManyToManyRelationships", manyToManyRelationshipMetadatas.ToArray());
                }
                if (manyToOneRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("ManyToOneRelationships", manyToOneRelationshipMetadatas.ToArray());
                }
                if (oneToManyRelationshipMetadatas.Any())
                {
                    metadata.SetSealedPropertyValue("OneToManyRelationships", oneToManyRelationshipMetadatas.ToArray());
                }
                entityMetadatas.Add(metadata);
            }
            return(entityMetadatas);
        }
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    String entityLogicalName = "incident";
                    // Retrieve status options for the Incident entity

                    //Retrieve just the incident entity and its attributes
                    MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                    entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
                    MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes" });

                    //Retrieve just the status attribute and the OptionSet property
                    MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
                    attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
                    MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

                    //Instantiate the entity query
                    EntityQueryExpression query = new EntityQueryExpression()
                    {
                        Criteria       = entityFilter,
                        Properties     = entityProperties,
                        AttributeQuery = new AttributeQueryExpression()
                        {
                            Criteria = attributeFilter, Properties = attributeProperties
                        }
                    };

                    //Retrieve the metadata
                    RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
                    {
                        Query = query
                    };
                    RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)service.Execute(request);


                    StatusAttributeMetadata  statusAttribute = (StatusAttributeMetadata)response.EntityMetadata[0].Attributes[0];
                    OptionMetadataCollection statusOptions   = statusAttribute.OptionSet.Options;
                    //Loop through each of the status options
                    foreach (StatusOptionMetadata option in statusOptions)
                    {
                        String StatusOptionLabel = GetOptionSetLabel(service, statusAttribute, option.Value.Value);
                        Console.WriteLine("[{0}] {1} records can transition to:", StatusOptionLabel, entityLogicalName);
                        List <StatusOption> validStatusOptions = GetValidStatusOptions(service, entityLogicalName, option.Value.Value);
                        //Loop through each valid transition for the option
                        foreach (StatusOption opt in validStatusOptions)
                        {
                            Console.WriteLine("{0,-3}{1,-10}{2,-5}{3,-10}", opt.StateValue, opt.StateLabel, opt.StatusValue, opt.StatusLabel);
                        }
                        Console.WriteLine("");
                    }
                }

                #endregion Demonstrate
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            #endregion Sample Code
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Esempio n. 21
0
  //<snippetStateModelTransitions.GetValidStatusOptions>
  /// <summary>
  /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity
  /// </summary>
  /// <param name="entityLogicalName">The logical name of the entity</param>
  /// <param name="currentStatusValue">The current status of the entity instance</param>
  /// <returns>A list of StatusOptions that represent the valid transitions</returns>
  public List<StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue)
  {

   List<StatusOption> validStatusOptions = new List<StatusOption>();

   //Check entity Metadata

   //Retrieve just one entity definition
   MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
   entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
   //Return the attributes and the EnforceStateTransitions property
   MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

   //Retrieve only State or Status attributes
   MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
   attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

   //Retrieve only the OptionSet property of the attributes
   MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

   //Set the query
   EntityQueryExpression query = new EntityQueryExpression()
   {
    Criteria = entityFilter,
    Properties = entityProperties,
    AttributeQuery = new AttributeQueryExpression() { Criteria = attributeFilter, Properties = attributeProperties }
   };

   //Retrieve the metadata
   RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest() { Query = query };
   RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

   //Check the value of EnforceStateTransitions
   Boolean? EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions;

   //Capture the state and status attributes
   StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
   StateAttributeMetadata stateAttribute = new StateAttributeMetadata();

   foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes)
   {
    switch (attributeMetadata.AttributeType)
    {
     case AttributeTypeCode.Status:
      statusAttribute = (StatusAttributeMetadata)attributeMetadata;
      break;
     case AttributeTypeCode.State:
      stateAttribute = (StateAttributeMetadata)attributeMetadata;
      break;
    }
   }


   if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
   {
    //When EnforceStateTransitions is true use the TransitionData to filter the valid options
    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value == currentStatusValue)
     {
      if (option.TransitionData != String.Empty)
      {
       XDocument transitionData = XDocument.Parse(option.TransitionData);

       IEnumerable<XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

       foreach (XElement e in elements)
       {
        int statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
        String statusLabel = GetOptionSetLabel(statusAttribute, statusOptionValue);

        string stateLabel = String.Empty;
        int? stateValue = null;
        foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
        {
         if (statusOption.Value.Value == statusOptionValue)
         {
          stateValue = statusOption.State.Value;
          stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
         }

        }


        validStatusOptions.Add(new StatusOption()
        {
         StateLabel = stateLabel,
         StateValue = stateValue.Value,
         StatusLabel = statusLabel,
         StatusValue = option.Value.Value
        });
       }
      }
     }
    }

   }
   else
   {
    ////When EnforceStateTransitions is false do not filter the available options

    foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
    {
     if (option.Value != currentStatusValue)
     {

      String statusLabel = "";
      try
      {
       statusLabel = option.Label.UserLocalizedLabel.Label;
      }
      catch (Exception)
      {
       statusLabel = option.Label.LocalizedLabels[0].Label;
      };

      String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

      validStatusOptions.Add(new StatusOption()
      {
       StateLabel = stateLabel,
       StateValue = option.State.Value,
       StatusLabel = statusLabel,
       StatusValue = option.Value.Value

      });
     }
    }
   }
   return validStatusOptions;

  }
Esempio n. 22
0
        /// <summary>
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    //<snippetDumpPicklistInfo1>
                    #region How to dump attribute info
                    //<snippetDumpPicklistInfo2>
                    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        XmlTextWriter metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    //</snippetDumpPicklistInfo2>
                    #endregion How to dump attribute info



                    Console.WriteLine("Done.");
                    //</snippetDumpPicklistInfo1>

                    //DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
 public StatusAttributeMetadataInfo(StatusAttributeMetadata amd)
     : base(amd)
 {
     this.amd = amd;
 }
Esempio n. 24
0
        public static object ConvertValue(object input, FieldMap map, AttributeMetadata field, IOrganizationService service)
        {
            if (map.Convert.Length != 0)
            {
                foreach (var converter in map.Convert)
                {
                    input = converter.Convert(input, service);
                }
            }

            if (input == null)
            {
                return(null);
            }

            if (input is int && field.AttributeType == AttributeTypeCode.Integer)
            {
                return(input);
            }

            if (input is double && field.AttributeType == AttributeTypeCode.Integer)
            {
                return((int)((double)input));
            }

            if (input is string && field.AttributeType == AttributeTypeCode.String)
            {
                return(input);
            }

            if (input is EntityReference && field.AttributeType == AttributeTypeCode.Lookup)
            {
                return(input);
            }

            if (input is OptionSetValue && field.AttributeType == AttributeTypeCode.Picklist)
            {
                return(input);
            }

            if (input is decimal && field.AttributeType == AttributeTypeCode.Decimal)
            {
                return(input);
            }

            if (input is double && field.AttributeType == AttributeTypeCode.Decimal)
            {
                return(Convert.ToDecimal(input));
            }

            if (input is int && field.AttributeType == AttributeTypeCode.Decimal)
            {
                return((decimal)((int)input));
            }

            if (input is Single && field.AttributeType == AttributeTypeCode.Decimal)
            {
                return((decimal)((Single)input));
            }

            if (input is string && field.AttributeType == AttributeTypeCode.Picklist)
            {
                PicklistAttributeMetadata picklist = (PicklistAttributeMetadata)field;
                var tmp = picklist.OptionSet.Options.FirstOrDefault(o => o.Label.UserLocalizedLabel.Label == (string)input);
                if (tmp != null)
                {
                    return(new OptionSetValue(tmp.Value.Value));
                }
                return(null);
            }

            if (field.AttributeType == AttributeTypeCode.String)
            {
                return(input.ToString());
            }

            if (input is string && field.AttributeType == AttributeTypeCode.Boolean)
            {
                BooleanAttributeMetadata boolMetadata = (BooleanAttributeMetadata)field;
                return(boolMetadata.OptionSet.TrueOption.Label.UserLocalizedLabel.Label == (string)input);
            }

            if (input is bool && field.AttributeType == AttributeTypeCode.Boolean)
            {
                return(input);
            }

            if (input is float && field.AttributeType == AttributeTypeCode.Double)
            {
                return(Convert.ToDouble((float)input));
            }

            if (input is double && field.AttributeType == AttributeTypeCode.Double)
            {
                return((double)input);
            }

            if (input is string && field.AttributeType == AttributeTypeCode.Status)
            {
                StatusAttributeMetadata picklist = (StatusAttributeMetadata)field;
                var tmp = picklist.OptionSet.Options.FirstOrDefault(o => o.Label.UserLocalizedLabel.Label == (string)input);
                if (tmp != null)
                {
                    return(new OptionSetValue(tmp.Value.Value));
                }
                return(null);
            }


            throw new Exception($"No conversion for field {field.LogicalName} input: {input.GetType().Name} output: {field.AttributeTypeName.Value}");
        }
Esempio n. 25
0
        public void Should_update_entity_metadata_with_status()
        {
            var label         = "dummy status";
            var attributeName = "statuscode";
            var value         = 1;
            var statecode     = 1;
            var ctx           = new XrmFakedContext();

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };
            StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata()
            {
                LogicalName = attributeName
            };

            entityMetadata.SetAttributeCollection(new List <AttributeMetadata>()
            {
                enumAttribute
            });

            ctx.InitializeMetadata(entityMetadata);

            var req = new InsertStatusValueRequest()
            {
                EntityLogicalName    = Contact.EntityLogicalName,
                AttributeLogicalName = attributeName,
                Label     = new Microsoft.Xrm.Sdk.Label(label, 0),
                Value     = value,
                StateCode = statecode
            };

            var service = ctx.GetOrganizationService();

            service.Execute(req);

            //Check the status metadata was updated
            var key = $"{Contact.EntityLogicalName}#{attributeName}";

            Assert.True(ctx.StatusAttributeMetadata.ContainsKey(key));

            var option = ctx.StatusAttributeMetadata[key].OptionSet.Options.FirstOrDefault();

            Assert.Equal(label, option.Label.LocalizedLabels[0].Label);

            // Get a list of Status values for the Status Reason fields from its metadata
            RetrieveAttributeRequest attReq = new RetrieveAttributeRequest
            {
                EntityLogicalName     = "contact",
                LogicalName           = "statuscode",
                RetrieveAsIfPublished = true
            };

            RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq);

            StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata;

            Assert.NotNull(statusAttributeMetadata.OptionSet);
            Assert.NotNull(statusAttributeMetadata.OptionSet.Options);
            Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Count(o => o.Label.LocalizedLabels[0].Label == label));
            Assert.Equal(statecode, ((StatusOptionMetadata)statusAttributeMetadata.OptionSet.Options[0]).State);

            Assert.Equal(statecode, ((StatusOptionMetadata)statusAttributeMetadata.OptionSet.Options.FirstOrDefault(o => o.Label.LocalizedLabels[0].Label == label)).State);
        }
Esempio n. 26
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate
                    var request = new RetrieveAllEntitiesRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false.
                        // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published.
                        RetrieveAsIfPublished = false
                    };

                    // Retrieve the MetaData.
                    var response = (RetrieveAllEntitiesResponse)service.Execute(request);

                    // Create an instance of StreamWriter to write text to a file.
                    // The using statement also closes the StreamWriter.
                    // To view this file, right click the file and choose open with Excel.
                    // Excel will figure out the schema and display the information in columns.

                    String filename = String.Concat("AttributePicklistValues.xml");
                    using (var sw = new StreamWriter(filename))
                    {
                        // Create Xml Writer.
                        var metadataWriter = new XmlTextWriter(sw);

                        // Start Xml File.
                        metadataWriter.WriteStartDocument();

                        // Metadata Xml Node.
                        metadataWriter.WriteStartElement("Metadata");

                        foreach (EntityMetadata currentEntity in response.EntityMetadata)
                        {
                            if (currentEntity.IsIntersect.Value == false)
                            {
                                // Start Entity Node
                                metadataWriter.WriteStartElement("Entity");

                                // Write the Entity's Information.
                                metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
                                if (currentEntity.IsCustomizable.Value == true)
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "yes");
                                }
                                else
                                {
                                    metadataWriter.WriteElementString("IsCustomizable", "no");
                                }

                                #region Attributes

                                // Write Entity's Attributes.
                                metadataWriter.WriteStartElement("Attributes");

                                foreach (AttributeMetadata currentAttribute in currentEntity.Attributes)
                                {
                                    // Only write out main attributes.
                                    if (currentAttribute.AttributeOf == null)
                                    {
                                        // Start Attribute Node
                                        metadataWriter.WriteStartElement("Attribute");

                                        // Write Attribute's information.
                                        metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName);
                                        metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString());

                                        if (currentAttribute.GetType() == typeof(PicklistAttributeMetadata))
                                        {
                                            PicklistAttributeMetadata optionMetadata = (PicklistAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StateAttributeMetadata))
                                        {
                                            StateAttributeMetadata optionMetadata = (StateAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }
                                        else if (currentAttribute.GetType() == typeof(StatusAttributeMetadata))
                                        {
                                            StatusAttributeMetadata optionMetadata = (StatusAttributeMetadata)currentAttribute;
                                            // Writes the picklist's options
                                            metadataWriter.WriteStartElement("Options");

                                            // Writes the attributes of each picklist option
                                            for (int c = 0; c < optionMetadata.OptionSet.Options.Count; c++)
                                            {
                                                metadataWriter.WriteStartElement("Option");
                                                metadataWriter.WriteElementString("OptionValue", optionMetadata.OptionSet.Options[c].Value.Value.ToString());
                                                metadataWriter.WriteElementString("OptionDescription", optionMetadata.OptionSet.Options[c].Label.UserLocalizedLabel.Label.ToString());
                                                if (optionMetadata.OptionSet.Options[c] is StatusOptionMetadata)
                                                {
                                                    metadataWriter.WriteElementString("RelatedToState", ((StatusOptionMetadata)optionMetadata.OptionSet.Options[c]).State.ToString());
                                                }
                                                metadataWriter.WriteEndElement();
                                            }

                                            metadataWriter.WriteEndElement();
                                        }

                                        // End Attribute Node
                                        metadataWriter.WriteEndElement();
                                    }
                                }
                                // End Attributes Node
                                metadataWriter.WriteEndElement();

                                #endregion

                                // End Entity Node
                                metadataWriter.WriteEndElement();
                            }
                        }

                        // End Metadata Xml Node
                        metadataWriter.WriteEndElement();
                        metadataWriter.WriteEndDocument();

                        // Close xml writer.
                        metadataWriter.Close();
                    }

                    Console.WriteLine("Done.");
                    #endregion Demonstrate
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
        public void Should_also_update_entity_metadata_when_not_using_global_option_set()
        {
            var label         = "dummy label";
            var attributeName = "statuscode";
            var ctx           = new XrmFakedContext();

            XrmFakedContext fakedContext = new XrmFakedContext
            {
                ProxyTypesAssembly = (Assembly.GetAssembly(typeof(Contact)))
            };

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };
            StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata()
            {
                LogicalName = attributeName
            };

            entityMetadata.SetAttributeCollection(new List <AttributeMetadata>()
            {
                enumAttribute
            });

            ctx.InitializeMetadata(entityMetadata);

            var req = new InsertOptionValueRequest()
            {
                EntityLogicalName    = Contact.EntityLogicalName,
                AttributeLogicalName = attributeName,
                Label = new Label(label, 0)
            };

            var service = ctx.GetOrganizationService();

            service.Execute(req);

            //Check the optionsetmetadata was updated
            var key = string.Format("{0}#{1}", Contact.EntityLogicalName, attributeName);

            Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key));

            var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault();

            Assert.Equal(label, option.Label.LocalizedLabels[0].Label);

            // Get a list of Option Set values for the Status Reason fields from its metadata
            RetrieveAttributeRequest attReq = new RetrieveAttributeRequest();

            attReq.EntityLogicalName     = "contact";
            attReq.LogicalName           = "statuscode";
            attReq.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq);

            StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata;

            Assert.NotNull(statusAttributeMetadata.OptionSet);
            Assert.NotNull(statusAttributeMetadata.OptionSet.Options);
            Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Where(o => o.Label.LocalizedLabels[0].Label == label).Count());
        }
Esempio n. 28
0
 // ReSharper disable once UnusedParameter.Local
 private AttributeMetadata CloneAttributes(StatusAttributeMetadata att)
 {
     return(new StatusAttributeMetadata());
 }
        protected override string GetRequestDescription(OrganizationRequest request)
        {
            Guid   id     = Guid.Empty;
            string state  = mode == SetStateMode.Fixed ? State.Name : "<State>";
            string status = mode == SetStateMode.Fixed ? Status.Name : "<Status>";

            if (request is UpdateRequest updateRequest)
            {
                id = updateRequest.Target.Id;
            }
            else if (request is SetStateRequest setStateRequest)
            {
                id = setStateRequest.EntityMoniker.Id;
            }
            else if (request is CloseIncidentRequest closeIncidentRequest)
            {
                id    = ((EntityReference)closeIncidentRequest.IncidentResolution[CASE_RESOLUTION_INCIDENT_ID]).Id;
                state = "Resolved";

                EntityMetadata          metadata       = Dynamics365Entity.Create(CASE_ENTITY_NAME, Connection).GetEntityMetadata(Connection);
                StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME));
                status = statusMetadata.OptionSet.Options.First(option => option.Value == closeIncidentRequest.Status.Value).Label.UserLocalizedLabel.Label;
            }
            else if (request is ReviseQuoteRequest reviseQuoteRequest)
            {
                id     = reviseQuoteRequest.QuoteId;
                state  = "Draft";
                status = "In Progress";
            }
            else if (request is WinQuoteRequest winQuoteRequest)
            {
                id     = ((EntityReference)winQuoteRequest.QuoteClose[QUOTE_CLOSE_QUOTE_ID]).Id;
                state  = "Won";
                status = "Won";
            }
            else if (request is CloseQuoteRequest closeQuoteRequest)
            {
                id    = ((EntityReference)closeQuoteRequest.QuoteClose[QUOTE_CLOSE_QUOTE_ID]).Id;
                state = "Closed";

                EntityMetadata          metadata       = Dynamics365Entity.Create(QUOTE_ENTITY_NAME, Connection).GetEntityMetadata(Connection);
                StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME));
                status = statusMetadata.OptionSet.Options.First(option => option.Value == closeQuoteRequest.Status.Value).Label.UserLocalizedLabel.Label;
            }
            else if (request is WinOpportunityRequest winOpportunityRequest)
            {
                id    = ((EntityReference)winOpportunityRequest.OpportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID]).Id;
                state = "Won";

                EntityMetadata          metadata       = Dynamics365Entity.Create(OPPORTUNITY_ENTITY_NAME, Connection).GetEntityMetadata(Connection);
                StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME));
                status = statusMetadata.OptionSet.Options.First(option => option.Value == winOpportunityRequest.Status.Value).Label.UserLocalizedLabel.Label;
            }
            else if (request is LoseOpportunityRequest loseOpportunityRequest)
            {
                id    = ((EntityReference)loseOpportunityRequest.OpportunityClose[OPPORTUNITY_CLOSE_OPPORTUNITY_ID]).Id;
                state = "Lost";

                EntityMetadata          metadata       = Dynamics365Entity.Create(OPPORTUNITY_ENTITY_NAME, Connection).GetEntityMetadata(Connection);
                StatusAttributeMetadata statusMetadata = ((StatusAttributeMetadata)metadata.Attributes.First(field => field.LogicalName == STATUSCODE_NAME));
                status = statusMetadata.OptionSet.Options.First(option => option.Value == loseOpportunityRequest.Status.Value).Label.UserLocalizedLabel.Label;
            }

            return(string.Format(Properties.Resources.Dynamics365SetStateOperationRequestDescription, Entity.DisplayName, id, state, status));
        }
Esempio n. 30
0
        public static List <OptionItem> GetStateOptionItems(StatusAttributeMetadata statusAttr, StateAttributeMetadata stateAttr, List <StringMap> listStringMap)
        {
            var options = new List <OptionItem>();

            foreach (StateOptionMetadata optionValue in stateAttr.OptionSet.Options)
            {
                if (!optionValue.Value.HasValue)
                {
                    continue;
                }

                var defaultStatusCodeName = "Null";

                if (optionValue.DefaultStatus.HasValue)
                {
                    var statusOptionValue = statusAttr.OptionSet.Options.FirstOrDefault(op => op.Value.Value == optionValue.DefaultStatus.Value);

                    if (statusOptionValue != null)
                    {
                        string statusLabel = GetLocalizedLabel(statusOptionValue.Label);

                        defaultStatusCodeName = GetOptionSetValueName(statusLabel, statusOptionValue.Value.Value);
                    }
                    else
                    {
                        defaultStatusCodeName = string.Format("Not finded: {0}", optionValue.DefaultStatus.ToString());
                    }
                }

                var stateName = GetStateName(optionValue);

                if (!string.IsNullOrEmpty(stateName))
                {
                    int?displayOrder = null;

                    if (listStringMap != null)
                    {
                        var stringMap = listStringMap.FirstOrDefault(e =>
                                                                     string.Equals(e.AttributeName, stateAttr.LogicalName, StringComparison.InvariantCultureIgnoreCase) &&
                                                                     string.Equals(e.ObjectTypeCode, stateAttr.EntityLogicalName, StringComparison.InvariantCultureIgnoreCase) &&
                                                                     e.AttributeValue == optionValue.Value.Value
                                                                     );

                        if (stringMap != null)
                        {
                            displayOrder = stringMap.DisplayOrder;
                        }
                    }

                    var optionItem = new OptionItem()
                    {
                        FieldName = stateName,
                        Value     = optionValue.Value.Value,

                        Label       = optionValue.Label,
                        Description = optionValue.Description,

                        DefaultStatusCode     = optionValue.DefaultStatus,
                        DefaultStatusCodeName = defaultStatusCodeName,

                        InvariantName = optionValue.InvariantName,

                        DisplayOrder = displayOrder,

                        OptionMetadata = optionValue,
                    };

                    options.Add(optionItem);
                }
            }

            options = options.OrderBy(op => op.DisplayOrder).ToList();

            return(options);
        }
Esempio n. 31
0
        public static List <Dynamics365State> GetStates(Dynamics365Entity entity, Dynamics365Connection connection)
        {
            ConnectionCache         cache    = new ConnectionCache(connection);
            string                  cacheKey = string.Format("GetStates:{0}", entity.LogicalName);
            List <Dynamics365State> states   = (List <Dynamics365State>)cache[cacheKey];

            if (states == null)
            {
                states = new List <Dynamics365State>();
                RetrieveEntityRequest request = new RetrieveEntityRequest()
                {
                    LogicalName           = entity.LogicalName,
                    EntityFilters         = EntityFilters.Attributes,
                    RetrieveAsIfPublished = false
                };

                using (OrganizationServiceProxy proxy = connection.OrganizationServiceProxy)
                {
                    RetrieveEntityResponse response      = (RetrieveEntityResponse)proxy.Execute(request);
                    StateAttributeMetadata stateMetadata = (StateAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StateAttributeMetadata);

                    if (stateMetadata != null)
                    {
                        foreach (StateOptionMetadata stateOption in stateMetadata.OptionSet.Options)
                        {
                            Dynamics365State state = new Dynamics365State()
                            {
                                Code        = (int)stateOption.Value,
                                Name        = stateOption.Label.UserLocalizedLabel.Label,
                                LogicalName = stateMetadata.LogicalName
                            };
                            StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)response.EntityMetadata.Attributes.FirstOrDefault(findField => findField is StatusAttributeMetadata);

                            if (statusMetadata != null)
                            {
                                foreach (StatusOptionMetadata statusOption in statusMetadata.OptionSet.Options)
                                {
                                    if (statusOption.State == state.Code)
                                    {
                                        Dynamics365Status status = new Dynamics365Status()
                                        {
                                            Code        = (int)statusOption.Value,
                                            Name        = statusOption.Label.UserLocalizedLabel.Label,
                                            LogicalName = statusMetadata.LogicalName
                                        };
                                        state.Statuses.Add(status);
                                    }
                                }

                                //state.Statuses.Sort((status1, status2) => status1.Name.CompareTo(status2.Name));
                            }

                            states.Add(state);
                        }
                    }
                }

                //states.Sort((state1, state2) => state1.Name.CompareTo(state2.Name));
                cache[cacheKey] = states;
            }

            return(states);
        }
Esempio n. 32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="oAttribute"></param>
        /// <param name="attMetadata"></param>
        /// <returns></returns>
        static public string GetMetadataValue(object oAttribute, RetrieveAttributeResponse attMetadata)
        {
            string sReturn = string.Empty;

            if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.OptionSetValue)))
            {
                OptionMetadata[] optionList = null;

                if (attMetadata.AttributeMetadata.GetType().FullName.Contains("PicklistAttributeMetadata"))
                {
                    PicklistAttributeMetadata retrievedPicklistAttributeMetadata =
                        (PicklistAttributeMetadata)attMetadata.AttributeMetadata;
                    // Get the current options list for the retrieved attribute.
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else if (attMetadata.AttributeMetadata.GetType().FullName.Contains("StatusAttributeMetadata"))
                {
                    StatusAttributeMetadata retrievedPicklistAttributeMetadata =
                        (StatusAttributeMetadata)attMetadata.AttributeMetadata;
                    // Get the current options list for the retrieved attribute.
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else if (attMetadata.AttributeMetadata.GetType().FullName.Contains("StateAttributeMetadata"))
                {
                    StateAttributeMetadata retrievedPicklistAttributeMetadata =
                        (StateAttributeMetadata)attMetadata.AttributeMetadata;
                    // Get the current options list for the retrieved attribute.
                    optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
                }
                else
                {
                    return(string.Empty);
                }

                // get the text values
                int i = int.Parse((oAttribute as Microsoft.Xrm.Sdk.OptionSetValue).Value.ToString());
                for (int c = 0; c < optionList.Length; c++)
                {
                    OptionMetadata opmetadata = (OptionMetadata)optionList.GetValue(c);
                    if (opmetadata.Value == i)
                    {
                        sReturn = opmetadata.Label.UserLocalizedLabel.Label;
                        break;
                    }
                }
            }
            else if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.Money)))
            {
                sReturn = (oAttribute as Microsoft.Xrm.Sdk.Money).Value.ToString();
            }
            else if (oAttribute.GetType().Equals(typeof(Microsoft.Xrm.Sdk.EntityReference)))
            {
                sReturn = (oAttribute as Microsoft.Xrm.Sdk.EntityReference).Name;
            }
            else
            {
                sReturn = oAttribute.ToString();
            }
            if (sReturn == null || sReturn.Length == 0)
            {
                sReturn = "No Value";
            }
            return(sReturn);
        }
Esempio n. 33
0
        //<snippetStateModelTransitions.GetValidStatusOptions>
        /// <summary>
        /// Returns valid status option transitions regardless of whether state transitions are enabled for the entity
        /// </summary>
        /// <param name="entityLogicalName">The logical name of the entity</param>
        /// <param name="currentStatusValue">The current status of the entity instance</param>
        /// <returns>A list of StatusOptions that represent the valid transitions</returns>
        public List <StatusOption> GetValidStatusOptions(String entityLogicalName, int currentStatusValue)
        {
            List <StatusOption> validStatusOptions = new List <StatusOption>();

            //Check entity Metadata

            //Retrieve just one entity definition
            MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);

            entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
            //Return the attributes and the EnforceStateTransitions property
            MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes", "EnforceStateTransitions" });

            //Retrieve only State or Status attributes
            MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.Or);

            attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
            attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.State));

            //Retrieve only the OptionSet property of the attributes
            MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

            //Set the query
            EntityQueryExpression query = new EntityQueryExpression()
            {
                Criteria       = entityFilter,
                Properties     = entityProperties,
                AttributeQuery = new AttributeQueryExpression()
                {
                    Criteria = attributeFilter, Properties = attributeProperties
                }
            };

            //Retrieve the metadata
            RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
            {
                Query = query
            };
            RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);

            //Check the value of EnforceStateTransitions
            Boolean?EnforceStateTransitions = response.EntityMetadata[0].EnforceStateTransitions;

            //Capture the state and status attributes
            StatusAttributeMetadata statusAttribute = new StatusAttributeMetadata();
            StateAttributeMetadata  stateAttribute  = new StateAttributeMetadata();

            foreach (AttributeMetadata attributeMetadata in response.EntityMetadata[0].Attributes)
            {
                switch (attributeMetadata.AttributeType)
                {
                case AttributeTypeCode.Status:
                    statusAttribute = (StatusAttributeMetadata)attributeMetadata;
                    break;

                case AttributeTypeCode.State:
                    stateAttribute = (StateAttributeMetadata)attributeMetadata;
                    break;
                }
            }


            if (EnforceStateTransitions.HasValue && EnforceStateTransitions.Value == true)
            {
                //When EnforceStateTransitions is true use the TransitionData to filter the valid options
                foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
                {
                    if (option.Value == currentStatusValue)
                    {
                        if (option.TransitionData != String.Empty)
                        {
                            XDocument transitionData = XDocument.Parse(option.TransitionData);

                            IEnumerable <XElement> elements = (((XElement)transitionData.FirstNode)).Descendants();

                            foreach (XElement e in elements)
                            {
                                int    statusOptionValue = Convert.ToInt32(e.Attribute("tostatusid").Value);
                                String statusLabel       = GetOptionSetLabel(statusAttribute, statusOptionValue);

                                string stateLabel = String.Empty;
                                int?   stateValue = null;
                                foreach (StatusOptionMetadata statusOption in statusAttribute.OptionSet.Options)
                                {
                                    if (statusOption.Value.Value == statusOptionValue)
                                    {
                                        stateValue = statusOption.State.Value;
                                        stateLabel = GetOptionSetLabel(stateAttribute, stateValue.Value);
                                    }
                                }


                                validStatusOptions.Add(new StatusOption()
                                {
                                    StateLabel  = stateLabel,
                                    StateValue  = stateValue.Value,
                                    StatusLabel = statusLabel,
                                    StatusValue = option.Value.Value
                                });
                            }
                        }
                    }
                }
            }
            else
            {
                ////When EnforceStateTransitions is false do not filter the available options

                foreach (StatusOptionMetadata option in statusAttribute.OptionSet.Options)
                {
                    if (option.Value != currentStatusValue)
                    {
                        String statusLabel = "";
                        try
                        {
                            statusLabel = option.Label.UserLocalizedLabel.Label;
                        }
                        catch (Exception)
                        {
                            statusLabel = option.Label.LocalizedLabels[0].Label;
                        };

                        String stateLabel = GetOptionSetLabel(stateAttribute, option.State.Value);

                        validStatusOptions.Add(new StatusOption()
                        {
                            StateLabel  = stateLabel,
                            StateValue  = option.State.Value,
                            StatusLabel = statusLabel,
                            StatusValue = option.Value.Value
                        });
                    }
                }
            }
            return(validStatusOptions);
        }
Esempio n. 34
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Retrieve status options for the Incident entity
        /// Use GetValidStatusOptions to get valid status transitions for each status option
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();
                    //<snippetStateModelTransitions.run>
                    String entityLogicalName = "incident";
                    // Retrieve status options for the Incident entity

                    //Retrieve just the incident entity and its attributes
                    MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.And);
                    entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName));
                    MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression(new string[] { "Attributes" });

                    //Retrieve just the status attribute and the OptionSet property
                    MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
                    attributeFilter.Conditions.Add(new MetadataConditionExpression("AttributeType", MetadataConditionOperator.Equals, AttributeTypeCode.Status));
                    MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression(new string[] { "OptionSet" });

                    //Instantiate the entity query
                    EntityQueryExpression query = new EntityQueryExpression()
                    {
                        Criteria       = entityFilter,
                        Properties     = entityProperties,
                        AttributeQuery = new AttributeQueryExpression()
                        {
                            Criteria = attributeFilter, Properties = attributeProperties
                        }
                    };

                    //Retrieve the metadata
                    RetrieveMetadataChangesRequest request = new RetrieveMetadataChangesRequest()
                    {
                        Query = query
                    };
                    RetrieveMetadataChangesResponse response = (RetrieveMetadataChangesResponse)_serviceProxy.Execute(request);


                    StatusAttributeMetadata  statusAttribute = (StatusAttributeMetadata)response.EntityMetadata[0].Attributes[0];
                    OptionMetadataCollection statusOptions   = statusAttribute.OptionSet.Options;
                    //Loop through each of the status options
                    foreach (StatusOptionMetadata option in statusOptions)
                    {
                        String StatusOptionLabel = GetOptionSetLabel(statusAttribute, option.Value.Value);
                        Console.WriteLine("[{0}] {1} records can transition to:", StatusOptionLabel, entityLogicalName);
                        List <StatusOption> validStatusOptions = GetValidStatusOptions(entityLogicalName, option.Value.Value);
                        //Loop through each valid transition for the option
                        foreach (StatusOption opt in validStatusOptions)
                        {
                            Console.WriteLine("{0,-3}{1,-10}{2,-5}{3,-10}", opt.StateValue, opt.StateLabel, opt.StatusValue, opt.StatusLabel);
                        }
                        Console.WriteLine("");
                    }
                    //</snippetStateModelTransitions.run>
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Esempio n. 35
0
        public void ConvertValueTests()
        {
            FieldMap        map               = new FieldMap("source", "dest");
            string          optionSetLabel    = "label";
            int             optionSetInt      = 1;
            string          booleanTrueLabel  = "Yes";
            string          booleanFalseLabel = "No";
            EntityReference entityRef         = new EntityReference("entity", Guid.NewGuid());

            // Set up metadata
            PicklistAttributeMetadata optionSetMetadata = new PicklistAttributeMetadata()
            {
                OptionSet = new OptionSetMetadata(
                    new OptionMetadataCollection(
                        new List <OptionMetadata>()
                {
                    new OptionMetadata {
                        Value = optionSetInt,
                        Label = GenerateLabel(optionSetLabel)
                    }
                }
                        )
                    )
            };
            StatusAttributeMetadata statusMetadata = new StatusAttributeMetadata()
            {
                OptionSet = new OptionSetMetadata(
                    new OptionMetadataCollection(
                        new List <OptionMetadata>()
                {
                    new OptionMetadata {
                        Value = optionSetInt,
                        Label = GenerateLabel(optionSetLabel)
                    }
                }
                        )
                    )
            };
            BooleanAttributeMetadata booleanMetadata = new BooleanAttributeMetadata(
                new BooleanOptionSetMetadata(
                    new OptionMetadata(GenerateLabel(booleanTrueLabel), 0),
                    new OptionMetadata(GenerateLabel(booleanFalseLabel), 1)
                    )
                );
            OptionSetValue optionSetValue = new OptionSetValue(optionSetInt);

            Assert.AreEqual(null, ImportMap.ConvertValue(null, map, new AttributeMetadata(), service));
            Assert.AreEqual(1, ImportMap.ConvertValue(1, map, new IntegerAttributeMetadata(), service));
            Assert.AreEqual(1, ImportMap.ConvertValue(1D, map, new IntegerAttributeMetadata(), service));

            Assert.AreEqual("string", ImportMap.ConvertValue("string", map, new StringAttributeMetadata(), service));
            Assert.AreEqual("1", ImportMap.ConvertValue(1, map, new StringAttributeMetadata(), service));

            Assert.AreEqual(1.0m, ImportMap.ConvertValue(1.0m, map, new DecimalAttributeMetadata(), service));
            Assert.AreEqual(1.0m, ImportMap.ConvertValue(1.0f, map, new DecimalAttributeMetadata(), service));
            Assert.AreEqual(1.0m, ImportMap.ConvertValue(1D, map, new DecimalAttributeMetadata(), service));
            Assert.AreEqual(1.0m, ImportMap.ConvertValue(1, map, new DecimalAttributeMetadata(), service));

            Assert.AreEqual(1.0, ImportMap.ConvertValue(1.0, map, new DoubleAttributeMetadata(), service));
            Assert.AreEqual(1.0, ImportMap.ConvertValue(1.0f, map, new DoubleAttributeMetadata(), service));

            Assert.AreEqual(optionSetInt, ((OptionSetValue)ImportMap.ConvertValue(optionSetLabel, map, optionSetMetadata, service)).Value);
            Assert.AreEqual(optionSetValue, ImportMap.ConvertValue(optionSetValue, map, new PicklistAttributeMetadata(), service));

            Assert.AreEqual(null, ImportMap.ConvertValue("UNKNOWNThing", map, optionSetMetadata, service));
            Assert.AreEqual(true, ImportMap.ConvertValue("Yes", map, booleanMetadata, service));
            Assert.AreEqual(true, ImportMap.ConvertValue(true, map, booleanMetadata, service));

            Assert.AreEqual(entityRef, ImportMap.ConvertValue(entityRef, map, new LookupAttributeMetadata(), service));
            Assert.AreEqual(optionSetInt, ((OptionSetValue)ImportMap.ConvertValue(optionSetLabel, map, statusMetadata, service)).Value);
            Assert.AreEqual(null, ImportMap.ConvertValue("UNKNOWNThing", map, statusMetadata, service));
        }