示例#1
0
        public Dictionary <string, Type> GetOneToManyRelationships()
        {
            var aliases = GetAliasesInCollection();

            var oneToManyRelationships = TypeDescriptor.GetProperties(typeof(T)).AsEnumerable()
                                         .Where(p => p.PropertyType.IsGenericType &&
                                                p.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) &&
                                                p.PropertyType.GetGenericArguments().Count() == 1 &&
                                                p.PropertyType.GetGenericArguments().Single() != typeof(T) &&
                                                typeof(CrmPlusPlusEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments().Single()));

            var relationships = new Dictionary <string, Type>();

            foreach (var oneToManyRelationship in oneToManyRelationships)
            {
                var manyEntity = oneToManyRelationship.PropertyType.GetGenericArguments().Single();
                var alias      = EntityNameAttribute.GetFromType(manyEntity);

                if (aliases.Contains(alias) && !relationships.ContainsKey(alias))
                {
                    relationships.Add(alias, manyEntity);
                }
            }

            return(relationships);
        }
示例#2
0
        internal Query(Query query, string from, string to, JoinType joinType, int linkedEntityDepth)
        {
            var entityName = EntityNameAttribute.GetFromType <T>();

            this.query             = query;
            this.linkedEntityDepth = linkedEntityDepth;

            EntityRootElement = new XElement("link-entity");
            EntityRootElement.Add(new XAttribute("name", entityName));
            EntityRootElement.Add(new XAttribute("alias", entityName));
            EntityRootElement.Add(new XAttribute("from", from));
            EntityRootElement.Add(new XAttribute("to", to));
            EntityRootElement.Add(new XAttribute("link-type", joinType.ToString().ToLower()));

            if (linkedEntityDepth < 2)
            {
                var createdOn = new XElement("attribute");
                createdOn.Add(new XAttribute("name", "createdon"));
                EntityRootElement.Add(createdOn);

                var modifiedOn = new XElement("attribute");
                modifiedOn.Add(new XAttribute("name", "modifiedon"));
                EntityRootElement.Add(modifiedOn);
            }
        }
示例#3
0
        public T Retrieve <T>(Retrieval <T> retrieval) where T : CrmPlusPlusEntity, new()
        {
            var crmEntity = service.Retrieve(EntityNameAttribute.GetFromType <T>(),
                                             retrieval.Id,
                                             retrieval.AllColumns
                    ? new ColumnSet(true)
                    : new ColumnSet(retrieval.IncludedColumns.ToArray()));

            return(crmEntity.ToCrmPlusPlusEntity <T>());
        }
        public void CreateProperty <T, TProperty>(Expression <Func <T, TProperty> > propertyExpr) where T : CrmPlusPlusEntity, new()
        {
            var entityName   = EntityNameAttribute.GetFromType <T>();
            var propertyName = PropertyNameAttribute.GetFromType(propertyExpr);
            var propertyInfo = PropertyInfoAttribute.GetFromType(propertyExpr);

            var attributes = ((MemberExpression)propertyExpr.Body).Member.GetCustomAttributes(true);

            CreateProperty(entityName, typeof(TProperty), attributes, propertyName, propertyInfo);
        }
        public void Delete <T>() where T : CrmPlusPlusEntity, new()
        {
            var entityName = EntityNameAttribute.GetFromType <T>();

            var deleteEntityRequest = new DeleteEntityRequest
            {
                LogicalName = entityName
            };

            service.Execute(deleteEntityRequest);
        }
        public void Has1ToNRelatedEntityRecords_ReturnsDataCorrectly()
        {
            var testEntity1Id        = Guid.NewGuid();
            var testEntity1String    = "dshajdsghjk";
            var testEntity2FirstId   = Guid.NewGuid();
            var testEntity2SecondId  = Guid.NewGuid();
            var testEntity2FirstInt  = 3;
            var testEntity2SecondInt = 5;

            var flatData = new List <Entity>();

            var first = new Entity(EntityNameAttribute.GetFromType <RetrieveMultipleTestEntity1>(), testEntity1Id);

            first["id"]         = testEntity1Id;
            first["createdon"]  = DateTime.Now;
            first["modifiedon"] = DateTime.Now;
            first["teststring"] = testEntity1String;
            first["retrievemultipletestentity2.id"]      = new AliasedValue("retrievemultipletestentity2", "id", testEntity2FirstId);
            first["retrievemultipletestentity2.testint"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity2FirstInt);

            var second = new Entity(EntityNameAttribute.GetFromType <RetrieveMultipleTestEntity1>(), testEntity1Id);

            second["id"]         = testEntity1Id;
            second["createdon"]  = DateTime.Now;
            second["modifiedon"] = DateTime.Now;
            second["teststring"] = testEntity1String;
            second["retrievemultipletestentity2.id"]      = new AliasedValue("retrievemultipletestentity2", "id", testEntity2SecondId);
            second["retrievemultipletestentity2.testint"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity2SecondInt);

            flatData.Add(first);
            flatData.Add(second);

            var service = A.Fake <IOrganizationService>();

            A.CallTo(() => service.RetrieveMultiple(A <QueryBase> ._))
            .Returns(new EntityCollection(flatData));

            var crmPlusPlusEntityClient = new CrmPlusPlusEntityClient(service);

            var result = crmPlusPlusEntityClient.RetrieveMultiple(Query.ForEntity <RetrieveMultipleTestEntity1>());

            Assert.Equal(1, result.Count());
            Assert.Equal(2, result.Single().RelatedEntities.Count());

            var firstEntity = result.Single();

            Assert.Equal(testEntity1String, firstEntity.TestString);
            Assert.Contains(testEntity2FirstInt, firstEntity.RelatedEntities.Select(e => e.TestInt));
            Assert.Contains(testEntity2SecondInt, firstEntity.RelatedEntities.Select(e => e.TestInt));
        }
示例#7
0
        public Query <T> JoinNTo1 <TRelatedEntity>(Expression <Func <T, EntityReference <TRelatedEntity> > > joinExpr,
                                                   JoinType joinType,
                                                   Action <Query <TRelatedEntity> > queryBuilder) where TRelatedEntity : CrmPlusPlusEntity, new()
        {
            var to   = PropertyNameAttribute.GetFromType(joinExpr);
            var from = EntityNameAttribute.GetFromType <TRelatedEntity>() + "id";

            var entityQuery = new Query <TRelatedEntity>(query, from, to, joinType, linkedEntityDepth + 1);

            queryBuilder(entityQuery);

            EntityRootElement.Add(entityQuery.EntityRootElement);

            return(this);
        }
        public void CreateOneToManyRelationship <TOne, TMany>(Expression <Func <TMany, EntityReference <TOne> > > lookupExpr, EntityAttributes.Metadata.AttributeRequiredLevel lookupRequiredLevel, string relationshipPrefix = "new")
            where TOne : CrmPlusPlusEntity, new()
            where TMany : CrmPlusPlusEntity, new()
        {
            Guard.This(relationshipPrefix).AgainstNullOrEmpty();

            var oneEntityName      = EntityNameAttribute.GetFromType <TOne>();
            var manyEntityName     = EntityNameAttribute.GetFromType <TMany>();
            var oneDisplayName     = EntityInfoAttribute.GetFromType <TOne>().DisplayName;
            var lookupPropertyName = PropertyNameAttribute.GetFromType(lookupExpr);

            var oneToManyRequest = new CreateOneToManyRequest
            {
                OneToManyRelationship = new OneToManyRelationshipMetadata
                {
                    ReferencedEntity            = oneEntityName,
                    ReferencingEntity           = manyEntityName,
                    SchemaName                  = relationshipPrefix.EndsWith("_") ? relationshipPrefix : relationshipPrefix + "_" + oneEntityName + "_" + manyEntityName,
                    AssociatedMenuConfiguration = new AssociatedMenuConfiguration
                    {
                        Behavior = AssociatedMenuBehavior.UseLabel,
                        Group    = AssociatedMenuGroup.Details,
                        Label    = oneDisplayName.ToLabel(),
                        Order    = 10000
                    },
                    CascadeConfiguration = new CascadeConfiguration
                    {
                        Assign   = CascadeType.NoCascade,
                        Delete   = CascadeType.RemoveLink,
                        Merge    = CascadeType.NoCascade,
                        Reparent = CascadeType.NoCascade,
                        Share    = CascadeType.NoCascade,
                        Unshare  = CascadeType.NoCascade
                    }
                },
                Lookup = new LookupAttributeMetadata
                {
                    SchemaName    = lookupPropertyName,
                    DisplayName   = (oneDisplayName + " Lookup").ToLabel(),
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(lookupRequiredLevel.ToSimilarEnum <AttributeRequiredLevel>()),
                    Description   = (oneDisplayName + " Lookup").ToLabel()
                }
            };

            service.Execute(oneToManyRequest);
        }
示例#9
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 bool CanCreateOneToManyRelationship <TOne, TMany>()
            where TOne : CrmPlusPlusEntity, new()
            where TMany : CrmPlusPlusEntity, new()
        {
            var canBeReferencedRequest = new CanBeReferencedRequest
            {
                EntityName = EntityNameAttribute.GetFromType <TOne>()
            };

            var canBeReferencingRequest = new CanBeReferencingRequest
            {
                EntityName = EntityNameAttribute.GetFromType <TMany>()
            };

            bool canBeReferenced  = ((CanBeReferencedResponse)service.Execute(canBeReferencedRequest)).CanBeReferenced;
            bool canBeReferencing = ((CanBeReferencingResponse)service.Execute(canBeReferencingRequest)).CanBeReferencing;

            return(canBeReferenced && canBeReferencing);
        }
示例#11
0
        internal Query(Query query)
        {
            this.query = query;

            EntityRootElement = new XElement("entity");
            EntityRootElement.Add(new XAttribute("name", EntityNameAttribute.GetFromType <T>()));

            var createdOn = new XElement("attribute");

            createdOn.Add(new XAttribute("name", "createdon"));
            EntityRootElement.Add(createdOn);

            var modifiedOn = new XElement("attribute");

            modifiedOn.Add(new XAttribute("name", "modifiedon"));
            EntityRootElement.Add(modifiedOn);

            linkedEntityDepth = 0;
        }
        public void HasNTo1RelatedEntityRecords_ReturnsDataCorrectly()
        {
            var testEntity2Id     = Guid.NewGuid();
            var testEntity2Int    = 2;
            var testEntity1Id     = Guid.NewGuid();
            var testEntity1String = "dshjakl";

            var flatData = new List <Entity>();

            var entity = new Entity(EntityNameAttribute.GetFromType <RetrieveMultipleTestEntity2>(), testEntity2Id);

            entity["id"]         = testEntity2Id;
            entity["createdon"]  = DateTime.Now;
            entity["modifiedon"] = DateTime.Now;
            entity["testint"]    = testEntity2Int;
            entity["retrievemultipletestentity1.id"]         = new AliasedValue("retrievemultipletestentity2", "id", testEntity1Id);
            entity["retrievemultipletestentity1.teststring"] = new AliasedValue("retrievemultipletestentity2", "testint", testEntity1String);

            flatData.Add(entity);

            var service = A.Fake <IOrganizationService>();

            A.CallTo(() => service.RetrieveMultiple(A <QueryBase> ._))
            .Returns(new EntityCollection(flatData));

            var crmPlusPlusEntityClient = new CrmPlusPlusEntityClient(service);

            var result = crmPlusPlusEntityClient.RetrieveMultiple(Query.ForEntity <RetrieveMultipleTestEntity2>());

            Assert.Equal(1, result.Count());

            var singleResult = result.Single();

            Assert.Equal(testEntity2Int, singleResult.TestInt);
            Assert.NotNull(singleResult.RetrieveMultipleTestEntity1Lookup);
            Assert.Equal(testEntity1Id, singleResult.RetrieveMultipleTestEntity1Lookup.Id);
            Assert.NotNull(singleResult.RetrieveMultipleTestEntity1Lookup.Entity);

            Assert.Equal(testEntity1Id, singleResult.RetrieveMultipleTestEntity1Lookup.Entity.Id);
            Assert.Equal(testEntity1String, singleResult.RetrieveMultipleTestEntity1Lookup.Entity.TestString);
        }
示例#13
0
        public void CorrectlyMapsPropertiesToCrmEntity()
        {
            var lookupId = Guid.NewGuid();

            var myString    = "dhsjadhkjsl";
            var myInt       = 32;
            var myDateTime  = DateTime.Now;
            var myDecimal   = 143.12M;
            var myBool      = false;
            var myDouble    = 103.23;
            var myLookup    = new EntityReference <CrmPlusPlusEntityExtensionsEntity>(lookupId);
            var myOptionSet = TestOptionSet.Three;

            var entity = new CrmPlusPlusEntityExtensionsEntity
            {
                MyString   = myString,
                MyInt      = myInt,
                MyDateTime = myDateTime,
                MyDecimal  = myDecimal,
                MyBool     = myBool,
                MyDouble   = myDouble,
                MyLookup   = myLookup,
                OptionSet  = myOptionSet
            };

            var crmEntity = entity.ToCrmEntity();

            Assert.Equal(myString, crmEntity["civica_string"]);
            Assert.Equal(myInt, crmEntity["civica_int"]);
            Assert.Equal(myDateTime, crmEntity["civica_datetime"]);
            Assert.Equal(myDecimal, crmEntity["civica_decimal"]);
            Assert.Equal(myBool, crmEntity["civica_bool"]);
            Assert.Equal(myDouble, crmEntity["civica_double"]);

            Assert.Equal(myLookup.Id, ((Microsoft.Xrm.Sdk.EntityReference)crmEntity["civica_lookup"]).Id);
            Assert.Equal(EntityNameAttribute.GetFromType <CrmPlusPlusEntityExtensionsEntity>(), ((Microsoft.Xrm.Sdk.EntityReference)crmEntity["civica_lookup"]).LogicalName);

            Assert.Equal((int)myOptionSet, ((OptionSetValue)crmEntity["civica_optionset"]).Value);
        }
        public void CreateEntity <T>() where T : CrmPlusPlusEntity, new()
        {
            var entityName = EntityNameAttribute.GetFromType <T>();
            var entityInfo = EntityInfoAttribute.GetFromType <T>();

            var createEntityRequest = new CreateEntityRequest
            {
                Entity = new EntityMetadata
                {
                    SchemaName            = entityName,
                    DisplayName           = entityInfo.DisplayName.ToLabel(),
                    DisplayCollectionName = entityInfo.PluralDisplayName.ToLabel(),
                    Description           = entityInfo.Description.ToLabel(),
                    OwnershipType         = entityInfo.OwnershipType,
                    IsActivity            = false
                },
                PrimaryAttribute = new StringAttributeMetadata
                {
                    SchemaName    = entityName + "primary",
                    RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                    MaxLength     = 100,
                    FormatName    = Microsoft.Xrm.Sdk.Metadata.StringFormatName.Text,
                    DisplayName   = "Primary attribute".ToLabel(),
                    Description   = string.Format("The primary attribute for the {0} entity", entityInfo.DisplayName).ToLabel()
                }
            };

            var response = (CreateEntityResponse)service.Execute(createEntityRequest);

            var addReq = new AddSolutionComponentRequest()
            {
                ComponentType      = (int)SolutionComponentTypes.Entity,
                ComponentId        = response.EntityId,
                SolutionUniqueName = Solution.Name
            };

            service.Execute(addReq);
        }
        public void CreateAllProperties <T>() where T : CrmPlusPlusEntity, new()
        {
            var entityName = EntityNameAttribute.GetFromType <T>();

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(typeof(T)))
            {
                var attributes = new List <object>();
                foreach (var attribute in property.Attributes)
                {
                    attributes.Add(attribute);
                }

                var propertyNameAttribute = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute));
                var propertyInfoAttribute = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute));

                if (propertyNameAttribute != null && propertyInfoAttribute != null)
                {
                    var name = (PropertyNameAttribute)propertyNameAttribute;
                    var info = (PropertyInfoAttribute)propertyInfoAttribute;

                    CreateProperty(entityName, property.PropertyType, attributes, name.PropertyName, info);
                }
            }
        }
示例#16
0
        public Associate With <TRelatedEntity>(TRelatedEntity entity) where TRelatedEntity : CrmPlusPlusEntity, new()
        {
            RelatedEntities.Add(entity.Id, EntityNameAttribute.GetFromType <TRelatedEntity>());

            return(this);
        }
示例#17
0
        public static Associate ThisEntity <T>(T entity) where T : CrmPlusPlusEntity, new()
        {
            var entityName = EntityNameAttribute.GetFromType <T>();

            return(new Associate(entity.Id, entityName));
        }
示例#18
0
 public void Delete <T>(T entity) where T : CrmPlusPlusEntity, new()
 {
     service.Delete(EntityNameAttribute.GetFromType <T>(), entity.Id);
 }