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);
        }
Example #2
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);
        }
        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);
        }
Example #4
0
        public void LocalCrmTests_AdvancedCrud()
        {
            // Verify that linked items exist upon create
            var service = GetService();
            var contact = new Contact {
                Id = Guid.NewGuid()
            };
            var opp = new Opportunity {
                ParentContactId = contact.ToEntityReference()
            };

            try
            {
                service.Create(opp);
                Assert.Fail("Opportunity Creation should have failed since the Contact Doesn't exist");
            }
            catch (System.ServiceModel.FaultException <OrganizationServiceFault> ex)
            {
                Assert.IsTrue(ex.Message.Contains($"With Id = {contact.Id} Does Not Exist"), "Exception type is different than expected");
            }
            catch (AssertFailedException)
            {
                throw;
            }
            catch (Exception)
            {
                Assert.Fail("Exception type is different than expected");
            }

            service.Create(contact);
            AssertCrm.Exists(service, contact);
            opp.Id = service.Create(opp);
            AssertCrm.Exists(service, opp);
        }
        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 LocalCrmTests_DeactivateActivate()
        {
            var service    = GetService();
            var entityType = typeof(Entity);
            var entitiesMissingStatusCodeAttribute = new List <string>();

            foreach (var entity in from t in typeof(SystemUser).Assembly.GetTypes()
                     where entityType.IsAssignableFrom(t) && new LateBoundActivePropertyInfo(EntityHelper.GetEntityLogicalName(t)).ActiveAttribute != ActiveAttributeType.None
                     select(Entity) Activator.CreateInstance(t))
            {
                entity.Id = service.Create(entity);
                AssertCrm.IsActive(service, entity, "Entity " + entity.GetType().Name + " wasn't created active!");
                try
                {
                    service.SetState(entity.LogicalName, entity.Id, false);
                }
                catch (Exception ex)
                {
                    if (ex.ToString().Contains("does not contain an attribute with name statuscode"))
                    {
                        entitiesMissingStatusCodeAttribute.Add(entity.LogicalName);
                        continue;
                    }
                    throw;
                }
                AssertCrm.IsNotActive(service, entity, "Entity " + entity.GetType().Name + " wasn't deactivated!");
                service.SetState(entity.LogicalName, entity.Id, true);
                AssertCrm.IsActive(service, entity, "Entity " + entity.GetType().Name + " wasn't activated!");
            }

            if (entitiesMissingStatusCodeAttribute.Any())
            {
                Assert.Fail("The following Entities do not contain an attribute with name statuscode " + String.Join(", ", entitiesMissingStatusCodeAttribute) + ". Check DLaB.Xrm.ActiveAttributeType for proper configuration.");
            }
        }
        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);
        }
Example #8
0
        public void LocalCrmDatabaseOrganizationServiceExecuteTests_ExecuteTransactionRequest()
        {
            var account = new Id <Account>("576E11B7-193A-4B80-A39A-1BF6ECD27A51");
            var contact = new Id <Contact>("A40249BF-637A-4AB9-A944-3C2506D12F18");
            var request = new ExecuteTransactionRequest
            {
                Requests = new OrganizationRequestCollection
                {
                    new CreateRequest {
                        Target = account
                    },
                    new CreateRequest {
                        Target = contact
                    }
                },
                ReturnResponses = true
            };
            var service  = GetService();
            var response = (ExecuteTransactionResponse)service.Execute(request);

            AssertCrm.Exists(service, account);
            AssertCrm.Exists(service, contact);
            Assert.AreEqual(response.Responses.Count, 2);

            service.Delete(account.Entity);
            service.Delete(contact.Entity);

            request.ReturnResponses = false;
            response = (ExecuteTransactionResponse)service.Execute(request);
            Assert.AreEqual(response.Responses.Count, 0);
        }
Example #9
0
        public void AssumedEntities_Load_Should_LoadAssumedEntities()
        {
            var service     = TestBase.GetOrganizationService();
            var assumptions = LoadTestAssumptions(service);

            AssertCrm.Exists(service, assumptions.Get <AccountDefault>());
            AssertCrm.Exists(service, assumptions.Get <ContactDefault>());
        }
Example #10
0
        public void AssumedEntities_Load_Should_LoadAssumedEntities()
        {
            TestInitializer.InitializeTestSettings();
            var service     = TestBase.GetOrganizationService();
            var assumptions = new AssumedEntities();

            assumptions.Load(service, new AccountDefault(), new ContactDefault());
            AssertCrm.Exists(service, assumptions.Get <AccountDefault>());
            AssertCrm.Exists(service, assumptions.Get <ContactDefault>());
        }
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service).WithIdsDefaultedForCreate(Ids.Contact).Build();
                var entity = new Contact
                {
                    Address1_City = "Any Town",
                    Address1_AddressTypeCodeEnum = Contact_Address1_AddressTypeCode.Primary,
                    FirstName        = "Hi",
                    LastName         = "Yah",
                    NumberOfChildren = 3,
                };

                // Should Create
                service.CreateOrMinimumUpdate(entity);
                AssertCrm.Exists(Ids.Contact);

                // Should not update or create
                var readOnly = new OrganizationServiceBuilder(service).IsReadOnly().Build();

                readOnly.CreateOrMinimumUpdate(entity);

                // Should update only single value;
                var entitiesById = new Dictionary <Guid, Contact>
                {
                    { entity.Id, entity.Clone(true) }
                };

                entity.Address1_Country = "USA";

                var updater = new TestUpdater(entitiesById);

                service.CreateOrMinimumUpdate(entity, updater);
                var unchanged = updater.MostRecentUnchangedAttributes;

                Assert.AreEqual(5, unchanged.Count);
                AssertContains(unchanged, Contact.Fields.Address1_City);
                AssertContains(unchanged, Contact.Fields.NumberOfChildren);
                AssertContains(unchanged, Contact.Fields.Address1_AddressTypeCode);
                AssertContains(unchanged, Contact.Fields.FirstName);
                AssertContains(unchanged, Contact.Fields.LastName);
                Assert.IsFalse(unchanged.Contains(Contact.Fields.Address1_Country));

                // No existing, should Update everything:
                updater.MostRecentUnchangedAttributes.Clear();
                service.CreateOrMinimumUpdate(new Contact {
                    Id        = Ids.Contact,
                    FirstName = "Updated"
                }, new Dictionary <Guid, Contact>());
                Assert.AreEqual(0, updater.MostRecentUnchangedAttributes.Count);
                var value = service.GetEntity(Ids.Contact);

                Assert.AreEqual("Updated", value.FirstName);
            }
        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 #13
0
        public void LocalCrmTests_Crud_Advanced()
        {
            // Verify that linked items exist upon create
            var service = GetService();
            var contact = new Contact {
                Id = Guid.NewGuid()
            };
            var opp = new Opportunity {
                ParentContactId = contact.ToEntityReference()
            };

            AssertOrganizationServiceFaultException("Opportunity Creation should have failed since the Contact Doesn't exist",
                                                    $"With Id = {contact.Id} Does Not Exist",
                                                    () => service.Create(opp));

            service.Create(contact);
            AssertCrm.Exists(service, contact);
            opp.Id = service.Create(opp);
            AssertCrm.Exists(service, opp);
        }
        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_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);
        }
 protected override void Test(IOrganizationService service)
 {
     // Test happens CleanupTestData
     AssertCrm.NotExists(Ids.Contact, "Contact Should have been deleted up by the CleanupDataPreInitialization");
 }
        public void Test(ITestLogger logger)
        {
            Logger = logger;
            var timer = new TestActionTimer(logger);
            LoadConfigurationSettingsOnce(this);
            InitializeEntityIds();
            if (EntityIds != null && EntityIds.Count > 0)
            {
                timer.Time(PopulateEntityReferences, "Initialization Entity Reference (ms): ");
            }
            using (var internalService = GetInternalOrganizationServiceProxy())
            {
                // ReSharper disable once AccessToDisposedClosure
                timer.Time(() => CleanupTestData(internalService, false), "Cleanup PreTestData (ms): ");

                try
                {
                    // ReSharper disable once AccessToDisposedClosure
                    timer.Time(() => ValidateAssumptions(internalService), "Validate Assumptions (ms): ");

                    var service = GetIOrganizationService();
                    AssertCrm = new AssertCrm(service);

                    timer.Time(() => InitializeTestData(service), "Initialize TestData (ms): ");
                    timer.Time(() => Test(service), "Run Test (ms): ");
                }
                finally
                {
                    // ReSharper disable once AccessToDisposedClosure
                    timer.Time(() => CleanupTestData(internalService, true), "Cleanup PostTestData (ms): ");
                }
            }
        }
Example #18
0
        public void LocalCrmTests_DeactivateActivate()
        {
            var service    = GetService();
            var entityType = typeof(Entity);
            var entitiesMissingStatusCodeAttribute = new List <string>();
            var entitiesMissingStateCodeAttribute  = new List <string>();

            foreach (var entity in from t in typeof(SystemUser).Assembly.GetTypes()
                     where entityType.IsAssignableFrom(t) && new LateBoundActivePropertyInfo(EntityHelper.GetEntityLogicalName(t)).ActiveAttribute != ActiveAttributeType.None
                     select(Entity) Activator.CreateInstance(t))
            {
                if (entity.LogicalName == RecommendationCache.EntityLogicalName)
                {
                    entity.Id = service.Create(entity);
                }
                if (entity.LogicalName == Incident.EntityLogicalName)
                {
                    // Satisfy ErrorCodes.unManagedidsincidentparentaccountandparentcontactnotpresent
                    var customer = new Account();
                    customer.Id = service.Create(customer);
                    entity[Incident.Fields.CustomerId] = customer.ToEntityReference();
                }
                entity.Id = service.Create(entity);
                AssertCrm.IsActive(service, entity, "Entity " + entity.GetType().Name + " wasn't created active!");
                try
                {
                    if (entity.LogicalName == Incident.EntityLogicalName)
                    {
                        // Requires the Special Resolve Incident Request Message
                        continue;
                    }

                    service.SetState(entity.LogicalName, entity.Id, false);
                }
                catch (Exception ex)
                {
                    if (ex.ToString().Contains("does not contain an attribute with name statuscode"))
                    {
                        entitiesMissingStatusCodeAttribute.Add(entity.LogicalName);
                        continue;
                    }
                    if (ex.ToString().Contains("does not contain an attribute with name statecode"))
                    {
                        entitiesMissingStateCodeAttribute.Add(entity.LogicalName);
                        continue;
                    }

                    throw;
                }
                AssertCrm.IsNotActive(service, entity, "Entity " + entity.GetType().Name + " wasn't deactivated!");
                service.SetState(entity.LogicalName, entity.Id, true);
                AssertCrm.IsActive(service, entity, "Entity " + entity.GetType().Name + " wasn't activated!");
            }

            if (entitiesMissingStatusCodeAttribute.Any())
            {
                Assert.Fail("The following Entities do not contain an attribute with name statuscode " + entitiesMissingStatusCodeAttribute.ToCsv() + ". Check DLaB.Xrm.ActiveAttributeType for proper configuration.");
            }

            if (entitiesMissingStateCodeAttribute.Any())
            {
                Assert.Fail("The following Entities do not contain an attribute with name statecode " + entitiesMissingStateCodeAttribute.ToCsv() + ". Check DLaB.Xrm.ActiveAttributeType for proper configuration.");
            }
        }