public void FormattedValueCollectionInObjectCanBeSerializedAndDeserialized()
        {
            FormattedValueCollectionContainer formattedValueCollectionContainer = new FormattedValueCollectionContainer();
            FormattedValueCollection          formattedValueCollection          = new FormattedValueCollection();

            formattedValueCollectionContainer.FormattedValueCollection = formattedValueCollection;
            formattedValueCollection.Add("Test", "test");
            JsonSerializer serializer   = new EntitySerializer();
            MemoryStream   memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), formattedValueCollectionContainer);
            }

            FormattedValueCollectionContainer deserializedFormattedValueCollectionContainer;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedFormattedValueCollectionContainer = (FormattedValueCollectionContainer)serializer.Deserialize(new JsonTextReader(reader));
            }
            FormattedValueCollection deserializedFormattedValueCollection = (FormattedValueCollection)deserializedFormattedValueCollectionContainer.FormattedValueCollection;


            Assert.Equal(formattedValueCollectionContainer.GetType(), deserializedFormattedValueCollectionContainer.GetType());
            Assert.Equal(formattedValueCollection.Count, deserializedFormattedValueCollection.Count);
            Assert.Equal(formattedValueCollection.Keys.First(), deserializedFormattedValueCollection.Keys.First());
            Assert.Equal(formattedValueCollection.Values.First(), deserializedFormattedValueCollection.Values.First());
        }
        public void FormattedValueCollectionCanBeSerializedAndDeserializedWithoutSpecifyingType()
        {
            FormattedValueCollection formattedValueCollection = new FormattedValueCollection();

            formattedValueCollection.Add("Test", "test");

            JsonSerializer serializer = new JsonSerializer();

            serializer.TypeNameHandling = TypeNameHandling.Objects;
            serializer.ContractResolver = new XrmContractResolver();
            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), formattedValueCollection);
            }

            FormattedValueCollection deserializedFormattedValueCollection;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedFormattedValueCollection = (FormattedValueCollection)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(formattedValueCollection.GetType(), deserializedFormattedValueCollection.GetType());
            Assert.Equal(formattedValueCollection.Count, deserializedFormattedValueCollection.Count);
            Assert.Equal(formattedValueCollection.Keys.First(), deserializedFormattedValueCollection.Keys.First());
            Assert.Equal(formattedValueCollection.Values.First(), deserializedFormattedValueCollection.Values.First());
        }
        public void When_an_entity_is_returned_formatted_values_are_also_cloned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            account["statecode"] = new OptionSetValue(0);

            var formattedValues = new FormattedValueCollection();

            formattedValues.Add("statecode", "Active");
            account.Inject("FormattedValues", formattedValues);

            context.Initialize(new List <Entity>()
            {
                account
            });

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery <Account>()
                         select acc).FirstOrDefault();

                Assert.True(a.FormattedValues != null);
                Assert.True(a.FormattedValues.Contains("statecode"));
                Assert.Equal("Active", a.FormattedValues["statecode"]);
            }
        }
Exemplo n.º 4
0
        public static Entity Clone(this Entity e, Type t)
        {
            if (t == null)
            {
                return(e.Clone());
            }

            var cloned = Activator.CreateInstance(t) as Entity;

            cloned.Id          = e.Id;
            cloned.LogicalName = e.LogicalName;

            if (e.FormattedValues != null)
            {
                var formattedValues = new FormattedValueCollection();
                foreach (var key in e.FormattedValues.Keys)
                {
                    formattedValues.Add(key, e.FormattedValues[key]);
                }

                cloned.Inject("FormattedValues", formattedValues);
            }

            foreach (var attKey in e.Attributes.Keys)
            {
                if (e[attKey] != null)
                {
                    cloned[attKey] = CloneAttribute(e[attKey]);
                }
            }
            return(cloned);
        }
 private static void CopyFormattedValues(FormattedValueCollection fromCollection, FormattedValueCollection toCollection)
 {
     foreach (var pair in fromCollection)
     {
         toCollection[pair.Key] = pair.Value;
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializableFormattedValueCollection"/> class.
 /// </summary>
 /// <param name="values">The values.</param>
 public SerializableFormattedValueCollection(FormattedValueCollection values)
 {
     foreach (var value in values)
     {
         Add(new KeyValuePairOfstringstring(value));
     }
 }
Exemplo n.º 7
0
        public void When_an_entity_is_returned_with_specific_columns_formatted_values_are_also_cloned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account()
            {
                Id = Guid.NewGuid()
            };

            account["statecode"] = AccountState.Active;

            var formattedValues = new FormattedValueCollection();

            formattedValues.Add("statecode", "Active");

            account.Inject("FormattedValues", formattedValues);

            context.Initialize(new List <Entity>()
            {
                account
            });

            var a = service.Retrieve("account", account.Id, new ColumnSet("statecode"));

            Assert.True(a.FormattedValues != null);
            Assert.True(a.FormattedValues.Contains("statecode"));
            Assert.Equal("Active", a.FormattedValues["statecode"]);
        }
Exemplo n.º 8
0
        public static Entity Clone(this Entity e, XrmFakedContext context = null)
        {
            var cloned = new Entity(e.LogicalName);

            cloned.Id          = e.Id;
            cloned.LogicalName = e.LogicalName;

            if (e.FormattedValues != null)
            {
                var formattedValues = new FormattedValueCollection();
                foreach (var key in e.FormattedValues.Keys)
                {
                    formattedValues.Add(key, e.FormattedValues[key]);
                }

                cloned.Inject("FormattedValues", formattedValues);
            }

            foreach (var attKey in e.Attributes.Keys)
            {
                cloned[attKey] = e[attKey] != null?CloneAttribute(e[attKey], context) : null;
            }
#if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013 && !FAKE_XRM_EASY_2015
            foreach (var attKey in e.KeyAttributes.Keys)
            {
                cloned.KeyAttributes[attKey] = e.KeyAttributes[attKey] != null?CloneAttribute(e.KeyAttributes[attKey]) : null;
            }
#endif
            return(cloned);
        }
        private static string GetValueStringShortEntityReference(FormattedValueCollection formattedValues, string key, object value, ConnectionData connectionData)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            if (value is EntityReference entityReference)
            {
                if (!string.IsNullOrEmpty(entityReference.Name))
                {
                    return(entityReference.Name);
                }
                else
                {
                    return(string.Format("{0} - {1}", entityReference.LogicalName, entityReference.Id.ToString()));
                }
            }

            if (value is BooleanManagedProperty booleanManagedboolean)
            {
                return(string.Format("{0,-5}    CanBeChanged = {1,-5}", booleanManagedboolean.Value, booleanManagedboolean.CanBeChanged));
            }

            if (value is OptionSetValue optionSetValue)
            {
                return(optionSetValue.Value.ToString() + (formattedValues.ContainsKey(key) ? string.Format(" - {0}", formattedValues[key]) : string.Empty));
            }

            if (value is OptionSetValueCollection valueOptionSetValueCollection)
            {
                string valuesString = valueOptionSetValueCollection.Any() ? string.Join(",", valueOptionSetValueCollection.Select(o => o.Value).OrderBy(o => o)) : "none";

                return(valuesString + (formattedValues.ContainsKey(key) ? string.Format(" - {0}", formattedValues[key]) : string.Empty));
            }

            if (value is Money money)
            {
                return(money.Value.ToString());
            }

            if (value is DateTime dateTime)
            {
                return(dateTime.ToLocalTime().ToString("G", System.Globalization.CultureInfo.CurrentCulture));
            }

            if (value is AliasedValue aliasedValue)
            {
                return(GetValueStringShortEntityReference(formattedValues, key, aliasedValue.Value, connectionData));
            }

            if (value is EntityCollection entityCollection)
            {
                return(string.Format("EnitityCollection {0}: {1}", entityCollection.EntityName, (entityCollection.Entities?.Count).GetValueOrDefault()));
            }

            return(value.ToString());
        }
        public void SetValue(object target, object value)
        {
            FormattedValueCollection formattedValueCollection   = (FormattedValueCollection)target;
            IEnumerable <KeyValuePair <string, string> > values = (IEnumerable <KeyValuePair <string, string> >)value;

            foreach (var item in values)
            {
                formattedValueCollection.Add(item);
            }
        }
Exemplo n.º 11
0
        public void Test_Conversion_OptionSetValue_ToXml()
        {
            var fake = new XrmFakedContext();

            fake.ProxyTypesAssembly = typeof(Crm.Contact).Assembly;
            var executor        = new ExecuteFetchRequestExecutor();
            var formattedValues = new FormattedValueCollection();

            formattedValues.Add("new_contact", "Test");
            var element = executor.AttributeValueToFetchResult(new KeyValuePair <string, object>("new_contact", new OptionSetValue(1)), formattedValues, fake);

            Assert.NotNull(element);
            Assert.Equal(@"<new_contact name=""Test"" formattedvalue=""1"">1</new_contact>", element.ToString());
        }
Exemplo n.º 12
0
        public void When_an_entity_is_returned_with_link_entity_and_specific_columns_formatted_values_are_also_cloned2()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var contact = new Contact()
            {
                Id = Guid.NewGuid()
            };

            contact["statecode"] = ContactState.Inactive;
            var contactFormattedValues = new FormattedValueCollection();

            contactFormattedValues.Add("statecode", "Inactive");

            contact.Inject("FormattedValues", contactFormattedValues);

            var account = new Account()
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = contact.ToEntityReference()
            };

            account["statecode"] = AccountState.Active;

            var accountFormattedValues = new FormattedValueCollection();

            accountFormattedValues.Add("statecode", "Active");

            account.Inject("FormattedValues", accountFormattedValues);

            context.Initialize(new List <Entity>()
            {
                account,
                contact
            });

            var query = new QueryExpression("account");

            query.Criteria.AddCondition("accountid", ConditionOperator.Equal, account.Id);
            var linkedContact = query.AddLink("contact", "primarycontactid", "contactid");

            linkedContact.Columns.AddColumns("statecode");

            var a = service.RetrieveMultiple(query).Entities.FirstOrDefault();

            Assert.True(a.FormattedValues != null);
            Assert.True(a.FormattedValues.Contains("contact1.statecode"));
            Assert.Equal("Inactive", a.FormattedValues["contact1.statecode"]);
        }
Exemplo n.º 13
0
        public void Test_Conversion_OptionSetValueCollection_ToXml()
        {
            var fake = new XrmFakedContext();

            fake.ProxyTypesAssembly = typeof(Crm.Contact).Assembly;
            var executor        = new ExecuteFetchRequestExecutor();
            var formattedValues = new FormattedValueCollection();
            var element         = executor.AttributeValueToFetchResult(
                new KeyValuePair <string, object>("new_multiselectattribute", new OptionSetValueCollection()
            {
                new OptionSetValue(1), new OptionSetValue(2)
            }),
                formattedValues,
                fake);

            Assert.NotNull(element);
            Assert.Equal(@"<new_multiselectattribute name=""[-1,1,2,-1]"">[-1,1,2,-1]</new_multiselectattribute>", element.ToString());
        }
Exemplo n.º 14
0
        public static Entity Clone(this Entity e)
        {
            var cloned = new Entity(e.LogicalName);

            cloned.Id          = e.Id;
            cloned.LogicalName = e.LogicalName;

            if (e.FormattedValues != null)
            {
                var formattedValues = new FormattedValueCollection();
                foreach (var key in e.FormattedValues.Keys)
                {
                    formattedValues.Add(key, e.FormattedValues[key]);
                }

                cloned.Inject("FormattedValues", formattedValues);
            }

            foreach (var attKey in e.Attributes.Keys)
            {
                cloned[attKey] = e[attKey] != null?CloneAttribute(e[attKey]) : null;
            }
            return(cloned);
        }
        public XElement AttributeValueToFetchResult(KeyValuePair <string, object> entAtt, FormattedValueCollection formattedValues, XrmFakedContext ctx)
        {
            XElement attributeValueElement;

            if (entAtt.Value == null)
            {
                return(null);
            }
            if (entAtt.Value is DateTime?)
            {
                attributeValueElement = XElement.Parse(String.Format("<{0} date=\"{1:yyyy-MM-dd}\" time=\"{1:hh:mm tt}\">{1:yyyy-MM-ddTHH:mm:sszz:00}</{0}>", entAtt.Key, entAtt.Value));
            }
            else if (entAtt.Value is EntityReference)
            {
                var entRef = (EntityReference)entAtt.Value;
                if (!_typeCodes.ContainsKey(entRef.LogicalName))
                {
                    var entType  = RetrieveEntityRequestExecutor.GetEntityProxyType(entRef.LogicalName, ctx);
                    var typeCode = entType.GetField("EntityTypeCode").GetValue(null);

                    _typeCodes.Add(entRef.LogicalName, (int?)typeCode);
                }

                attributeValueElement = XElement.Parse(String.Format("<{0} dsc=\"0\" yomi=\"{1}\" name=\"{1}\" type=\"{3}\">{2:D}</{0}>", entAtt.Key, entRef.Name, entRef.Id.ToString().ToUpper(), _typeCodes[entRef.LogicalName]));
            }
            else if (entAtt.Value is bool?)
            {
                var boolValue = (bool?)entAtt.Value;

                var formattedValue = boolValue.ToString();
                if (formattedValues.ContainsKey(entAtt.Key))
                {
                    formattedValue = formattedValues[entAtt.Key];
                }
                attributeValueElement = XElement.Parse(String.Format("<{0} name=\"{1}\">{2}</{0}>", entAtt.Key, formattedValue, Convert.ToInt16(boolValue)));
            }
            else if (entAtt.Value is OptionSetValue)
            {
                var osValue = (OptionSetValue)entAtt.Value;

                var formattedValue = osValue.Value.ToString();
                if (formattedValues.ContainsKey(entAtt.Key))
                {
                    formattedValue = formattedValues[entAtt.Key];
                }
                attributeValueElement = XElement.Parse(String.Format("<{0} name=\"{1}\" formattedvalue=\"{2}\">{2}</{0}>", entAtt.Key, formattedValue, osValue.Value));
            }
            else if (entAtt.Value is Enum)
            {
                var osValue = (Enum)entAtt.Value;

                var formattedValue = osValue.ToString();
                if (formattedValues.ContainsKey(entAtt.Key))
                {
                    formattedValue = formattedValues[entAtt.Key];
                }
                attributeValueElement = XElement.Parse(String.Format("<{0} name=\"{1}\" formattedvalue=\"{2}\">{2}</{0}>", entAtt.Key, formattedValue, osValue));
            }
            else if (entAtt.Value is Money)
            {
                var moneyValue = (Money)entAtt.Value;

                var formattedValue = moneyValue.Value.ToString();
                if (formattedValues.ContainsKey(entAtt.Key))
                {
                    formattedValue = formattedValues[entAtt.Key];
                }
                attributeValueElement = XElement.Parse(String.Format("<{0} formattedvalue=\"{1}\">{2:0.##}</{0}>", entAtt.Key, formattedValue, moneyValue.Value));
            }
            else if (entAtt.Value is decimal?)
            {
                var decimalVal = (decimal?)entAtt.Value;

                attributeValueElement = XElement.Parse(String.Format("<{0}>{1:0.####}</{0}>", entAtt.Key, decimalVal.Value));
            }
            else if (entAtt.Value is AliasedValue)
            {
                var alliasedVal = entAtt.Value as AliasedValue;
                attributeValueElement = AttributeValueToFetchResult(new KeyValuePair <string, object>(entAtt.Key, alliasedVal.Value), formattedValues, ctx);
            }
            else if (entAtt.Value is Guid)
            {
                attributeValueElement = XElement.Parse(String.Format("<{0}>{1}</{0}>", entAtt.Key, entAtt.Value.ToString().ToUpper()));;
            }
            else
            {
                attributeValueElement = XElement.Parse(String.Format("<{0}>{1}</{0}>", entAtt.Key, entAtt.Value));
            }
            return(attributeValueElement);
        }
        public object GetValue(object target)
        {
            FormattedValueCollection value = (FormattedValueCollection)target;

            return(value);
        }
Exemplo n.º 17
0
 private static IEnumerable <XElement> GetContentValues(FormattedValueCollection attributes)
 {
     return(attributes.OrderBy(a => a.Key).Select(a => new XElement("label", new XAttribute("name", a.Key), new XText(a.Value.ToString()))));
 }
        private static string GetValueStringFull(FormattedValueCollection formattedValues, string key, object value, ConnectionData connectionData)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            if (value is EntityReference entityReference)
            {
                StringBuilder result = new StringBuilder();

                if (!string.IsNullOrEmpty(entityReference.Name))
                {
                    result.AppendFormat("{0} - ", entityReference.Name);
                }

                result.AppendFormat("{0} - {1}", entityReference.LogicalName, entityReference.Id.ToString());

                if (connectionData != null)
                {
                    var url = connectionData.GetEntityInstanceUrl(entityReference.LogicalName, entityReference.Id);

                    if (!string.IsNullOrEmpty(url))
                    {
                        result.AppendFormat(" - {0}", url);
                    }
                }

                return(result.ToString());
            }

            if (value is BooleanManagedProperty booleanManaged)
            {
                return(string.Format("{0,-5}        CanBeChanged = {1,-5}", booleanManaged.Value, booleanManaged.CanBeChanged));
            }

            if (value is OptionSetValue optionSetValue)
            {
                return(optionSetValue.Value.ToString() + (formattedValues.ContainsKey(key) ? string.Format(" - {0}", formattedValues[key]) : string.Empty));
            }

            if (value is OptionSetValueCollection valueOptionSetValueCollection)
            {
                string valuesString = valueOptionSetValueCollection.Any() ? string.Join(",", valueOptionSetValueCollection.Select(o => o.Value).OrderBy(o => o)) : "none";

                return(valuesString + (formattedValues.ContainsKey(key) ? string.Format(" - {0}", formattedValues[key]) : string.Empty));
            }

            if (value is Money money)
            {
                return(money.Value.ToString());
            }

            if (value is DateTime dateTime)
            {
                return(dateTime.ToLocalTime().ToString("G", System.Globalization.CultureInfo.CurrentCulture));
            }

            if (value is AliasedValue aliasedValue)
            {
                return(GetValueStringFull(formattedValues, key, aliasedValue.Value, connectionData));
            }

            if (value is EntityCollection entityCollection)
            {
                StringBuilder result = new StringBuilder();

                result.AppendFormat("EnitityCollection {0}: {1}", entityCollection.EntityName, (entityCollection.Entities?.Count).GetValueOrDefault()).AppendLine();

                foreach (var item in entityCollection.Entities)
                {
                    string entityDesc = GetEntityDescription(item, connectionData);

                    if (!string.IsNullOrEmpty(entityDesc))
                    {
                        var split = entityDesc.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (var str in split)
                        {
                            result.AppendLine(_defaultTabSpacer + _defaultTabSpacer + str);
                        }
                    }
                }

                return(result.ToString());
            }

            return(value.ToString());
        }