Exemple #1
0
        public void When_execute_is_called_with_reversed_target_and_Related()
        {
            var context = new XrmFakedContext();

            var userId  = Guid.NewGuid();
            var teamId  = Guid.NewGuid();
            var user2Id = Guid.NewGuid();

            context.Initialize(new List <Entity> {
                new SystemUser
                {
                    Id = userId
                },
                new SystemUser
                {
                    Id = user2Id
                },
                new Team
                {
                    Id = teamId
                }
            });

            context.AddRelationship("teammembership", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.ManyToMany,
                IntersectEntity    = "teammembership",
                Entity1Attribute   = "systemuserid",
                Entity1LogicalName = "systemuser",
                Entity2Attribute   = "teamid",
                Entity2LogicalName = "team"
            });

            var orgSvc = context.GetFakedOrganizationService();

            orgSvc.Associate("team", teamId, new Relationship("teammembership"),
                             new EntityReferenceCollection(new List <EntityReference> {
                new EntityReference("systemuser", userId)
            }));

            orgSvc.Associate("systemuser", user2Id, new Relationship("teammembership"),
                             new EntityReferenceCollection(new List <EntityReference> {
                new EntityReference("team", teamId)
            }));

            using (Crm.XrmServiceContext ctx = new XrmServiceContext(orgSvc))
            {
                var firstAssociation = (from tu in ctx.TeamMembershipSet
                                        where tu.TeamId == teamId &&
                                        tu.SystemUserId == userId
                                        select tu).FirstOrDefault();
                Assert.NotNull(firstAssociation);

                var secondAssociation = (from tu in ctx.TeamMembershipSet
                                         where tu.TeamId == teamId &&
                                         tu.SystemUserId == user2Id
                                         select tu).FirstOrDefault();
                Assert.NotNull(secondAssociation);
            }
        }
Exemple #2
0
        public void When_execute_is_called_with_empty_relatedentities_collection_exception_is_thrown()
        {
            // arrange
            var context = new XrmFakedContext();

            var teamId = Guid.NewGuid();

            context.Initialize(new List <Entity> {
                new Team
                {
                    Id = teamId
                }
            });

            context.AddRelationship("teammembership", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.ManyToMany,
                IntersectEntity    = "teammembership",
                Entity1Attribute   = "systemuserid",
                Entity1LogicalName = "systemuser",
                Entity2Attribute   = "teamid",
                Entity2LogicalName = "team"
            });

            var orgSvc = context.GetFakedOrganizationService();


            // act, assert
            Assert.Throws <IndexOutOfRangeException>(() => orgSvc.Associate("team", teamId, new Relationship("teammembership"),
                                                                            new EntityReferenceCollection()));
        }
            public void recalculatechecklistresponses_field_should_be_set_to_true()
            {
                // Arrange
                var  context = new XrmFakedContext();
                var  pluginContext = context.GetDefaultPluginContext();
                Guid targetComplaint, targetIndustry;

                context.Initialize(new[]
                {
                    new Entity("opc_complaint", targetComplaint = Guid.NewGuid()),
                    new Entity("industry", targetIndustry       = Guid.NewGuid()),
                    new opc_complaintsrelatedindustries {
                        Id = Guid.NewGuid(), ["complaintid"] = targetComplaint, ["industryid"] = targetIndustry
                    }
                });
                context.AddRelationship
                (
                    nameof(opc_complaint.opc_complaints_industries_relatedindustries),
                    new XrmFakedRelationship(nameof(opc_complaint.opc_complaints_industries_relatedindustries), "complaintid", "industryid", "opc_complaint", "industry")
                );

                pluginContext.MessageName     = PluginMessage.Associate;
                pluginContext.InputParameters = new ParameterCollection
                {
                    { "Target", new EntityReference("opc_complaint", targetComplaint) },
                    { "Relationship", new Relationship(nameof(opc_complaint.opc_complaints_industries_relatedindustries)) },
                    { "RelatedEntities", new EntityReferenceCollection(new [] { new EntityReference("industry", targetIndustry) }) }
                };

                // Act
                context.ExecutePluginWith <RecalculateChecklistResponsesFlagPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().Retrieve("opc_complaint", targetComplaint, new ColumnSet("opc_recalculatechecklistresponses"))?.Attributes["opc_recalculatechecklistresponses"].Should().Be(true);
            }
Exemple #4
0
        public void Create_RelatedRecordExists()
        {
            var fake  = new XrmFakedContext();
            var accnt = new Account {
                Id = Guid.NewGuid()
            };

            fake.Initialize(accnt);
            fake.AddRelationship("account_primary_contact", new XrmFakedRelationship("contactid", "primarycontactid", Contact.EntityLogicalName, Account.EntityLogicalName));
            var fakedService = fake.GetOrganizationService();

            using (var ctx = new Crm.XrmServiceContext(fakedService))
            {
                var cntc = new Contact();
                ctx.AddObject(cntc);

                ctx.Attach(accnt);
                ctx.AddLink(cntc, new Microsoft.Xrm.Sdk.Relationship("account_primary_contact"), accnt);

                ctx.SaveChanges();

                accnt = ctx.AccountSet.Where(a => a.Id == accnt.Id).FirstOrDefault();
                Assert.Equal(cntc.Id, accnt.PrimaryContactId.Id);
            }
        }
Exemple #5
0
            public void an_event_should_not_be_created_for_tracked_field_with_no_changes()
            {
                // Arrange
                var context       = new XrmFakedContext();
                var pluginContext = context.GetDefaultPluginContext();

                var preImageEntity  = PreImageEntity;
                var postImageEntity = PreImageEntity;

                pluginContext.PreEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", preImageEntity));
                pluginContext.PostEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", postImageEntity));
                context.AddRelationship("opc_complaint_opc_events", new XrmFakedRelationship("opc_complaint_opc_events", "opc_complaint_opc_events", "opc_complaint", "opc_event"));
                pluginContext.InputParameters = new ParameterCollection {
                    { "Target", new EntityReference("opc_complaint", preImageEntity.Id) },
                };

                pluginContext.MessageName = PluginMessage.Update;

                // Act
                context.ExecutePluginWith <ChangeEventPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().RetrieveMultiple(new QueryExpression(opc_event.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(false)
                }).Entities.Count.Should().Be(0);
            }
Exemple #6
0
            public void two_events_should_be_created_for_two_tracked_changed_fields()
            {
                // Arrange
                var context       = new XrmFakedContext();
                var pluginContext = context.GetDefaultPluginContext();

                context.Initialize(new[] {
                    TestUser
                });

                var preImageEntity = new Entity("opc_complaint", Guid.NewGuid())
                {
                    Attributes = new AttributeCollection()
                    {
                        { "ownerid", new EntityReference("systemuser", Guid.NewGuid())
                          {
                              Name = "John Doe"
                          } },
                        { nameof(opc_complaint.opc_intakeofficer), new EntityReference("systemuser", Guid.NewGuid())
                          {
                              Name = "John Doe 2"
                          } }
                    }
                };

                var postImageEntity = new Entity("opc_complaint", Guid.NewGuid())
                {
                    Attributes = new AttributeCollection()
                    {
                        { "ownerid", new EntityReference("systemuser", Guid.NewGuid())
                          {
                              Name = "Johna Doey"
                          } },
                        { "opc_intakeofficer", new EntityReference("systemuser", Guid.NewGuid())
                          {
                              Name = "Johna Doey 2"
                          } }
                    }
                };

                pluginContext.PreEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", preImageEntity));
                pluginContext.PostEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", postImageEntity));
                pluginContext.InitiatingUserId = TestUser.Id;
                context.AddRelationship("opc_complaint_opc_events", new XrmFakedRelationship("opc_complaint_opc_events", "opc_complaint_opc_events", "opc_complaint", "opc_event"));
                pluginContext.InputParameters = new ParameterCollection {
                    { "Target", new EntityReference("opc_complaint", Guid.NewGuid()) },
                };

                pluginContext.MessageName = PluginMessage.Update;

                // Act
                context.ExecutePluginWith <ChangeEventPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().RetrieveMultiple(new QueryExpression(opc_event.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(false)
                }).Entities.Count.Should().Be(2);
            }
 public void When_execute_is_called_with_a_null_target_exception_is_thrown()
 {
     var context = new XrmFakedContext();
     var executor = new AssociateRequestExecutor();
     var req = new AssociateRequest() { Target = null, Relationship = new Relationship("fakeRelationship") };
     context.AddRelationship("fakeRelationship", new XrmFakedRelationship());
     Assert.Throws<Exception>(() => executor.Execute(req, context));
 }
Exemple #8
0
            public void owner_team_should_not_be_associated_to_users_who_are_member_through_another_AAD_team()
            {
                // Arrange
                var  context = new XrmFakedContext();
                var  pluginContext = context.GetDefaultPluginContext();
                Guid targetAADTeamGuid, startAADTeamGuid, userGuid1, userGuid2, targetOwnerTeamGuid;

                context.Initialize(new[] {
                    new Entity("team", targetOwnerTeamGuid = Guid.NewGuid()),
                    new Entity("team", targetAADTeamGuid   = Guid.NewGuid()),
                    new Entity("team", startAADTeamGuid    = Guid.NewGuid()),
                    new Entity("systemuser", userGuid1     = Guid.NewGuid()),
                    new Entity("systemuser", userGuid2     = Guid.NewGuid()),
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = targetAADTeamGuid, ["systemuserid"] = userGuid1
                    },
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = targetAADTeamGuid, ["systemuserid"] = userGuid2
                    },
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = targetOwnerTeamGuid, ["systemuserid"] = userGuid1
                    },
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = targetOwnerTeamGuid, ["systemuserid"] = userGuid2
                    },
                    new opc_teams_teams {
                        Id = Guid.NewGuid(), ["teamidone"] = targetOwnerTeamGuid, ["teamidtwo"] = startAADTeamGuid
                    }
                });
                context.AddRelationship("teammembership_association", new XrmFakedRelationship("teammembership", "teamid", "systemuserid", "team", "systemuser"));

                pluginContext.MessageName     = PluginMessage.Associate;
                pluginContext.InputParameters = new ParameterCollection {
                    { "Target", new EntityReference("team", targetOwnerTeamGuid) },
                    { "Relationship", new Relationship("opc_teams_teams_owneraadassociation") },
                    { "RelatedEntities", new EntityReferenceCollection(new [] { new EntityReference("team", targetAADTeamGuid) }) }
                };

                // Act
                context.ExecutePluginWith <OwnerTeamMemberShipPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().RetrieveMultiple(new QueryExpression("teammembership")
                {
                    Distinct  = false,
                    ColumnSet = new ColumnSet(false),
                    Criteria  =
                    {
                        Conditions =
                        {
                            new ConditionExpression("teamid",       ConditionOperator.In, targetOwnerTeamGuid),
                            new ConditionExpression("systemuserid", ConditionOperator.In, new [] { userGuid1,  userGuid2})
                        }
                    }
                }).Entities.Count.Should().Be(2);
            }
Exemple #9
0
        public void When_execute_is_called_with_a_null_target_exception_is_thrown()
        {
            var context  = new XrmFakedContext();
            var executor = new AssociateRequestExecutor();
            var req      = new AssociateRequest()
            {
                Target = null, Relationship = new Relationship("fakeRelationship")
            };

            context.AddRelationship("fakeRelationship", new XrmFakedRelationship());
            Assert.Throws <Exception>(() => executor.Execute(req, context));
        }
        public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();

            var relationship = new XrmFakedRelationship()
            {
                IntersectEntity    = "accountleads",
                Entity1Attribute   = "accountid",
                Entity2Attribute   = "leadid",
                Entity1LogicalName = "account",
                Entity2LogicalName = "lead"
            };

            context.AddRelationship("accountleads", relationship);

            var service = context.GetFakedOrganizationService();

            using (var ctx = new XrmServiceContext(service))
            {
                var account = new Account()
                {
                    Name = "Test account"
                };
                ctx.AddObject(account);

                var contact = new Lead()
                {
                    FirstName = "Jane", LastName = "Doe"
                };
                ctx.AddRelatedObject(account, new Relationship("accountleads"), contact);
                var result = ctx.SaveChanges();

                var resultaccount = ctx.CreateQuery <Account>()
                                    .ToList()
                                    .FirstOrDefault();

                Assert.NotNull(resultaccount);
                Assert.Equal("Test account", resultaccount.Name);

                var reaultlead = ctx.CreateQuery <Lead>()
                                 .ToList()
                                 .FirstOrDefault();

                Assert.NotNull(reaultlead);
                Assert.Equal("Jane", reaultlead.FirstName);
                Assert.Equal("Doe", reaultlead.LastName);

                var relationshipRecords = ctx.CreateQuery("accountleads")
                                          .ToList();
                Assert.NotEmpty(relationshipRecords);
            }
        }
        public void NoM2MData_ReturnsValidSchemaXML()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);

            fakedContext.Initialize(SupportMethods.Getm2mRelationshipTypeEntities());

            fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship
            {
                IntersectEntity    = "systemuserroles",
                Entity1LogicalName = "systemuser",
                Entity1Attribute   = "systemuserid",
                Entity2LogicalName = "role",
                Entity2Attribute   = "roleid"
            });

            var AssociateRequest = SupportMethods.Getm2mRelationshipTypeAssociateRequest();
            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            fakedService.Execute(AssociateRequest);

            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata = fakedContext.GetEntityMetadataByName(SupportMethods.UserLogicalName);

                entityMetadata.DisplayName = new Label(SupportMethods.UserDisplayName, 1033);
                entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "fullname");
                entityMetadata.Attributes.First(a => a.LogicalName == "systemuserid").SetSealedPropertyValue("DisplayName", new Label("User", 1033));
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("IntersectEntityName", "systemuserroles");
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("Entity2LogicalName", "role");
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("Entity2IntersectAttribute", "roleid");

                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData("<fetch><entity name='systemuser'><attribute name='systemuserid'/><link-entity name='systemuserroles' from='systemuserid' to='systemuserid' intersect='true'><link-entity name='role' from='roleid' to='roleid'/><attribute name='roleid'/></link-entity><filter><condition attribute='systemuserid' operator='eq' value='00e7b0b9-1ace-e711-a970-000d3a192315'/></filter></entity></fetch>");

            Assert.AreEqual(
                DataBuilder.BuildSchemaXML().InnerXml,
                "<entities />");
        }
        public void ReflexiveM2MRelationship_Schema()
        {
            XrmFakedContext fakedContext = SupportMethods.SetupPrimitiveFakedService(
                SupportMethods.AgentScriptActionLogicalName,
                SupportMethods.AgentScriptActionDisplayName,
                SupportMethods.Getm2mReflexiveRelationshipTypeEntities());

            fakedContext.AddRelationship("msdyusd_subactioncalls", new XrmFakedRelationship
            {
                IntersectEntity    = "msdyusd_subactioncalls",
                Entity1LogicalName = "msdyusd_agentscriptaction",
                Entity1Attribute   = "msdyusd_agentscriptactionidone",
                Entity2LogicalName = "msdyusd_agentscriptaction",
                Entity2Attribute   = "msdyusd_agentscriptactionidtwo"
            });

            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata = fakedContext.GetEntityMetadataByName(SupportMethods.AgentScriptActionLogicalName);

                entityMetadata.DisplayName = new Label(SupportMethods.AgentScriptActionDisplayName, 1033);
                entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "msdyusd_name");
                entityMetadata.Attributes.First(a => a.LogicalName == "msdyusd_agentscriptactionid").SetSealedPropertyValue("DisplayName", new Label("Agent Script Action", 1033));
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "msdyusd_subactioncalls").SetSealedPropertyValue("IntersectEntityName", "msdyusd_subactioncalls");
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "msdyusd_subactioncalls").SetSealedPropertyValue("Entity1LogicalName", "msdyusd_agentscriptaction");
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "msdyusd_subactioncalls").SetSealedPropertyValue("Entity2LogicalName", "msdyusd_agentscriptaction");
                entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "msdyusd_subactioncalls").SetSealedPropertyValue("Entity2IntersectAttribute", "msdyusd_agentscriptactionidtwo");

                var response = new RetrieveEntityResponse()
                {
                    Results = new ParameterCollection
                    {
                        { "EntityMetadata", entityMetadata }
                    }
                };
                return(response);
            });

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            SupportMethods.Getm2mReflexiveRelationshipTypeAssociateRequests().ToList <AssociateRequest>().ForEach(r => fakedService.Execute(r));


            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.Getm2mReflexiveRelationshipTypeFetch());

            Assert.AreEqual(DataBuilder.BuildSchemaXML().InnerXml, SupportMethods.Getm2mReflexiveRelationshipTypeExpectedSchema());
        }
        private static XrmFakedContext GenerateBaseContext()
        {
            var context = new XrmFakedContext();

            // configure the relationship
            context.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = PlaceholderTags.EntityLogicalName,
                Entity1LogicalName = Placeholder.EntityLogicalName,
                Entity1Attribute   = "placeholderid",
                Entity2LogicalName = Tag.EntityLogicalName,
                Entity2Attribute   = "tagid"
            });

            return(context);
        }
Exemple #14
0
            public void an_event_should_not_be_created_for_non_tracked_changed_field()
            {
                // Arrange
                var  context = new XrmFakedContext();
                var  pluginContext = context.GetDefaultPluginContext();
                Guid complaintId, preOwnerId, postOwnerId;

                var preImageEntity = new Entity("opc_complaint", complaintId = Guid.NewGuid())
                {
                    Attributes = new AttributeCollection()
                    {
                        { nameof(opc_complaint.opc_complainantrep), new EntityReference("Contact", preOwnerId = Guid.NewGuid())
                          {
                              Name = "John Doe"
                          } }
                    }
                };

                var postImageEntity = new Entity("opc_complaint", complaintId = Guid.NewGuid())
                {
                    Attributes = new AttributeCollection()
                    {
                        { nameof(opc_complaint.opc_complainantrep), new EntityReference("Contact", postOwnerId = Guid.NewGuid())
                          {
                              Name = "Johna Doey"
                          } }
                    }
                };

                pluginContext.PreEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", preImageEntity));
                pluginContext.PostEntityImages.Add(new KeyValuePair <string, Entity>("EntityImages", postImageEntity));
                context.AddRelationship("opc_complaint_opc_events", new XrmFakedRelationship("opc_complaint_opc_events", "opc_complaint_opc_events", "opc_complaint", "opc_event"));
                pluginContext.InputParameters = new ParameterCollection {
                    { "Target", new EntityReference("opc_complaint", complaintId) },
                };

                pluginContext.MessageName = PluginMessage.Update;

                // Act
                context.ExecutePluginWith <ChangeEventPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().RetrieveMultiple(new QueryExpression(Annotation.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(false)
                }).Entities.Count.Should().Be(0);
            }
Exemple #15
0
            public void owner_teams_should_be_disassociated_from_user()
            {
                // Arrange
                var  context = new XrmFakedContext();
                var  pluginContext = context.GetDefaultPluginContext();
                Guid targetAADTeamGuid, targetUserGuid, ownerTeamGuid;

                context.Initialize(new[] {
                    new Entity("systemuser", targetUserGuid = Guid.NewGuid()),
                    new Entity("queue", ownerTeamGuid       = Guid.NewGuid()),
                    new Entity("team", targetAADTeamGuid    = Guid.NewGuid()),
                    new opc_teams_teams {
                        Id = Guid.NewGuid(), ["teamidone"] = ownerTeamGuid, ["teamidtwo"] = targetAADTeamGuid
                    },
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = ownerTeamGuid, ["systemuserid"] = targetUserGuid
                    },
                    new TeamMembership {
                        Id = Guid.NewGuid(), ["teamid"] = targetAADTeamGuid, ["systemuserid"] = targetUserGuid
                    }
                });
                context.AddRelationship("teammembership_association", new XrmFakedRelationship("teammembership", "teamid", "systemuserid", "team", "systemuser"));

                pluginContext.MessageName     = PluginMessage.Disassociate;
                pluginContext.InputParameters = new ParameterCollection {
                    { "Target", new EntityReference("team", targetAADTeamGuid) },
                    { "Relationship", new Relationship("teammembership_association") },
                    { "RelatedEntities", new EntityReferenceCollection(new [] { new EntityReference("systemuser", targetUserGuid = Guid.NewGuid()) }) }
                };

                // Act
                context.ExecutePluginWith <OwnerTeamMemberShipPlugin>(pluginContext);

                // Assert
                context.GetOrganizationService().RetrieveMultiple(new QueryExpression("teammembership")
                {
                    ColumnSet = new ColumnSet(false),
                    Criteria  =
                    {
                        Conditions =
                        {
                            new ConditionExpression("systemuserid", ConditionOperator.In, targetUserGuid)
                        }
                    }
                }).Entities.Count.Should().Be(0);
            }
        public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();

            var relationship = new XrmFakedRelationship()
            {
                IntersectEntity = "accountleads",
                Entity1Attribute = "accountid",
                Entity2Attribute = "leadid",
                Entity1LogicalName = "account",
                Entity2LogicalName = "lead"
            };
            context.AddRelationship("accountleads", relationship);

            var service = context.GetFakedOrganizationService();

            using (var ctx = new XrmServiceContext(service))
            {
                var account = new Account() { Name = "Test account" };
                ctx.AddObject(account);

                var contact = new Lead() { FirstName = "Jane", LastName = "Doe" };
                ctx.AddRelatedObject(account, new Relationship("accountleads"), contact);
                var result = ctx.SaveChanges();

                var resultaccount = ctx.CreateQuery<Account>()
                                       .ToList()
                                       .FirstOrDefault();

                Assert.NotNull(resultaccount);
                Assert.Equal("Test account", resultaccount.Name);

                var reaultlead = ctx.CreateQuery<Lead>()
                                    .ToList()
                                    .FirstOrDefault();

                Assert.NotNull(reaultlead);
                Assert.Equal("Jane", reaultlead.FirstName);
                Assert.Equal("Doe", reaultlead.LastName);

                var relationshipRecords = ctx.CreateQuery("accountleads")
                                             .ToList();
                Assert.NotEmpty(relationshipRecords);
            }
        }
Exemple #17
0
        public void When_related_entities_and_relationship_are_used_child_entities_are_created()
        {
            var ctx     = new XrmFakedContext();
            var service = ctx.GetFakedOrganizationService();

            ctx.AddRelationship("order_details",
                                new XrmFakedRelationship()
            {
                Entity1LogicalName = SalesOrder.EntityLogicalName,  //Referenced
                Entity1Attribute   = "salesorderid",                //Pk
                Entity2LogicalName = SalesOrderDetail.EntityLogicalName,
                Entity2Attribute   = "salesorderid",                //Lookup attribute
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.OneToMany
            });


            var order = new SalesOrder();

            var orderItems = new EntityCollection(new List <Entity>()
            {
                new SalesOrderDetail(),
                new SalesOrderDetail()
            });

            // Add related order items so it can be created in one request
            order.RelatedEntities.Add(new Relationship
            {
                PrimaryEntityRole = EntityRole.Referenced,
                SchemaName        = "order_details"
            }, orderItems);

            var request = new CreateRequest
            {
                Target = order
            };

            var id = (service.Execute(request) as CreateResponse).id;
            var createdOrderDetails = ctx.CreateQuery <SalesOrderDetail>().ToList();

            Assert.Equal(createdOrderDetails.Count, 2);
            Assert.Equal(createdOrderDetails[0].SalesOrderId.Id, id);
            Assert.Equal(createdOrderDetails[1].SalesOrderId.Id, id);
        }
Exemple #18
0
        public void When_execute_is_called_with_a_non_existing_reference_exception_is_thrown()
        {
            var context  = new XrmFakedContext();
            var executor = new AssociateRequestExecutor();

            context.AddRelationship("fakeRelationship",
                                    new XrmFakedRelationship()
            {
                IntersectEntity    = "account_contact_intersect",
                Entity1LogicalName = Contact.EntityLogicalName,
                Entity1Attribute   = "contactid",
                Entity2LogicalName = Account.EntityLogicalName,
                Entity2Attribute   = "accountid"
            });

            var contact = new Entity("contact")
            {
                Id = Guid.NewGuid()
            };
            var account = new Entity("account")
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new List <Entity>()
            {
                contact
            });
            var req = new AssociateRequest()
            {
                Target          = contact.ToEntityReference(),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Account.EntityLogicalName, account.Id),
                },
                Relationship = new Relationship("fakeRelationship")
            };

            Assert.Throws <Exception>(() => executor.Execute(req, context));
        }
Exemple #19
0
        private static XrmFakedContext GetDisassosiateContext(Guid businessUnitId, Guid userId, Guid hotelId)
        {
            // role
            var baseRole = new Entity(Entities.Team, Guid.NewGuid());

            baseRole["name"]           = General.RoleTcIdBase;
            baseRole["businessunitid"] = businessUnitId;
            // team
            var team = new Entity(Entities.Team)
            {
                Id = Guid.NewGuid()
            };

            team[Attributes.Team.HotelTeam] = true;
            // hotel
            var hotel = new Entity(Entities.Hotel)
            {
                Id = hotelId
            };

            hotel[Attributes.Hotel.OwningTeam] = new EntityReference(Entities.Team, team.Id);
            // user
            var user = new Entity(Entities.User)
            {
                Id = userId
            };

            user["businessunit"] = businessUnitId;
            var context = new XrmFakedContext();

            context.Initialize(new List <Entity>()
            {
                baseRole, hotel, user, team
            });
            var relationship = new XrmFakedRelationship(Entities.Team, "teamid", "systemuserid", "team", "systemuser");

            context.AddRelationship(Relationships.TeamMembershipAssociation, relationship);
            return(context);
        }
        public void BasicDisassociateTestWithEnumerableRecords()
        {
            var context    = new XrmFakedContext();
            var orgService = context.GetOrganizationService();

            context.AddRelationship("account_primary_contact", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.OneToMany,
                Entity1LogicalName = "contact",
                Entity1Attribute   = "contactid",
                Entity2LogicalName = "account",
                Entity2Attribute   = "contactid"
            });

            context.Initialize(new List <Entity>()
            {
                TestAccount1,
                TestAccount1Duplicate
            });

            var contact = new Contact()
            {
                FirstName = "Jaroslaw",
                LastName  = "Czyz"
            };

            contact.Create(orgService);

            IEnumerable <Account> accountCollection = new List <Account>()
            {
                TestAccount1,
                TestAccount1Duplicate
            };

            contact.Associate(orgService, "account_primary_contact", accountCollection);

            Assert.Throws <FeatureRequestException>(() =>
                                                    contact.Disassociate(orgService, "account_primary_contact", accountCollection));
        }
        public void BasicAssociateTest()
        {
            var context    = new XrmFakedContext();
            var orgService = context.GetOrganizationService();

            context.AddRelationship("account_primary_contact", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.OneToMany,
                Entity1LogicalName = "contact",
                Entity1Attribute   = "contactid",
                Entity2LogicalName = "account",
                Entity2Attribute   = "contactid"
            });

            context.Initialize(new List <Entity>()
            {
                TestAccount1,
                TestAccount1Duplicate
            });

            var contact = new Contact()
            {
                FirstName = "Jaroslaw",
                LastName  = "Czyz"
            };

            contact.Create(orgService);

            var accountCollection = new EntityReferenceCollection()
            {
                TestAccount1.ToEntityReference(),
                TestAccount1Duplicate.ToEntityReference()
            };

            Assert.DoesNotThrow(() =>
                                contact.Associate(orgService, "account_primary_contact", accountCollection));
        }
Exemple #22
0
        public static void Should_Retrieve_A_Correct_Entity_With_N_To_N_Related_Records_And_Related_Record_Query_Criteria()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            fakedContext.Initialize(new Entity[] { account1, account2, account3, lead1, lead2, lead3 });
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead3.ToEntityReference(),
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead1.ToEntityReference(),
            });

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("subject"),
                            EntityName = Lead.EntityLogicalName,
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression("subject",   ConditionOperator.Equal, "Lead 3"),
                                    new ConditionExpression("statecode", ConditionOperator.Equal, 0)
                                }
                            }
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            Assert.NotNull(resultAccount.accountleads_association);
            Assert.Equal(1, resultAccount.accountleads_association.Count());
            Assert.Equal(lead3.Id, resultAccount.accountleads_association.First().Id);
        }
        public void When_execute_is_called_with_reverse_param_order()
        {
            var context = new XrmFakedContext();


            var userId  = Guid.NewGuid();
            var teamId  = Guid.NewGuid();
            var user2Id = Guid.NewGuid();

            context.Initialize(new List <Entity> {
                new SystemUser
                {
                    Id = userId
                },
                new SystemUser
                {
                    Id = user2Id
                },
                new Team
                {
                    Id = teamId
                },
                new Entity("teammembership")
                {
                    Id = Guid.NewGuid(),
                    ["systemuserid"] = userId,
                    ["teamid"]       = teamId
                },
                new Entity("teammembership")
                {
                    Id = Guid.NewGuid(),
                    ["systemuserid"] = teamId,
                    ["teamid"]       = userId
                },
                new Entity("teammembership")
                {
                    Id = Guid.NewGuid(),
                    ["systemuserid"] = user2Id,
                    ["teamid"]       = teamId
                },
                new Entity("teammembership")
                {
                    Id = Guid.NewGuid(),
                    ["systemuserid"] = teamId,
                    ["teamid"]       = user2Id
                }
            });

            context.AddRelationship("teammembership", new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.ManyToMany,
                IntersectEntity    = "teammembership",
                Entity1Attribute   = "systemuserid",
                Entity1LogicalName = "systemuser",
                Entity2Attribute   = "teamid",
                Entity2LogicalName = "team"
            });

            var orgSvc = context.GetFakedOrganizationService();

            orgSvc.Disassociate("team", teamId, new Relationship("teammembership"),
                                new EntityReferenceCollection(new List <EntityReference> {
                new EntityReference("systemuser", userId), new EntityReference("systemuser", user2Id)
            }));

            using (Crm.XrmServiceContext ctx = new XrmServiceContext(orgSvc))
            {
                var correctAssociation1 = (from tu in ctx.TeamMembershipSet
                                           where tu.TeamId == teamId &&
                                           tu.SystemUserId == user2Id
                                           select tu).ToList();
                Assert.False(correctAssociation1.Any());

                var correctAssociation = (from tu in ctx.TeamMembershipSet
                                          where tu.TeamId == teamId &&
                                          tu.SystemUserId == userId
                                          select tu).ToList();
                Assert.False(correctAssociation.Any());

                var wrongAssociation2 = (from tu in ctx.TeamMembershipSet
                                         where tu.TeamId == user2Id &&
                                         tu.SystemUserId == teamId
                                         select tu).ToList();
                Assert.Equal(1, wrongAssociation2.Count());

                var wrongAssociation = (from tu in ctx.TeamMembershipSet
                                        where tu.TeamId == userId &&
                                        tu.SystemUserId == teamId
                                        select tu).ToList();
                Assert.Equal(1, wrongAssociation.Count());
            }
        }
        public static void Should_Only_Find_Correct_Faked_N_To_N_Records()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var userId     = new Guid("11111111-7982-4276-A8FE-7CE05FABEAB4");
            var businessId = Guid.NewGuid();

            var testUser = new SystemUser
            {
                Id = userId
            };

            var testRole = new Role
            {
                Id             = new Guid("22222222-7982-4276-A8FE-7CE05FABEAB4"),
                Name           = "Test Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId)
            };

            var testUser2 = new SystemUser
            {
                Id = Guid.NewGuid()
            };

            var testRole2 = new Role
            {
                Id             = Guid.NewGuid(),
                Name           = "Test Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId)
            };

            fakedContext.Initialize(new Entity[] { testUser, testRole, testUser2, testRole2 });

            fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship
            {
                IntersectEntity    = "systemuserroles",
                Entity1LogicalName = SystemUser.EntityLogicalName,
                Entity1Attribute   = "systemuserid",
                Entity2LogicalName = Role.EntityLogicalName,
                Entity2Attribute   = "roleid"
            });

            var request = new AssociateRequest()
            {
                Target          = testUser.ToEntityReference(),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, testRole.Id),
                },
                Relationship = new Relationship("systemuserroles_association")
            };

            fakedService.Execute(request);

            var request2 = new AssociateRequest()
            {
                Target          = testUser2.ToEntityReference(),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, testRole2.Id),
                },
                Relationship = new Relationship("systemuserroles_association")
            };

            fakedService.Execute(request2);

            var query = new QueryExpression()
            {
                EntityName   = "role",
                ColumnSet    = new ColumnSet("name"),
                LinkEntities =
                {
                    new LinkEntity
                    {
                        LinkFromEntityName    = Role.EntityLogicalName,
                        LinkFromAttributeName = "roleid",
                        LinkToEntityName      = SystemUserRoles.EntityLogicalName,
                        LinkToAttributeName   = "roleid",
                        LinkCriteria          = new FilterExpression
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "systemuserid",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { userId }
                                }
                            }
                        }
                    }
                }
            };

            var result = fakedService.RetrieveMultiple(query);

            Assert.NotEmpty(result.Entities);
            Assert.Equal(1, result.Entities.Count);
        }
        public static void Should_Not_Fail_On_Conditions_In_Link_Entities()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var testEntity1 = new Entity("entity1")
            {
                Attributes = new AttributeCollection
                {
                    { "entity1attr", "test1" }
                }
            };
            var testEntity2 = new Entity("entity2")
            {
                Attributes = new AttributeCollection
                {
                    { "entity2attr", "test2" }
                }
            };

            testEntity1.Id = fakedService.Create(testEntity1);
            testEntity2.Id = fakedService.Create(testEntity2);

            var testRelation = new XrmFakedRelationship
            {
                IntersectEntity    = "TestIntersectEntity",
                Entity1LogicalName = "entity1",
                Entity1Attribute   = "entity1attr",
                Entity2LogicalName = "entity2",
                Entity2Attribute   = "entity2attr"
            };

            fakedContext.AddRelationship(testRelation.Entity2LogicalName, testRelation);
            fakedService.Associate(testEntity1.LogicalName, testEntity1.Id,
                                   new Relationship(testRelation.Entity2LogicalName),
                                   new EntityReferenceCollection {
                testEntity2.ToEntityReference()
            });

            var query = new QueryExpression
            {
                EntityName = "entity1",
                Criteria   = new FilterExpression {
                    FilterOperator = LogicalOperator.And
                },
                ColumnSet = new ColumnSet(true)
            };

            var link = new LinkEntity
            {
                JoinOperator          = JoinOperator.Natural,
                LinkFromEntityName    = "entity1",
                LinkFromAttributeName = "entity1attr",
                LinkToEntityName      = "entity2",
                LinkToAttributeName   = "entity2attr",
                LinkCriteria          = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions     =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "entity2attr",
                            Operator      = ConditionOperator.Equal,
                            Values        = { "test2" }
                        }
                    }
                }
            };

            query.LinkEntities.Add(link);

            var result = fakedService.RetrieveMultiple(query);

            Assert.NotEmpty(result.Entities);
            Assert.Equal(1, result.Entities.Count);
        }
        public static void Should_Not_Fail_On_Conditions_In_Link_Entities_Multiple()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetOrganizationService();

            fakedContext.AddRelationship("new_invoicepaymentmethod_invoicedetail",
                                         new XrmFakedRelationship("new_invoicepaymentmethod_invoicedetail",
                                                                  "invoicedetailid", "new_invoicepaymentmethodid",
                                                                  "invoicedetail",
                                                                  "new_invoicepaymentmethod"));

            Entity product01 = new Entity("product");

            product01.Id = Guid.NewGuid();
            product01.Attributes.Add("name", "Test Product");

            Entity invoicedetail01 = new Entity("invoicedetail");

            invoicedetail01.Id = Guid.NewGuid();
            invoicedetail01.Attributes.Add("invoicedetailid", invoicedetail01.Id);
            invoicedetail01.Attributes.Add("new_productid", new EntityReference("product", product01.Id));

            Entity pmr01 = new Entity("new_invoicepaymentmethod");

            pmr01.Id = Guid.NewGuid();
            pmr01.Attributes.Add("new_invoicepaymentmethodid", pmr01.Id);
            pmr01.Attributes.Add("new_name", "PMR0000000001");


            Entity invoicedetail02 = new Entity("invoicedetail");

            invoicedetail02.Id = Guid.NewGuid();
            invoicedetail02.Attributes.Add("invoicedetailid", invoicedetail02.Id);
            invoicedetail02.Attributes.Add("new_productid", new EntityReference("product", product01.Id));

            Entity pmr02 = new Entity("new_invoicepaymentmethod");

            pmr02.Id = Guid.NewGuid();
            pmr02.Attributes.Add("new_invoicepaymentmethodid", pmr02.Id);
            pmr02.Attributes.Add("new_name", "PMR0000000002");

            fakedService.Create(product01);

            fakedService.Create(invoicedetail01);
            fakedService.Create(invoicedetail02);
            fakedService.Create(pmr01);
            fakedService.Create(pmr02);

            fakedService.Associate("invoicedetail", invoicedetail01.Id, new Relationship("new_invoicepaymentmethod_invoicedetail"), new EntityReferenceCollection()
            {
                pmr01.ToEntityReference()
            });
            fakedService.Associate("invoicedetail", invoicedetail02.Id, new Relationship("new_invoicepaymentmethod_invoicedetail"), new EntityReferenceCollection()
            {
                pmr02.ToEntityReference()
            });


            EntityCollection invoiceDetails = new EntityCollection();

            QueryExpression query = new QueryExpression("invoicedetail");

            query.ColumnSet = new ColumnSet(true);
            LinkEntity link1 = new LinkEntity();

            link1.JoinOperator          = JoinOperator.Natural;
            link1.LinkFromEntityName    = "invoicedetail";
            link1.LinkFromAttributeName = "invoicedetailid";
            link1.LinkToEntityName      = "new_invoicepaymentmethod_invoicedetail";
            link1.LinkToAttributeName   = "invoicedetailid";

            LinkEntity link2 = new LinkEntity();

            link2.JoinOperator          = JoinOperator.Natural;
            link2.LinkFromEntityName    = "new_invoicepaymentmethod_invoicedetail";
            link2.LinkFromAttributeName = "new_invoicepaymentmethodid";
            link2.LinkToEntityName      = "new_invoicepaymentmethod";
            link2.LinkToAttributeName   = "new_invoicepaymentmethodid";
            link2.LinkCriteria          = new FilterExpression(LogicalOperator.And);

            ConditionExpression condition1 = new ConditionExpression("new_invoicepaymentmethodid", ConditionOperator.Equal, pmr02.Id);

            link2.LinkCriteria.Conditions.Add(condition1);
            link1.LinkEntities.Add(link2);
            query.LinkEntities.Add(link1);

            invoiceDetails = fakedService.RetrieveMultiple(query);

            Assert.Equal(1, invoiceDetails.Entities.Count);
            Assert.Equal(invoicedetail02.Id, invoiceDetails.Entities[0].Id);
        }
        public static void Should_Not_Fail_On_Conditions_In_Link_Entities()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var testEntity1 = new Entity("entity1")
            {
                Attributes = new AttributeCollection
                {
                    {"entity1attr", "test1" }
                }
            };
            var testEntity2 = new Entity("entity2")
            {
                Attributes = new AttributeCollection
                {
                    {"entity2attr", "test2" }
                }
            };

            testEntity1.Id = fakedService.Create(testEntity1);
            testEntity2.Id = fakedService.Create(testEntity2);

            var testRelation = new XrmFakedRelationship
            {
                IntersectEntity = "TestIntersectEntity",
                Entity1LogicalName = "entity1",
                Entity1Attribute = "entity1attr",
                Entity2LogicalName = "entity2",
                Entity2Attribute = "entity2attr"
            };
            fakedContext.AddRelationship(testRelation.Entity2LogicalName, testRelation);
            fakedService.Associate(testEntity1.LogicalName, testEntity1.Id, new Relationship(testRelation.Entity2LogicalName), new EntityReferenceCollection { testEntity2.ToEntityReference() });

            var query = new QueryExpression
            {
                EntityName = "entity1",
                Criteria = new FilterExpression { FilterOperator = LogicalOperator.And },
                ColumnSet = new ColumnSet(true)
            };

            var link = new LinkEntity
            {
                JoinOperator = JoinOperator.Natural,
                LinkFromEntityName = "entity1",
                LinkFromAttributeName = "entity1attr",
                LinkToEntityName = "entity2",
                LinkToAttributeName = "entity2attr",
                LinkCriteria = new FilterExpression
                {
                    FilterOperator = LogicalOperator.And,
                    Conditions = { new ConditionExpression { AttributeName = "entity2attr", Operator = ConditionOperator.Equal, Values = { "test2" } } }
                }
            };
            query.LinkEntities.Add(link);

            var result = fakedService.RetrieveMultiple(query);
            Assert.NotEmpty(result.Entities);
            Assert.Equal(1, result.Entities.Count);
        }
        public static void Should_Only_Find_Correct_Faked_N_To_N_Records()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var userId = new Guid("11111111-7982-4276-A8FE-7CE05FABEAB4");
            var businessId = Guid.NewGuid();

            var testUser = new SystemUser
            {
                Id = userId
            };

            var testRole = new Role
            {
                Id = new Guid("22222222-7982-4276-A8FE-7CE05FABEAB4"),
                Name = "Test Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId)
            };

            var testUser2 = new SystemUser
            {
                Id = Guid.NewGuid()
            };

            var testRole2 = new Role
            {
                Id = Guid.NewGuid(),
                Name = "Test Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, businessId)
            };

            fakedContext.Initialize(new Entity[] { testUser, testRole, testUser2, testRole2 });

            fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship
            {
                IntersectEntity = "systemuserroles",
                Entity1LogicalName = SystemUser.EntityLogicalName,
                Entity1Attribute = "systemuserid",
                Entity2LogicalName = Role.EntityLogicalName,
                Entity2Attribute = "roleid"
            });

            var request = new AssociateRequest()
            {
                Target = testUser.ToEntityReference(),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, testRole.Id),
                },
                Relationship = new Relationship("systemuserroles_association")
            };

            fakedService.Execute(request);

            var request2 = new AssociateRequest()
            {
                Target = testUser2.ToEntityReference(),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, testRole2.Id),
                },
                Relationship = new Relationship("systemuserroles_association")
            };

            fakedService.Execute(request2);

            var query = new QueryExpression()
            {
                EntityName = "role",
                ColumnSet = new ColumnSet("name"),
                LinkEntities = {
                    new LinkEntity {
                        LinkFromEntityName = Role.EntityLogicalName,
                        LinkFromAttributeName = "roleid",
                        LinkToEntityName = SystemUserRoles.EntityLogicalName,
                        LinkToAttributeName = "roleid",
                        LinkCriteria = new FilterExpression {
                            FilterOperator = LogicalOperator.And,
                            Conditions = {
                                new ConditionExpression {
                                    AttributeName = "systemuserid",
                                    Operator = ConditionOperator.Equal,
                                    Values = { userId }
                                }
                            }
                        }
                    }
                }
            };

            var result = fakedService.RetrieveMultiple(query);
            Assert.NotEmpty(result.Entities);
            Assert.Equal(1, result.Entities.Count);
        }
Exemple #29
0
        public static void Should_Retrieve_A_Correct_Entity_With_Multiple_Related_Record_Queries()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var accountLeadsRelationshipName = "accountleads_association";

            //account N:N leads
            fakedContext.AddRelationship(accountLeadsRelationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            //account 1:N contacts
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            fakedContext.Initialize(new Entity[] { account1, account2, lead1, lead2, lead3, contact1, contact2, contact3 });

            //associate account N:N leads
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(accountLeadsRelationshipName),
                                   new EntityReferenceCollection()
            {
                lead1.ToEntityReference(),
                lead3.ToEntityReference(),
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(accountLeadsRelationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference()
            });

            //build a request
            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(accountLeadsRelationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("subject"),
                            EntityName = Lead.EntityLogicalName
                        }
                    },
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName
                        }
                    }
                }
            };

            //execute request
            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            //check first relationship
            Assert.NotNull(resultAccount.accountleads_association);
            Assert.Equal(2, resultAccount.accountleads_association.Count());

            //and check another relationship
            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(2, resultAccount.contact_customer_accounts.Count());
        }
Exemple #30
0
        public static void Should_Retrieve_A_Correct_Entity_With_1_To_N_Related_Records_And_Related_Record_Query_Criteria()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new Entity[] { account1, account2, contact1, contact2, contact3 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName,
                            Criteria   = new FilterExpression
                            {
                                Conditions =
                                {
                                    new ConditionExpression("firstname", ConditionOperator.Equal, contact3.FirstName),
                                    new ConditionExpression("statecode", ConditionOperator.Equal, 0)
                                }
                            }
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);

            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(1, resultAccount.contact_customer_accounts.Count());
            Assert.Equal(contact3.Id, resultAccount.contact_customer_accounts.First().Id);
        }
Exemple #31
0
        public static void Should_Retrieve_A_Correct_Entity_With_1_To_N_Related_Records()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var contact1 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 1",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact2 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 2",
                ParentCustomerId = account1.ToEntityReference()
            };

            var contact3 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 3",
                ParentCustomerId = account2.ToEntityReference()
            };

            var contact4 = new Contact
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Contact 4",
                ParentCustomerId = account3.ToEntityReference()
            };

            var contact5 = new Contact
            {
                Id        = Guid.NewGuid(),
                FirstName = "Contact 5"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new Entity[] { account1, account2, account3, contact1, contact2, contact3, contact4, contact5 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: Contact.EntityLogicalName,
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: Account.EntityLogicalName,
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = Contact.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            Assert.Equal(account2.Id, resultAccount.Id);
            Assert.Equal(account2.Name, resultAccount.Name);

            //check relationship
            Assert.NotNull(resultAccount.contact_customer_accounts);
            Assert.Equal(2, resultAccount.contact_customer_accounts.Count());

            //check that contacts are retrieved
            var resultRelatedRecordsList = resultAccount.contact_customer_accounts;

            Assert.True(resultRelatedRecordsList.Any(x => x.Id == contact1.Id));
            Assert.True(resultRelatedRecordsList.Any(x => x.Id == contact3.Id));

            //check contacts (optional check)
            Assert.Equal(contact1.FirstName, resultRelatedRecordsList.First(x => x.Id == contact1.Id).FirstName);
            Assert.Equal(contact3.FirstName, resultRelatedRecordsList.First(x => x.Id == contact3.Id).FirstName);
        }
Exemple #32
0
        public static void Should_Retrieve_A_Correct_Entity_With_Relationship_Early_Bound()
        {
            var account1 = new Entity("account")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "name", "Account 1" }
                }
            };

            var account2 = new Entity("account")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "name", "Account 2" }
                }
            };

            var contact1 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 1"                  },
                    { "parentcustomerid", account2.ToEntityReference() }
                }
            };

            var contact2 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 2"                  },
                    { "parentcustomerid", account1.ToEntityReference() }
                }
            };

            var contact3 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname",        "Contact 3"                  },
                    { "parentcustomerid", account2.ToEntityReference() }
                }
            };

            var contact4 = new Entity("contact")
            {
                Id         = Guid.NewGuid(),
                Attributes =
                {
                    { "firstname", "Contact 4" }
                }
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            fakedContext.Initialize(new[] { account1, account2, contact1, contact2, contact3, contact4 });
            fakedContext.AddRelationship("contact_customer_accounts", new XrmFakedRelationship
                                         (
                                             entity1LogicalName: "contact",
                                             entity1Attribute: "parentcustomerid",
                                             entity2LogicalName: "account",
                                             entity2Attribute: "accountid"
                                         ));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship("contact_customer_accounts"),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("firstname"),
                            EntityName = "contact"
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity;

            Assert.Equal(account2.Id, resultAccount.Id);
            Assert.Equal(account2["name"], resultAccount["name"]);

            //check relationship
            Assert.NotNull(resultAccount.RelatedEntities.FirstOrDefault(x => x.Key.SchemaName == "contact_customer_accounts"));

            var relatedEntityCollection = resultAccount.RelatedEntities.FirstOrDefault(x => x.Key.SchemaName == "contact_customer_accounts");

            Assert.NotNull(relatedEntityCollection.Value);
            Assert.NotNull(relatedEntityCollection.Value.Entities);

            var relatedEntities = relatedEntityCollection.Value.Entities;

            Assert.Equal(2, relatedEntities.Count);

            Assert.True(relatedEntities.Any(x => x.Id == contact1.Id));
            Assert.True(relatedEntities.Any(x => x.Id == contact3.Id));

            //check contacts (optional check)
            Assert.Equal(contact1["firstname"], relatedEntities.First(x => x.Id == contact1.Id)["firstname"]);
            Assert.Equal(contact3["firstname"], relatedEntities.First(x => x.Id == contact3.Id)["firstname"]);
        }
Exemple #33
0
        public static void Should_Retrieve_A_Correct_Entity_With_N_To_N_Related_Records_Vice_Versa()
        {
            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var account3 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 3"
            };

            var lead1 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 1"
            };

            var lead2 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 2"
            };

            var lead3 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 3"
            };

            var lead4 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 4"
            };

            var lead5 = new Lead
            {
                Id      = Guid.NewGuid(),
                Subject = "Lead 5"
            };

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            fakedContext.Initialize(new Entity[] { account1, account2, account3, lead1, lead2, lead3, lead4, lead5 });
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead4.ToEntityReference(),
                lead5.ToEntityReference()
            });

            fakedService.Associate(Account.EntityLogicalName, account1.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection()
            {
                lead2.ToEntityReference(),
                lead3.ToEntityReference()
            });

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("subject"),
                Target               = lead2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            ColumnSet  = new ColumnSet("name"),
                            EntityName = Account.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultLead = result.Entity.ToEntity <Lead>();

            Assert.Equal(lead2.Id, lead2.Id);
            Assert.Equal(lead2.Subject, lead2.Subject);

            //check relationship
            Assert.NotNull(resultLead.accountleads_association);
            Assert.Equal(2, resultLead.accountleads_association.Count());

            //check that accounts are retrieved
            var resultRelatedRecordsList = resultLead.accountleads_association;

            Assert.True(resultRelatedRecordsList.Any(x => x.Id == account2.Id));
            Assert.True(resultRelatedRecordsList.Any(x => x.Id == account1.Id));

            //check accounts (optional check)
            Assert.Equal(account2.Name, resultRelatedRecordsList.First(x => x.Id == account2.Id).Name);
            Assert.Equal(account1.Name, resultRelatedRecordsList.First(x => x.Id == account1.Id).Name);
        }
Exemple #34
0
        public static void Should_Retrieve_All_Related_Records()
        {
            //related entities should all be returned
            //even when PageInfo is set

            var account1 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 1"
            };

            var account2 = new Account
            {
                Id   = Guid.NewGuid(),
                Name = "Account 2"
            };

            var leads = new List <Lead>();

            for (int i = 0; i < 50; i++)
            {
                leads.Add(new Lead {
                    Id = Guid.NewGuid()
                });
            }

            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var relationshipName = "accountleads_association";

            fakedContext.AddRelationship(relationshipName, new XrmFakedRelationship
            {
                IntersectEntity    = "accountleads",
                Entity1LogicalName = Account.EntityLogicalName,
                Entity1Attribute   = "accountid",
                Entity2LogicalName = Lead.EntityLogicalName,
                Entity2Attribute   = "leadid"
            });

            var initData = new List <Entity>();

            initData.AddRange(new Entity[] { account1, account2 });
            initData.AddRange(leads);

            fakedContext.Initialize(initData);
            fakedService.Associate(Account.EntityLogicalName, account2.Id, new Relationship(relationshipName),
                                   new EntityReferenceCollection(leads.Select(x => x.ToEntityReference()).ToList()));

            var request = new RetrieveRequest
            {
                ColumnSet            = new ColumnSet("name"),
                Target               = account2.ToEntityReference(),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    {
                        new Relationship(relationshipName),
                        new QueryExpression
                        {
                            PageInfo = new PagingInfo {
                                Count = 20, PageNumber = 1
                            },
                            ColumnSet  = new ColumnSet(false),
                            EntityName = Lead.EntityLogicalName
                        }
                    }
                }
            };

            var result = (RetrieveResponse)fakedService.Execute(request);

            Assert.NotNull(result.Entity);

            //check account
            var resultAccount = result.Entity.ToEntity <Account>();

            //check relationship
            Assert.NotNull(resultAccount.accountleads_association);
            Assert.Equal(50, resultAccount.accountleads_association.Count());
        }