Ejemplo n.º 1
0
        public static Microsoft.Xrm.Sdk.OptionSetValueCollection GetMultiEnum <T>(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName, System.Collections.Generic.IEnumerable <T> values)

        {
            Microsoft.Xrm.Sdk.OptionSetValueCollection collection = new Microsoft.Xrm.Sdk.OptionSetValueCollection();
            collection.AddRange(System.Linq.Enumerable.Select(values, v => new Microsoft.Xrm.Sdk.OptionSetValue((int)(object)v)));
            return(collection);
        }
Ejemplo n.º 2
0
 internal void UpdateFrom(Microsoft.Xrm.Sdk.Entity entity)
 {
     foreach (var key in entity.Attributes.Keys)
     {
         this[key] = entity[key];
     }
 }
        public void Update(Microsoft.Xrm.Sdk.Entity target)
        {
            try
            {
                var key = target.LogicalName + target.Id.ToString();
                if (!entities.ContainsKey(key))
                {
                    throw new Exceptions.EntityNotFoundException(target.LogicalName, target.Id);
                }

                this.ExecuteStep(target, 10, "Update", false, null, OnValidation);
                this.ExecuteStep(target, 20, "Update", false, () =>
                {
                    ((Repository.IEntityShadow) this).Update(target);
                    ((Repository.IEntityShadow) this).Commit();
                }, OnPre);
                this.ExecuteStep(target, 40, "Update", false, () =>
                {
                    ((Repository.IEntityShadow) this).Commit();
                }, OnPost);
                this.ExecuteStep(target, 40, "Update", true, () =>
                {
                    ((Repository.IEntityShadow) this).Commit();
                }, OnPostAsync);
            }
            catch (Exception)
            {
                ((IEntityShadow)this).Rollback();
                throw;
            }
        }
Ejemplo n.º 4
0
        public void RetrieveAccountsByIdTest()
        {
            var connection = new CrmConnection("Crm");
            var service    = new OrganizationService(connection);
            var context    = new OrganizationServiceContext(service);

            using (ShimsContext.Create())
            {
                var       fakeContext = new Microsoft.Xrm.Sdk.Client.Fakes.ShimOrganizationServiceContext(context);
                LINQToCRM target      = new LINQToCRM(context);

                fakeContext.CreateQueryString = (entityName) =>
                {
                    return(new System.Linq.EnumerableQuery <Microsoft.Xrm.Sdk.Entity>(new Microsoft.Xrm.Sdk.Entity[] { }));
                };

                Guid id = Guid.NewGuid();

                Microsoft.Xrm.Sdk.Entity expected = new Microsoft.Xrm.Sdk.Entity();

                System.Linq.Fakes.ShimQueryable.FirstOrDefaultOf1IQueryableOfM0 <Microsoft.Xrm.Sdk.Entity>((a) =>
                {
                    expected.Id = id;
                    return(expected);
                });

                Microsoft.Xrm.Sdk.Entity actual;

                actual = target.RetrieveAccountsById(id);

                Assert.AreEqual(expected, actual);
            }
        }
Ejemplo n.º 5
0
        public void UnknownEntityTypeExceptionTest()
        {
            var entity = new Microsoft.Xrm.Sdk.Entity("notdefinedentityname", Guid.NewGuid());

            entity["name"] = "The name of the company";

            Assert.ThrowsException <Kipon.Xrm.Exceptions.UnknownEntityTypeException>(() => entity.ToEarlyBoundEntity());
        }
Ejemplo n.º 6
0
        public static System.Collections.Generic.IEnumerable <T> GetMultiEnum <T>(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName)

        {
            Microsoft.Xrm.Sdk.OptionSetValueCollection value = entity.GetAttributeValue <Microsoft.Xrm.Sdk.OptionSetValueCollection>(attributeLogicalName);
            System.Collections.Generic.List <T>        list  = new System.Collections.Generic.List <T>();
            list.AddRange(System.Linq.Enumerable.Select(value, v => (T)(object)v.Value));
            return(list);
        }
 public static object GetSafeValue(this Microsoft.Xrm.Sdk.Entity entity, string attribLogicalName)
 {
     if (!entity.Attributes.ContainsKey(attribLogicalName))
     {
         return(null);
     }
     return(entity[attribLogicalName]);
 }
Ejemplo n.º 8
0
 internal EntityShadow(Microsoft.Xrm.Sdk.Entity from)
 {
     this.Id          = from.Id;
     this.LogicalName = from.LogicalName;
     foreach (var key in from.Attributes.Keys)
     {
         this[key] = from[key];
     }
 }
        public void OptionSetToEnumTest()
        {
            var entity = new Microsoft.Xrm.Sdk.Entity();

            entity["enumvalue"] = new Microsoft.Xrm.Sdk.OptionSetValue(1);
            Assert.AreEqual(TestEnum.V1, entity.Attributes.ValueOf <TestEnum?>("enumvalue"));

            TestEnum?value = entity.Attributes.ValueOf <TestEnum?>("notinthere");

            Assert.IsNull(value);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="target">The tarket entity</param>
        /// <param name="stage">10=validate,20=pre,40=post</param>
        /// <param name="message">Create,Update,Delete,??</param>
        /// <param name="isAsync">false or true, only apply to stage 40</param>
        /// <param name="finalize">Will be executed end of step, regardless of any plugin execution</param>
        /// <param name="onDone">the valide method provided by the test library</param>
        private void ExecuteStep(Microsoft.Xrm.Sdk.Entity target, int stage, string message, bool isAsync, Action finalize, Action onDone)
        {
            if (message != "Create" && stage == 10)
            {
                var key = target.LogicalName + target.Id.ToString();
                this.preImage = this.entities[key].Clone();
            }

            var methods = this.pluginMethodCache.ForPlugin(this.plugin.GetType(), stage, message, target.LogicalName, isAsync, false);

            if (methods.Length > 0)
            {
                var pluginExecutionContext = new Services.PluginExecutionContext(stage, 1, message, target.LogicalName, target.Id, isAsync);
                pluginExecutionContext.InputParameters.Add("Target", target);

                if (message != "Create")
                {
                    var imagePre = this.ResolveImage(target.LogicalName, target.Id, 1, methods, preImage);
                    if (imagePre != null)
                    {
                        var imgName = Kipon.Fake.Xrm.Reflection.PluginMethod.ImageSuffixFor(1, stage, isAsync);
                        pluginExecutionContext.PreEntityImages.Add(imgName, imagePre);
                    }
                }

                if (stage == 40 && message != "Delete")
                {
                    var imagePost = this.ResolveImage(target.LogicalName, target.Id, 2, methods, null);
                    if (imagePost != null)
                    {
                        var imgName = Kipon.Fake.Xrm.Reflection.PluginMethod.ImageSuffixFor(2, stage, isAsync);
                        pluginExecutionContext.PostEntityImages.Add(imgName, imagePost);
                    }
                }

                var serviceProvider = new Services.ServiceProvider(pluginExecutionContext, this, this.plugin.GetType().Assembly);
                this.plugin.Execute(serviceProvider);

                finalize?.Invoke();

                onDone?.Invoke();
            }
            else
            {
                if (onDone != null)
                {
                    throw new Exceptions.UnexpectedEventListenerException(plugin.GetType(), message, stage);
                }
                else
                {
                    finalize?.Invoke();
                }
            }
        }
Ejemplo n.º 11
0
        internal Microsoft.Xrm.Sdk.Entity ToEntity()
        {
            var result = new Microsoft.Xrm.Sdk.Entity {
                Id = this.Id, LogicalName = this.LogicalName
            };

            foreach (var f in this.values.Keys)
            {
                result[f] = EntityShadow.ValueCloning(this[f]);
            }
            return(result);
        }
Ejemplo n.º 12
0
 public static System.Nullable <int> GetEnum(Microsoft.Xrm.Sdk.Entity entity, string attributeLogicalName)
 {
     if (entity.Attributes.ContainsKey(attributeLogicalName))
     {
         Microsoft.Xrm.Sdk.OptionSetValue value = entity.GetAttributeValue <Microsoft.Xrm.Sdk.OptionSetValue>(attributeLogicalName);
         if (value != null)
         {
             return(value.Value);
         }
     }
     return(null);
 }
Ejemplo n.º 13
0
        public void ToEarlyBoundEntityTest()
        {
            var entity = new Microsoft.Xrm.Sdk.Entity(Entities.Account.EntityLogicalName, Guid.NewGuid());

            entity["name"] = "The name of the company";

            var acc = entity.ToEarlyBoundEntity();

            Assert.AreEqual(typeof(Entities.Account), acc.GetType());

            var ra = acc as Kipon.Solid.Plugin.Entities.Account;

            Assert.AreEqual(ra.Name, entity["name"]);
        }
Ejemplo n.º 14
0
        private ThumbnailCard ToThumbNailCard(Microsoft.Xrm.Sdk.Entity kbArticle)
        {
            var publicNumber = kbArticle.GetAttributeValue <string>("articlepublicnumber");

            HtmlToMarkdownConverter converter = new HtmlToMarkdownConverter();
            var content = converter.Convert(kbArticle.GetAttributeValue <string>("content"));

            return(new ThumbnailCard()
            {
                Title = kbArticle.GetAttributeValue <string>("title"),
                Buttons = new[] { new CardAction(ActionTypes.OpenUrl, "View Article", value: $"https://portalurl.microsoftcrmportals.com/knowledgebase/article/{publicNumber}/en-us") },
                Text = content
            });
        }
        void IEntityShadow.Create(Microsoft.Xrm.Sdk.Entity entity)
        {
            var key = entity.LogicalName + entity.Id.ToString();

            if (this.entities.ContainsKey(key))
            {
                throw new Exceptions.EntityExistsException(entity);
            }
            transaction.Add(new TransactionElement {
                Operation = "Create", Entity = new EntityShadow(entity.LogicalName, entity.Id)
            });
            var et = new EntityShadow(entity);

            entities.Add(et.Key, et);
        }
        void IEntityShadow.Update(Microsoft.Xrm.Sdk.Entity entity)
        {
            var key = entity.LogicalName + entity.Id.ToString();

            if (!entities.ContainsKey(key))
            {
                throw new Exceptions.EntityNotFoundException(entity.LogicalName, entity.Id);
            }

            var before = new EntityShadow(entities[key]);

            transaction.Add(new TransactionElement {
                Operation = "Update", Entity = before
            });
            entities[key].UpdateFrom(entity);
        }
Ejemplo n.º 17
0
        public void RetrieveAccountsByNameTest()
        {
            var connection = new CrmConnection("Crm");
            var service    = new OrganizationService(connection);
            var context    = new OrganizationServiceContext(service);

            using (ShimsContext.Create())
            {
                var       fakeContext = new Microsoft.Xrm.Sdk.Client.Fakes.ShimOrganizationServiceContext(context);
                LINQToCRM target      = new LINQToCRM(context);

                var entity1 = new Microsoft.Xrm.Sdk.Entity("account");
                entity1.Id      = Guid.NewGuid();
                entity1["name"] = "abcabcabc";

                var entity2 = new Microsoft.Xrm.Sdk.Entity("account");
                entity2.Id      = Guid.NewGuid();
                entity2["name"] = "123123123";

                var entity3 = new Microsoft.Xrm.Sdk.Entity("account");
                entity3.Id      = Guid.NewGuid();
                entity3["name"] = "a1b2c3a1b2c3";

                fakeContext.CreateQueryString = (entityName) =>
                {
                    return(new System.Linq.EnumerableQuery <Microsoft.Xrm.Sdk.Entity>(new Microsoft.Xrm.Sdk.Entity[] { entity1, entity2, entity3 }));
                };

                IEnumerable <Microsoft.Xrm.Sdk.Entity> expected = new List <Microsoft.Xrm.Sdk.Entity> {
                    entity1, entity2
                };

                System.Linq.Fakes.ShimEnumerableQuery <Microsoft.Xrm.Sdk.Entity> .AllInstances.GetEnumerator = (a) =>
                {
                    return(expected.GetEnumerator());
                };

                string accountName = "abcabcabc";
                IEnumerable <Microsoft.Xrm.Sdk.Entity> actual;
                actual = target.RetrieveAccountsByName(accountName);

                Assert.AreEqual(expected.Count(), actual.Count());
                Assert.AreEqual(expected.ElementAt(0), actual.ElementAt(0));
                Assert.AreEqual(expected.ElementAt(1), actual.ElementAt(1));
            }
        }
Ejemplo n.º 18
0
        internal static Microsoft.Xrm.Sdk.Entity ToCrmEntity <T>(this T crmPlusPlusEntity) where T : CrmPlusPlusEntity, new()
        {
            var entity = new Microsoft.Xrm.Sdk.Entity(EntityNameAttribute.GetFromType <T>(), crmPlusPlusEntity.Id);

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(T)))
            {
                var attributes = property.Attributes.AsEnumerable();

                var propertyNameAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute));
                var propertyInfoAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute));
                var typeInfoAttr     = attributes
                                       .SingleOrDefault(attr => (attr.GetType() == typeof(BooleanAttribute) && property.PropertyType == typeof(bool)) ||
                                                        (attr.GetType() == typeof(DateTimeAttribute) && property.PropertyType == typeof(DateTime)) ||
                                                        (attr.GetType() == typeof(DecimalAttribute) && property.PropertyType == typeof(decimal)) ||
                                                        (attr.GetType() == typeof(DoubleAttribute) && property.PropertyType == typeof(double)) ||
                                                        (attr.GetType() == typeof(IntegerAttribute) && property.PropertyType == typeof(int)) ||
                                                        (attr.GetType() == typeof(StringAttribute) && property.PropertyType == typeof(string)) ||
                                                        (attr.GetType() == typeof(LookupAttribute) && property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference <>)) ||
                                                        (attr.GetType() == typeof(OptionSetAttribute) && property.PropertyType.IsEnum));

                if (propertyNameAttr != null && propertyInfoAttr != null && typeInfoAttr != null)
                {
                    var propertyName = ((PropertyNameAttribute)propertyNameAttr).PropertyName;
                    var value        = property.GetValue(crmPlusPlusEntity);

                    if (value != null)
                    {
                        if (value.GetType().IsGenericType&& value.GetType().GetGenericTypeDefinition() == typeof(EntityReference <>))
                        {
                            var entityReferenceType = property.PropertyType.GetGenericArguments().Single();
                            var entityName          = EntityNameAttribute.GetFromType(entityReferenceType);

                            value = new Microsoft.Xrm.Sdk.EntityReference(entityName, ((dynamic)value).Id);
                        }
                        else if (value.GetType().IsEnum)
                        {
                            value = new Microsoft.Xrm.Sdk.OptionSetValue((int)value);
                        }

                        entity[propertyName] = value;
                    }
                }
            }

            return(entity);
        }
        public void PreValueOfTest()
        {
            var ctx = new Kipon.Solid.Plugin.UnitTests.Mocks.PluginExecutionContext
            {
                PreEntityImages = new Microsoft.Xrm.Sdk.EntityImageCollection()
            };

            var account = new Microsoft.Xrm.Sdk.Entity(Kipon.Solid.Plugin.Entities.Account.EntityLogicalName, Guid.NewGuid());

            account["accountcategorycode"] = new Microsoft.Xrm.Sdk.OptionSetValue(1);
            account["name"] = "Kipon ApS";
            var parent = new Microsoft.Xrm.Sdk.EntityReference("account", new Guid());

            account["parentaccountid"] = parent;
            ctx.PreEntityImages.Add("animage", account);

            var enumValue = ctx.PreValueOf <Kipon.Solid.Plugin.Entities.Account.AnEnum?>(nameof(Kipon.Solid.Plugin.Entities.Account.AnEnumValue));

            Assert.AreEqual(Kipon.Solid.Plugin.Entities.Account.AnEnum.Value1, enumValue);
            Assert.AreEqual(account["name"], ctx.PreValueOf <string>(nameof(Kipon.Solid.Plugin.Entities.Account.Name)));

            Assert.AreEqual(parent, ctx.PreValueOf <Microsoft.Xrm.Sdk.EntityReference>(nameof(Kipon.Solid.Plugin.Entities.Account.ParentAccountId)));

            account.Attributes.Remove("accountcategorycode");
            enumValue = ctx.PreValueOf <Kipon.Solid.Plugin.Entities.Account.AnEnum?>(nameof(Kipon.Solid.Plugin.Entities.Account.AnEnumValue));
            Assert.IsNull(enumValue);

            {
                var ex = Assert.ThrowsException <Microsoft.Xrm.Sdk.InvalidPluginExecutionException>(() =>
                {
                    ctx.PreValueOf <string>("NoneExistingProperty");
                });

                Assert.AreEqual(string.Format(Kipon.Xrm.Extensions.Sdk.KiponSdkGeneratedExtensionMethods.UNDEFINED_ATTRIBUTE_MESSAGE, "account", "NoneExistingProperty"), ex.Message);
            }

            {
                var ex = Assert.ThrowsException <Microsoft.Xrm.Sdk.InvalidPluginExecutionException>(() =>
                {
                    ctx.PreValueOf <string>(nameof(Kipon.Solid.Plugin.Entities.Account.NoDecorationProperty));
                });

                Assert.AreEqual(string.Format(Kipon.Xrm.Extensions.Sdk.KiponSdkGeneratedExtensionMethods.MISSING_DECORATION_ATTRIBUTE_MESSAGE, "account", nameof(Kipon.Solid.Plugin.Entities.Account.NoDecorationProperty)), ex.Message);
            }
        }
Ejemplo n.º 20
0
        public static Guid PrayerCreate(this OrganizationServiceProxy service, Microsoft.Xrm.Sdk.Entity entity, TimeSpan timeout, int tryCount)
        {
            TimeSpan tempTimeOut = service.Timeout;

            service.Timeout = timeout;

            int tc = tryCount;

            do
            {
                try
                {
                    if (tc == 1)
                    {
                        service.Timeout = tempTimeOut;
                    }
                    var id = service.Create(entity);

                    service.Timeout = tempTimeOut;
                    return(id);
                }
                catch (Exception e)
                {
                    if (e.Message == "Generic SQL error." ||
                        e is System.Data.SqlClient.SqlException ||
                        e is TimeoutException)
                    {
                        tc--;
                        if (tryCount <= 0)
                        {
                            service.Timeout = tempTimeOut;
                            throw e;
                        }
                    }
                    else
                    {
                        service.Timeout = tempTimeOut;
                        throw e;
                    }
                }
            } while (tryCount > 0);

            return(Guid.Empty);
        }
Ejemplo n.º 21
0
        public bool IsRelevant(Microsoft.Xrm.Sdk.Entity target)
        {
            if (this.FilterAllProperties)
            {
                return(true);
            }

            if (this.FilteredProperties != null && this.FilteredProperties.Length > 0)
            {
                foreach (var f in this.FilteredProperties)
                {
                    if (target.Attributes.Keys.Contains(f.LogicalName))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        public void OptionSetCollectionToArrayTest()
        {
            var entity = new Microsoft.Xrm.Sdk.Entity();

            var col = new Microsoft.Xrm.Sdk.OptionSetValueCollection();

            col.Add(new Microsoft.Xrm.Sdk.OptionSetValue(1));
            col.Add(new Microsoft.Xrm.Sdk.OptionSetValue(2));

            entity["enumvaluecol"] = col;

            var enumcol = entity.Attributes.ValueOf <TestEnum[]>("enumvaluecol");

            Assert.AreEqual(TestEnum.V1, enumcol[0]);
            Assert.AreEqual(TestEnum.V2, enumcol[1]);

            TestEnum[] notin = entity.Attributes.ValueOf <TestEnum[]>("notinthere");

            Assert.IsNull(notin);
        }
        public Guid Create(Microsoft.Xrm.Sdk.Entity target)
        {
            this.preImage = null;
            try
            {
                if (target.Id == Guid.Empty)
                {
                    target.Id = Guid.NewGuid();
                }

                var key = target.LogicalName + target.Id.ToString();
                if (entities.ContainsKey(key))
                {
                    throw new Exceptions.EntityExistsException(target);
                }

                this.ExecuteStep(target, 10, "Create", false, null, this.OnValidation);
                this.ExecuteStep(target, 20, "Create", false, () =>
                {
                    ((Repository.IEntityShadow) this).Create(target);
                    ((Repository.IEntityShadow) this).Commit();
                }, this.OnPre);

                this.ExecuteStep(target, 40, "Create", false, () =>
                {
                    ((Repository.IEntityShadow) this).Commit();
                }, OnPost);

                this.ExecuteStep(target, 40, "Create", true, () =>
                {
                    ((Repository.IEntityShadow) this).Commit();
                }, OnPostAsync);

                return(target.Id);
            } catch (Exception)
            {
                ((IEntityShadow)this).Rollback();
                throw;
            }
        }
Ejemplo n.º 24
0
        private void testConnection()
        {
            string organizationUrl = "https://csp-build.crm.dynamics.com";
            string resourceURL     = "https://csp-build.api.crm.dynamics.com" + "/api/data/";
            string clientId        = "c4e4407b-66d1-4452-9b05-db0a0ce9baef"; // Client Id
            string appKey          = "Sy[?Mk106C2OvHXZ:Krytwj=_XN_KKlh";     //Client Secret

            //Create the Client credentials to pass for authentication
            ClientCredential clientcred = new ClientCredential(clientId, appKey);


            //get the authentication parameters
            AuthenticationParameters authParam = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(resourceURL)).Result;

            //Generate the authentication context - this is the azure login url specific to the tenant
            string authority = authParam.Authority;

            //request token
            AuthenticationResult authenticationResult = new AuthenticationContext(authority).AcquireTokenAsync(organizationUrl, clientcred).Result;

            //get the token
            string token = authenticationResult.AccessToken;

            Uri serviceUrl = new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=9.1");
            OrganizationWebProxyClient sdkService;

            Microsoft.Xrm.Sdk.IOrganizationService _orgService;

            sdkService             = new OrganizationWebProxyClient(serviceUrl, false);
            sdkService.CallerId    = new Guid("{A9D51F0B-B11B-E611-80E0-5065F38AA901}");
            sdkService.HeaderToken = token;

            _orgService = (Microsoft.Xrm.Sdk.IOrganizationService)sdkService != null ? (Microsoft.Xrm.Sdk.IOrganizationService)sdkService : null;


            Microsoft.Xrm.Sdk.Entity user = _orgService.Retrieve("systemuser", new Guid("{A9D51F0B-B11B-E611-80E0-5065F38AA901}"), new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
        }
 public EntityExistsException(Microsoft.Xrm.Sdk.Entity entity) : base($"Entity: {entity.LogicalName} + Id: {entity.Id.ToString()} already exists.")
 {
 }
Ejemplo n.º 26
0
 public System.Guid Create(Microsoft.Xrm.Sdk.Entity entity)
 {
     return(base.Channel.Create(entity));
 }
Ejemplo n.º 27
0
 public void Update(Microsoft.Xrm.Sdk.Entity entity)
 {
     base.Channel.Update(entity);
 }
        public void AddEntity(Microsoft.Xrm.Sdk.Entity crmEntity)
        {
            var et = new EntityShadow(crmEntity);

            entities.Add(et.Key, et);
        }
        private Microsoft.Xrm.Sdk.Entity ResolveImage(string logicalName, Guid id, int pre1post2, Kipon.Fake.Xrm.Reflection.PluginMethod[] methods, EntityShadow pre)
        {
            if (pre1post2 == 1 && pre == null)
            {
                throw new ArgumentException("For pre you must parse the pre entity state");
            }

            if (pre1post2 == 2 && pre != null)
            {
                throw new ArgumentException("For post you cannot parse the pre entity state");
            }

            var needAll = false;

            string[] neededProperties = null;

            if (pre1post2 == 1)
            {
                var need = (from m in methods where m.NeedPreimage select m).Any();
                if (!need)
                {
                    return(null);
                }
                needAll = (from m in methods where m.AllPreimageProperties select m).Any();

                if (!needAll)
                {
                    var np = new List <string>();
                    foreach (var m in methods)
                    {
                        if (m.PreimageProperties != null && m.PreimageProperties.Length > 0)
                        {
                            np.AddRange((from p in m.PreimageProperties select p.LogicalName).Distinct());
                        }
                    }
                    neededProperties = np.Distinct().ToArray();
                }
            }

            if (pre1post2 == 2)
            {
                var need = (from m in methods where m.NeedPostimage select m).Any();
                if (!need)
                {
                    return(null);
                }

                needAll = (from m in methods where m.AllPostimageProperties select m).Any();
                if (!needAll)
                {
                    var np = new List <string>();
                    foreach (var m in methods)
                    {
                        if (m.PostimageProperties != null && m.PostimageProperties.Length > 0)
                        {
                            np.AddRange((from p in m.PostimageProperties select p.LogicalName).Distinct());
                        }
                    }
                    neededProperties = np.Distinct().ToArray();
                }
            }

            if (needAll == false && (neededProperties == null || neededProperties.Length == 0))
            {
                return(null);
            }

            var key = logicalName + id.ToString();

            if (!this.entities.ContainsKey(key))
            {
                throw new Exceptions.EntityNotFoundException(logicalName, id);
            }

            var data = pre;

            if (pre1post2 == 2)
            {
                data = entities[key];
            }

            if (needAll)
            {
                return(data.ToEntity());
            }

            var result = new Microsoft.Xrm.Sdk.Entity {
                LogicalName = logicalName, Id = id
            };

            foreach (var prop in neededProperties)
            {
                result[prop] = data.ValueOf(prop);
            }
            return(result);
        }
Ejemplo n.º 30
0
        public static string GetAttributeLabel(Microsoft.Xrm.Sdk.IOrganizationService service, Microsoft.Xrm.Sdk.Entity entity, string attribute)

        {
            string strLabel = String.Empty;

            Microsoft.Xrm.Sdk.OptionSetValue option = null;



            var attributeRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveAttributeRequest

            {
                EntityLogicalName = entity.LogicalName,

                LogicalName = attribute,

                RetrieveAsIfPublished = true
            };



            Microsoft.Xrm.Sdk.Messages.RetrieveAttributeResponse attributeResponse = (Microsoft.Xrm.Sdk.Messages.RetrieveAttributeResponse)service.Execute(attributeRequest);

            Microsoft.Xrm.Sdk.Metadata.AttributeMetadata attrMetadata = (Microsoft.Xrm.Sdk.Metadata.AttributeMetadata)attributeResponse.AttributeMetadata;

            Microsoft.Xrm.Sdk.Metadata.OptionMetadataCollection optionMeta = null;



            //Console.Write("\tDebug attributeType : " + attrMetadata.AttributeType.ToString() + "\t");



            #region Switch

            switch (attrMetadata.AttributeType.ToString())

            {
            case "Status":     //Status

                optionMeta = ((Microsoft.Xrm.Sdk.Metadata.StatusAttributeMetadata)attrMetadata).OptionSet.Options;

                break;

            case "Picklist":     //Picklist

                optionMeta = ((Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)attrMetadata).OptionSet.Options;

                break;

            case "State":     //State

                optionMeta = ((Microsoft.Xrm.Sdk.Metadata.StateAttributeMetadata)attrMetadata).OptionSet.Options;

                break;

            case "Decimal":     //Decimal

                break;

            case "Enum":     //Enum

                break;

            case "Memo":     //Memo

                break;

            case "Money":     //Money

                break;

            case "Lookup":

                break;

            case "Integer":

                break;

            case "Owner":

                strLabel = ((Microsoft.Xrm.Sdk.EntityReference)entity.Attributes[attribute]).Name;

                break;

            case "DateTime":     //DateTime

                strLabel = Convert.ToDateTime(entity.Attributes[attribute].ToString()).ToString();

                break;

            case "Boolean":     //Boolean

                break;

            case "String":     //String

                strLabel = entity[attribute].ToString();

                break;

            case "Double":     //Double

                break;

            case "EntityName":     //Entity Name

                break;

            case "Image":     //Image, it will return image name.

                break;

            case "BigInt":

                break;

            case "ManagedProperty":

                break;

            case "Uniqueidentifier":

                break;

            case "Virtual":

                break;

            default:

                //TODO: Write Err Exception

                break;
            }

            #endregion Switch

            //If this attr is OptionSet, Find Label
            if (optionMeta != null)
            {
                option = ((Microsoft.Xrm.Sdk.OptionSetValue)entity.Attributes[attribute]);

                foreach (Microsoft.Xrm.Sdk.Metadata.OptionMetadata metadata in optionMeta)

                {
                    if (metadata.Value == option.Value)

                    {
                        strLabel = metadata.Label.UserLocalizedLabel.Label;
                    }
                }
            }



            return(strLabel);
        }