Example #1
0
        private static IClientSideOrganizationService GetLocalCrmDatabaseOrganizationService(string organizationName, Guid impersonationUserId)
        {
            // Create a unique Database for each Unit Test by looking up the first method in the stack trace that has a TestMethodAttribute,
            // and using it's method handle, combined with the OrganizationName, as a unqiue Key
            var    method      = GetUnitTestMethod() ?? MethodBase.GetCurrentMethod();
            string databaseKey = String.Format("UnitTest {0}:{1}:{2}", method.Name, organizationName, method.MethodHandle);

            var info = LocalCrmDatabaseInfo.Create(TestSettings.EarlyBound.Assembly, TestSettings.EarlyBound.Namespace, databaseKey, impersonationUserId);

            var service = new LocalCrmDatabaseOrganizationService(info);

            // Create BU and SystemUser for currently executing user
            var bu = new Entity(BusinessUnit.EntityLogicalName)
            {
                [BusinessUnit.Fields.Name] = "Currently Executing BusinessUnit"
            };

            bu.Id = service.Create(bu);

            var id = service.Create(new Entity(SystemUser.EntityLogicalName)
            {
                [SystemUser.Fields.FirstName]      = Environment.UserDomainName.Split('/').First(),
                [SystemUser.Fields.LastName]       = Environment.UserName,
                [SystemUser.Fields.BusinessUnitId] = bu.ToEntityReference(),
            }.ToSdkEntity());

            info = LocalCrmDatabaseInfo.Create(TestSettings.EarlyBound.Assembly, TestSettings.EarlyBound.Namespace, databaseKey, id, impersonationUserId, bu.Id);

            return(new LocalCrmDatabaseOrganizationService(info));
        }
Example #2
0
        public void LocalCrmTests_OwningBuPopulated()
        {
            var id      = Guid.NewGuid();
            var info    = LocalCrmDatabaseInfo.Create <CrmContext>(userId: id, userBusinessUnit: Guid.NewGuid());
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(info);
            var buId    = service.Create(new BusinessUnit());
            var userId  = service.Create(new SystemUser
            {
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, buId)
            });
            var user = service.GetEntity <SystemUser>(userId);

            Assert.AreEqual(user.BusinessUnitId.Id, buId);

            var accountId = service.Create(new Account
            {
                OwnerId = new EntityReference(SystemUser.EntityLogicalName, userId)
            });

            // Test Create BU Logic
            var account = service.GetEntity <Account>(accountId);

            Assert.IsNotNull(account.OwningBusinessUnit);
            Assert.AreEqual(buId, account.OwningBusinessUnit.Id);

            // Test Update BU Logic
            service.Update(new Account
            {
                Id      = accountId,
                OwnerId = new EntityReference(SystemUser.EntityLogicalName, id)
            });
            account = service.GetEntity <Account>(accountId);
            Assert.IsNotNull(account.OwningBusinessUnit);
            Assert.AreNotEqual(buId, account.OwningBusinessUnit.Id);
        }
Example #3
0
        public void LocalCrmTests_Crud_ColumnSetLookups()
        {
            var          dbInfo    = LocalCrmDatabaseInfo.Create <CrmContext>();
            var          service   = new LocalCrmDatabaseOrganizationService(dbInfo);
            const string firstName = "Joe";
            const string lastName  = "Plumber";
            var          contact   = new Contact {
                FirstName = firstName, LastName = lastName
            };

            contact.Id = service.Create(contact);
            var cs = new ColumnSet("firstname");

            Assert.AreEqual(firstName, service.GetEntity <Contact>(contact.Id, cs).FirstName, "Failed to retrieve first name correctly");
            Assert.IsNull(service.GetEntity <Contact>(contact.Id, cs).LastName, "Last name was not requested, but was returned");
            Assert.AreEqual(firstName + " " + lastName, service.GetEntity <Contact>(contact.Id).FullName, "Full Name not populated correctly");

            // Test L, F M format
            dbInfo = LocalCrmDatabaseInfo.Create <CrmContext>(new LocalCrmDatabaseOptionalSettings
            {
                DatabaseName   = nameof(LocalCrmTests_Crud_ColumnSetLookups),
                FullNameFormat = "L, F M"
            });
            service = new LocalCrmDatabaseOrganizationService(dbInfo);
            contact = new Contact {
                FirstName = firstName, LastName = lastName
            };
            contact.Id = service.Create(contact);
            Assert.AreEqual($"{lastName}, {firstName}", service.GetEntity <Contact>(contact.Id).FullName, "Full Name not populated correctly");
        }
Example #4
0
        private static IOrganizationService GetService(bool createUnique = true, Guid?businessUnitId = null)
        {
            var info = createUnique
                ? LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString(), userBusinessUnit: businessUnitId)
                : LocalCrmDatabaseInfo.Create <CrmContext>(userBusinessUnit: businessUnitId);

            return(new LocalCrmDatabaseOrganizationService(info));
        }
Example #5
0
        private void SetupMock()
        {
            var serviceProviderMock = new Mock <IServiceProvider>();

            _tracingMock = new Mock <ITracingService>();

            //Organisation service
            _organizationServiceFake = new LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo.Create <OrganisationServiceContext>());
            var accountGuid = _organizationServiceFake.Create(new Account()
            {
                Name = "Packt Test"
            });

            _email1Guid = _organizationServiceFake.Create(new Email()
            {
                Subject = "Mock 1", RegardingObjectId = new EntityReference(Account.EntityLogicalName, accountGuid)
            });
            _email2Guid = _organizationServiceFake.Create(new Email()
            {
                Subject = "Mock 2", RegardingObjectId = new EntityReference(Account.EntityLogicalName, accountGuid)
            });
            _email3Guid = _organizationServiceFake.Create(new Email()
            {
                Subject = string.Empty, RegardingObjectId = new EntityReference(Account.EntityLogicalName, accountGuid)
            });


            //Plugin Context
            var pluginContextMock = new Mock <IPluginExecutionContext>();
            //pluginContextMock.Setup(c => c.UserId).Returns(new Guid());

            //Target InputParameter for plugin context
            var parameterCollection = new ParameterCollection();

            parameterCollection.Add("Target", new Account()
            {
                Id = accountGuid
            });
            pluginContextMock.Setup(c => c.InputParameters).Returns(parameterCollection);

            //Factory
            var organisationServicefactoryMock = new Mock <IOrganizationServiceFactory>();

            organisationServicefactoryMock.Setup(f => f.CreateOrganizationService(It.IsAny <Guid>())).Returns(_organizationServiceFake);

            //Set up provider mothods
            serviceProviderMock.Setup(sp => sp.GetService(typeof(ITracingService))).Returns(_tracingMock.Object);
            serviceProviderMock.Setup(sp => sp.GetService(typeof(IPluginExecutionContext))).Returns(pluginContextMock.Object);
            serviceProviderMock.Setup(sp => sp.GetService(typeof(IOrganizationServiceFactory))).Returns(organisationServicefactoryMock.Object);

            _serviceProvider = serviceProviderMock.Object;
        }
Example #6
0
        public void FilteringByMismatchedAttribute_Should_PerformFilter()
        {
            var info    = LocalCrmDatabaseInfo.Create <CrmContext>("FakeEntities");
            var service = new LocalCrmDatabaseOrganizationService(info);
            var fake    = new FakeEntity {
                FakeEntity1 = "Fake"
            };

            service.Create(fake);
            var dbFake = service.GetFirst <FakeEntity>("fakeentity", fake.FakeEntity1);

            Assert.AreEqual(dbFake.FakeEntity1, fake.FakeEntity1);
        }
Example #7
0
        public void LocalCrmTests_OwnerPopulated()
        {
            var id        = Guid.NewGuid();
            var info      = LocalCrmDatabaseInfo.Create <CrmContext>(userId: id);
            var service   = LocalCrmDatabaseOrganizationService.CreateOrganizationService(info);
            var accountId = service.Create(new Account());

            var account = service.GetEntity <Account>(accountId);

            // Retrieve
            Assert.IsNotNull(account.OwnerId);
            Assert.AreEqual(id, account.OwnerId.Id);
        }
        public void OrganizationServiceBuilder_WithEntityNameDefaulted_Name_Should_BeDefaulted()
        {
            //
            // Arrange
            //
            const string notExistsEntityLogicalName = "notexists";
            const string customEntityLogicalName    = "custom_entity";
            var          entities = new List <Entity>();

            IOrganizationService service =
                LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service = new OrganizationServiceBuilder(service)
                      .WithFakeCreate((s, e) =>
            {
                // Don't create fake entities
                if (e.LogicalName == notExistsEntityLogicalName)
                {
                    entities.Add(e);
                    return(Guid.NewGuid());
                }
                if (e.LogicalName == customEntityLogicalName)
                {
                    entities.Add(e);
                    return(Guid.NewGuid());
                }

                return(s.Create(e));
            })
                      .WithEntityNameDefaulted((e, info) => GetName(e.LogicalName, info.AttributeName))
                      .Build();


            //
            // Act
            //
            service.Create(new Entity(notExistsEntityLogicalName));
            service.Create(new Entity(customEntityLogicalName));
            service.Create(new Contact());
            service.Create(new Account());


            //
            // Assert
            //
            Assert.AreEqual(0, entities.Single(e => e.LogicalName == notExistsEntityLogicalName).Attributes.Count);
            Assert.AreEqual(GetName(customEntityLogicalName, "custom_name"), entities.Single(e => e.LogicalName == customEntityLogicalName)["custom_name"]);
            Assert.AreEqual(GetName(Contact.EntityLogicalName, " " + Contact.Fields.FullName), service.GetFirst <Contact>().FullName);
            Assert.AreEqual(GetName(Account.EntityLogicalName, Account.Fields.Name), service.GetFirst <Account>().Name);
        }
Example #9
0
        public void MakeNameMatchCase_NameIsMcdonald_Should_UpdateToMcDonald()
        {
            //
            // Arrange
            //
            var service = new LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>());
            var id      = service.Create(new Contact {
                LastName = "Mcdonald"
            });

            //
            // Act
            //
            MakeNameMatchCase(service, "McDonald");

            //
            // Assert
            //
            Assert.AreEqual("McDonald", service.GetEntity <Contact>(id).LastName);
        }
        public void CrmEnvironmentBuilder_Create_ConnectionAssociation_Should_CreateAssociationBeforeConnection()
        {
            var to          = new Id <ConnectionRole>("D588F8F5-9276-471E-9A73-C62217C29FD1");
            var from        = new Id <ConnectionRole>("29E71A5B-692D-4777-846D-FD1687D7DDB7");
            var association = new Id <ConnectionRoleAssociation>("C1B93E89-F070-4FE7-81B4-94BA123222CA");
            var connection  = new Id <Connection>("AC56E429-452F-49F5-A463-894E8CA8E17C");

            connection.Inject(new Connection
            {
                Record1RoleId = to,
                Record2RoleId = from
            });
            association.Inject(new ConnectionRoleAssociation
            {
                ConnectionRoleId           = to,
                AssociatedConnectionRoleId = from
            });
            var service         = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var containsFailure = false;

            try
            {
                new CrmEnvironmentBuilder()
                .WithEntities(to, from, connection)
                .Create(service);
            }
            catch (Exception ex)
            {
                containsFailure = ex.ToString().Contains("The connection roles are not related");
            }
            Assert.IsTrue(containsFailure, "CRM does not allow connection roles to be used on a connection without being associated.");
            service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            new CrmEnvironmentBuilder()
            .WithEntities(to, from, association, connection)
            .Create(service);
        }
 public void Initialize()
 {
     Trace   = new FakeTraceService(new DebugLogger());
     Service = new ExtendedOrganizationService(new LocalCrmDatabaseOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>()), Trace);
 }
Example #12
0
 /// <summary>
 /// Returns a local Crm Database Info from the TestSettings
 /// </summary>
 /// <param name="databaseKey">Key to Use</param>
 /// <param name="impersonationUserId">Impersonation User</param>
 /// <returns></returns>
 public static LocalCrmDatabaseInfo GetConfiguredLocalDatabaseInfo(string databaseKey, Guid impersonationUserId)
 {
     return(LocalCrmDatabaseInfo.Create(TestSettings.EarlyBound.Assembly, TestSettings.EarlyBound.Namespace, databaseKey, Guid.NewGuid(), impersonationUserId, Guid.NewGuid()));
 }
        public void CrmEnvironmentBuilder_WithChildEntities_ContactAndAccountAdded_Should_AddedViaCustomerId()
        {
            //
            // Arrange
            //
            var service         = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var account         = new Id <Account>(Guid.NewGuid());
            var contact         = new Id <Contact>(Guid.NewGuid());
            var accountIncident = new Id <Incident>(Guid.NewGuid());
            var contactIncident = new Id <Incident>(Guid.NewGuid());

            // The Account and Incident will be added as Account first, and Incident second.
            // The Lead will force an reorder and the Account incident would normally get placed after the Incident
            var builder = new DLaBCrmEnvironmentBuilder()
                          .WithChildEntities(contact, contactIncident)
                          .WithChildEntities(account, accountIncident);


            //
            // Act
            //
            builder.Create(service);


            //
            // Assert
            //

            AssertCrm.Exists(service, account);
            AssertCrm.Exists(service, accountIncident);
            AssertCrm.Exists(service, contact);
            AssertCrm.Exists(service, contactIncident);
        }
        public void CrmEnvironmentBuilder_Create_WithSelfReferencingEntity_Should_CreateThenUpdate()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var id      = Guid.NewGuid();
            var account = new Account
            {
                Id = id,
                ParentAccountId = new EntityReference(Account.EntityLogicalName, id)
            };

            //
            // Act
            //
            new DLaBCrmEnvironmentBuilder().WithEntities(account).Create(service);

            //
            // Assert
            //

            AssertCrm.Exists(service, account);
        }
        public void CrmEnvironmentBuilder_Create_WithCyclicReferencingEntities_Should_CreateThenUpdate()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            CyclicIds.Account.Entity = new Account
            {
                Id = CyclicIds.Account.EntityId,
                ParentAccountId   = CyclicIds.Account,
                PrimaryContactId  = CyclicIds.Contact,
                OriginatingLeadId = CyclicIds.Lead
            };

            CyclicIds.Contact.Entity = new Contact
            {
                Id = CyclicIds.Contact.EntityId,
                ParentCustomerId  = CyclicIds.Account,
                OriginatingLeadId = CyclicIds.Lead
            };

            CyclicIds.Lead.Entity = new Lead
            {
                Id              = CyclicIds.Lead.EntityId,
                CustomerId      = CyclicIds.Account,
                ParentAccountId = CyclicIds.Account,
                ParentContactId = CyclicIds.Contact
            };


            //
            // Act
            //
            new DLaBCrmEnvironmentBuilder().WithEntities <CyclicIds>().Create(service);

            //
            // Assert
            //
            var account = service.GetEntity(CyclicIds.Account);
            var contact = service.GetEntity(CyclicIds.Contact);
            var lead    = service.GetEntity(CyclicIds.Lead);

            Assert.AreEqual(account.ParentAccountId.Id, CyclicIds.Account.EntityId);
            Assert.AreEqual(account.PrimaryContactId.Id, CyclicIds.Contact.EntityId);
            Assert.AreEqual(account.OriginatingLeadId.Id, CyclicIds.Lead.EntityId);
            Assert.AreEqual(contact.ParentCustomerId.Id, CyclicIds.Account.EntityId);
            Assert.AreEqual(contact.OriginatingLeadId.Id, CyclicIds.Lead.EntityId);
            Assert.AreEqual(lead.CustomerId.Id, CyclicIds.Account.EntityId);
            Assert.AreEqual(lead.ParentAccountId.Id, CyclicIds.Account.EntityId);
            Assert.AreEqual(lead.ParentContactId.Id, CyclicIds.Contact.EntityId);
        }
        public void OrganizationServiceBuilder_WithFakeRetrieveMultipleForEntity_FakedRetrieves_Should_BeFaked()
        {
            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var accounts = new List <Account> {
                GetFakedAccount()
            };

            AssertAccountNotQueried(new OrganizationServiceBuilder(service).WithFakeRetrieveMultipleForEntity(Account.EntityLogicalName, new EntityCollection(accounts.Cast <Entity>().ToArray())).Build());
            AssertAccountNotQueried(new OrganizationServiceBuilder(service).WithFakeRetrieveMultipleForEntity(accounts).Build());
            AssertAccountNotQueried(new OrganizationServiceBuilder(service).WithFakeRetrieveMultipleForEntity(accounts.First()).Build());
        }
        public void OrganizationServiceBuilder_WithFakeRetrieve_FakedRetrieves_Should_BeFaked()
        {
            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var id = service.Create(new Account());

            service = new OrganizationServiceBuilder(service).WithFakeRetrieve(new Account {
                Name = "TEST"
            }).Build();
            var account = service.GetEntity <Account>(id);

            Assert.AreEqual("TEST", account.Name);
            Assert.AreEqual(Guid.Empty, account.Id);

            service = new OrganizationServiceBuilder(service).WithFakeRetrieve((s, n, i, cs) => i == id, new Account {
                Name = "TEST2"
            }).Build();
            account = service.GetEntity <Account>(id);
            Assert.AreEqual("TEST2", account.Name);
            Assert.AreEqual(Guid.Empty, account.Id);
        }
        public void OrganizationServiceBuilder_WithFakeAction_FakedBookingStatusRequest_Should_BeFaked()
        {
            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service = new OrganizationServiceBuilder(service)
                      .WithFakeAction(new msdyn_UpdateBookingsStatusResponse
            {
                BookingResult = "Success"
            }).Build();

            var response = (msdyn_UpdateBookingsStatusResponse)service.Execute(new msdyn_UpdateBookingsStatusRequest());

            Assert.AreEqual("Success", response.BookingResult);
        }
        public void CrmEnvironmentBuilder_Create_WithMultipleChildEntities_Should_CreateEntities()
        {
            //
            // Arrange
            //
            var account     = new Id <Account>("2b9631fd-c402-490d-8276-0a0e0ff3ba2f");
            var contact     = new Id <Contact>("2b9631fd-c402-490d-8276-0a0e0ff3ba2e");
            var lead        = new Id <Lead>("2b9631fd-c402-490d-8276-0a0e0ff3ba2d");
            var opportunity = new Id <Opportunity>("2b9631fd-c402-490d-8276-0a0e0ff3ba2c");

            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            //
            // Act
            //
            new CrmEnvironmentBuilder()
            .WithChildEntities(lead, opportunity)
            .WithChildEntities(lead, contact)
            .WithChildEntities(account, contact)
            .Create(service);

            //
            // Assert
            //
            AssertCrm.Exists(service, lead);
            AssertCrm.Exists(service, contact);
            AssertCrm.Exists(service, account);
            AssertCrm.Exists(service, opportunity);
        }
        public void CrmEnvironmentBuilder_Create_WithMyOtherBuilder_Should_UseBuilder()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var id      = new Id <Lead>(Guid.NewGuid());
            var email   = "*****@*****.**";

            //
            // Act
            //
            new DLaBCrmEnvironmentBuilder().
            WithBuilder <MyOtherBuilder>(id, b => b.WithEmail(email)).Create(service);

            //
            // Assert
            //
            var lead = service.GetEntity(id);

            Assert.AreEqual(email, lead.EMailAddress1);
        }
        public void CrmEnvironmentBuilder_Create_WithBuilder_Should_UseBuilder()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var id      = new Id <Lead>(Guid.NewGuid());
            var country = "Kerbal";

            //
            // Act
            //
            new DLaBCrmEnvironmentBuilder().
            WithBuilder <MyLeadBuilder>(id, b =>
                                        b.WithAddress1()
                                        .WithAttributeValue(Lead.Fields.Address1_Country, Guid.NewGuid().ToString())
                                        .WithPostCreateAttributeValue(Lead.Fields.Address1_Country, country)).Create(service);

            //
            // Assert
            //
            var lead = service.GetEntity(id);

            Assert.IsNotNull(lead.Address1_City);
            Assert.IsNotNull(lead.Address1_Line1);
            Assert.IsNotNull(lead.Address1_PostalCode);
            Assert.IsNotNull(lead.Address1_StateOrProvince);
            Assert.AreEqual(country, lead.Address1_Country);
            Assert.IsNull(lead.Address2_City);
        }
Example #22
0
        public void LocalCrmTests_Crud_NestedJoins()
        {
            TestInitializer.InitializeTestSettings();
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            var user1 = new Id <SystemUser>(Guid.NewGuid())
            {
                Entity = { FirstName = "Stan", }
            };
            var user2 = new Id <SystemUser>(Guid.NewGuid())
            {
                Entity = { FirstName = "Steve" }
            };
            var account = new Id <Account>(Guid.NewGuid())
            {
                Entity = { Name = "Marvel Comics" }
            };
            var contact1 = new Id <Contact>(Guid.NewGuid())
            {
                Entity = { FirstName = "Bruce", CreatedOnBehalfBy = user1, ModifiedOnBehalfBy = user2 }
            };
            var contact2 = new Id <Contact>(Guid.NewGuid())
            {
                Entity = { FirstName = "Peter", CreatedOnBehalfBy = user2, ModifiedOnBehalfBy = user1 }
            };

            var builder = new DLaBCrmEnvironmentBuilder().
                          WithChildEntities(account, contact1, contact2).
                          WithEntities(user1, user2);

            builder.Create(service);

            var temp = service.GetEntity(contact1);

            Assert.AreEqual(account.EntityReference, temp.ParentCustomerId);
            Assert.AreEqual(user1.EntityReference, temp.CreatedOnBehalfBy);
            Assert.AreEqual(user2.EntityReference, temp.ModifiedOnBehalfBy);
            temp = service.GetEntity(contact2);
            Assert.AreEqual(account.EntityReference, temp.ParentCustomerId);
            Assert.AreEqual(user1.EntityReference, temp.ModifiedOnBehalfBy);
            Assert.AreEqual(user2.EntityReference, temp.CreatedOnBehalfBy);

            var qe           = QueryExpressionFactory.Create <Account>(a => new { a.Name });
            var contactLink  = qe.AddLink <Contact>(Account.Fields.Id, Contact.Fields.ParentCustomerId, c => new { c.FirstName, c.Id });
            var createdLink  = contactLink.AddLink <SystemUser>(Contact.Fields.CreatedOnBehalfBy, SystemUser.Fields.Id, u => new { u.FirstName, u.Id });
            var modifiedLink = contactLink.AddLink <SystemUser>(Contact.Fields.ModifiedOnBehalfBy, SystemUser.Fields.Id, u => new { u.FirstName, u.Id });

            contactLink.EntityAlias  = "ContactLink";
            createdLink.EntityAlias  = "CreatedLink";
            modifiedLink.EntityAlias = "ModifiedLink";
            var results = service.RetrieveMultiple(qe);

            Assert.AreEqual(2, results.Entities.Count);
            foreach (var entity in results.Entities)
            {
                Assert.IsTrue(entity.Attributes.ContainsKey("CreatedLink.firstname"));
                Assert.IsTrue(entity.Attributes.ContainsKey("ModifiedLink.firstname"));
            }
        }
Example #23
0
        public void LocalCrmTests_Crud_ConnectionConstraints()
        {
            var to         = new Id <Contact>("458DB1CB-12F8-40FD-BCEF-DCDACAEB10D8");
            var toRole     = new Id <ConnectionRole>("D588F8F5-9276-471E-9A73-C62217C29FD1");
            var fromRole   = new Id <ConnectionRole>("29E71A5B-692D-4777-846D-FD1687D7DDB7");
            var connection = new Id <Connection>("AC56E429-452F-49F5-A463-894E8CA8E17C");

            connection.Inject(new Connection
            {
                Record1Id     = to,
                Record1RoleId = toRole
            });
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service.Create(to);
            service.Create(toRole);
            service.Create(fromRole);
            var containsFailure = false;

            try
            {
                service.Create(connection);
            }
            catch (Exception ex)
            {
                containsFailure = ex.ToString().Contains("You must provide a name or select a role for both sides of this connection.");
                if (!containsFailure)
                {
                    throw;
                }
            }

            Assert.IsTrue(containsFailure, "The Create should have failed with a You must provide a name or select a role for both sides of this connection., message.");
            connection.Entity.Record2RoleId = fromRole;
            containsFailure = false;

            try
            {
                service.Create(connection);
            }
            catch (Exception ex)
            {
                containsFailure = ex.ToString().Contains("The connection roles are not related");
                if (!containsFailure)
                {
                    throw;
                }
            }

            Assert.IsTrue(containsFailure, "The Create should have failed with a The connection roles are not related, message.");

            service.Associate(toRole, toRole, new Relationship("connectionroleassociation_association"), new EntityReferenceCollection(new List <EntityReference>
            {
                fromRole.EntityReference
            }));
            service.Create(connection);
        }
        public void CrmEnvironmentBuilder_Create_WithBuilderSelfReferencingEntity_Should_CreateThenUpdate()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var id      = new Id <Lead>(Guid.NewGuid());

            //
            // Act
            //
            new DLaBCrmEnvironmentBuilder().
            WithBuilder <MyLeadBuilder>(id, b => b.WithAttributeValue(Lead.Fields.MasterId, id.EntityReference)).
            Create(service);

            //
            // Assert
            //

            AssertCrm.Exists(service, id);
            var lead = service.GetEntity(id);

            Assert.AreEqual(lead.MasterId, id.EntityReference);
        }
        public void OrganizationServiceBuilder_WithFakeAction_FakedConditionalBookingStatusRequest_Should_BeFaked()
        {
            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service = new OrganizationServiceBuilder(service)
                      .WithFakeAction <msdyn_UpdateBookingsStatusRequest, msdyn_UpdateBookingsStatusResponse>((s, r) =>
            {
                return(new msdyn_UpdateBookingsStatusResponse
                {
                    BookingResult = r.BookingStatusChangeContext == "A"
                                ? "Apple"
                                : "Banana"
                });
            }).Build();

            var response = (msdyn_UpdateBookingsStatusResponse)service.Execute(new msdyn_UpdateBookingsStatusRequest {
                BookingStatusChangeContext = "A"
            });

            Assert.AreEqual("Apple", response.BookingResult);

            response = (msdyn_UpdateBookingsStatusResponse)service.Execute(new msdyn_UpdateBookingsStatusRequest {
                BookingStatusChangeContext = "B"
            });
            Assert.AreEqual("Banana", response.BookingResult);
        }
        public void CrmEnvironmentBuilder_WithChildEntities_BiDirectionalRelationship_Should_PopulateBothIds()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var contact = new Id <Contact>(Guid.NewGuid());
            var account = new Id <Account>(Guid.NewGuid());

            // The Account and Incident will be added as Account first, and Incident second.
            // The Lead will force a reorder and the Account incident would normally get placed after the Incident
            var builder = new DLaBCrmEnvironmentBuilder().
                          WithChildEntities(contact, account).
                          WithChildEntities(account, contact);

            //
            // Act
            //
            builder.Create(service);


            //
            // Assert
            //

            AssertCrm.Exists(service, account);
            AssertCrm.Exists(service, contact);
            Assert.AreEqual(contact.EntityReference, service.GetEntity(account).PrimaryContactId);
            Assert.AreEqual(contact.EntityReference, account.Entity.PrimaryContactId);
            Assert.AreEqual(account.EntityReference, service.GetEntity(contact).ParentCustomerId);
            Assert.AreEqual(account.EntityReference, contact.Entity.ParentCustomerId);
        }
        public void OrganizationServiceBuilder_WithFakeRetrieveMultiple_FakedRetrieves_Should_BeFaked()
        {
            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service = new OrganizationServiceBuilder(service).WithFakeRetrieveMultiple((s, qb) => true, GetFakedAccount()).Build();
            AssertAccountNotQueried(service);
        }
        public void CrmEnvironmentBuilder_WithChildEntities_IncidentAndAccountButAccountAddedIncidentFirst_Should_CreateAccountFirst()
        {
            //
            // Arrange
            //
            var service  = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));
            var account  = new Id <Account>(Guid.NewGuid());
            var incident = new Id <Incident>(Guid.NewGuid());

            // The Account and Incident will be added as Account first, and Incident second.
            // The Lead will force an reorder and the Account incident would normally get placed after the Incident
            var builder = new DLaBCrmEnvironmentBuilder().
                          WithEntities(new Id <PhoneCall>(Guid.NewGuid()), incident, account).
                          WithChildEntities(account, incident);

            //
            // Act
            //
            builder.Create(service);


            //
            // Assert
            //

            AssertCrm.Exists(service, account);
            AssertCrm.Exists(service, incident);
            Assert.AreEqual(account.EntityReference, service.GetEntity(incident).CustomerId);
            Assert.AreEqual(account.EntityReference, incident.Entity.CustomerId);
        }
        public void OrganizationServiceBuilder_WithIdsDefaultedForCreate_Ids_Should_BeDefaulted()
        {
            //
            // Arrange
            //
            var ids = new
            {
                Account = new
                {
                    A = new Id <Account>("E2D24D5D-428F-4FBC-AA8D-5235DC27651C"),
                    B = new Id <Account>("D901F79B-2730-47BE-821F-3485A4CA020D")
                },
                Contact = new
                {
                    A = new Id <Contact>("02C430B9-B5CC-413F-B697-1C813F194547"),
                    B = new Id <Contact>("95D9BF9A-C603-4D5C-A078-7B01A4C47BA2")
                }
            };

            IOrganizationService service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            service = new OrganizationServiceBuilder(service)
                      .WithIdsDefaultedForCreate(
                ids.Account.A,
                ids.Account.B,
                ids.Contact.A,
                ids.Contact.B).Build();

            Assert.AreEqual(ids.Account.A.EntityId, service.Create(new Account()));
            Assert.AreEqual(ids.Contact.A.EntityId, service.Create(new Contact()));
            using (var context = new CrmContext(service))
            {
                var account = new Account {
                    Id = ids.Account.B
                };
                context.AddObject(account);
                context.SaveChanges();
                AssertCrm.Exists(service, ids.Account.B);
                var contact = new Contact();
                context.AddObject(contact);
                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    var inner = ex.InnerException;
                    Assert.AreEqual("An attempt was made to create an entity of type contact with the EntityState set to created which normally means it comes from an OrganizationServiceContext.SaveChanges call.\r\nEither set ignoreContextCreation to true on the WithIdsDefaultedForCreate call, or define the id before calling SaveChanges, and add the id with the WithIdsDefaultedForCreate method.", inner?.Message);
                }
            }
        }
Example #30
0
        public void CrmEnvironmentBuilder_ExceptEntities_GivenIdStruct_Should_CreateAllExceptExcluded()
        {
            //
            // Arrange
            //
            var service = LocalCrmDatabaseOrganizationService.CreateOrganizationService(LocalCrmDatabaseInfo.Create <CrmContext>(Guid.NewGuid().ToString()));

            //
            // Act
            //
            var builder = new CrmEnvironmentBuilder().
                          WithEntities <Ids>().
                          ExceptEntities <Ids.Nested>();

            builder.Create(service);

            //
            // Assert
            //

            AssertCrm.Exists(service, Ids.Value1);
            AssertCrm.Exists(service, Ids.Value2);
            AssertCrm.NotExists(service, Ids.Nested.Value1);
            AssertCrm.NotExists(service, Ids.Nested.Value2);
        }