protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new TestPlugin(null, null);


                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    new PluginExecutionContextBuilder()
                    .WithRegisteredEvent(40, "Create", "new_testentity")
                    .WithPrimaryEntityId(Guid.NewGuid())
                    .Build(),
                    new DebugLogger()).Build();

                for (int i = 0; i < 20; i++)
                {
                    try
                    {
                        plugin.Execute(serviceProvider);
                    }
                    catch (Exception ex)
                    {
                        // Process if it is not the expected exception we are throwing to test telemetry.
                        if (ex.Message != "Unhandled Plugin Exception Throw Unhandled Exception")
                        {
                            throw;
                        }
                    }
                }
            }
        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 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);
        }
Beispiel #4
0
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new Sample.FieldEncryptionPlugin(null, null);

                plugin.Container.Implement <ICache>().Using <Fakes.FakeCacheProvider>().WithOverwrite();
                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();


                var target = new Contact()
                {
                    Id         = ExistingIds.Contact.EntityId,
                    Department = TestData.DecryptedValue
                };


                var executionContext = new PluginExecutionContextBuilder()
                                       .WithRegisteredEvent(20, "Update", Contact.EntityLogicalName)
                                       .WithInputParameter("Target", target)
                                       .Build();

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    executionContext,
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);


                var contextTarget = executionContext.InputParameters["Target"] as Contact;

                Assert.AreEqual(TestData.EncryptedValue, contextTarget.Department);
            }
Beispiel #5
0
            protected override void Test(IOrganizationService service)
            {
                //
                // Arrange
                //
                service = new OrganizationServiceBuilder(service)
                          .WithIdsDefaultedForCreate(Ids.Lead)
                          .Build();

                //
                // Act
                //
                service.Create(Ids.Account); // Id is populated, This is OK
                service.Create(new Lead());  // No Id populated, but WithIdsDefaultedForCreate, lists it as a value
                try
                {
                    service.Create(new Lead()); // Not valid since only one Lead Id has been pre-defined.
                }
                catch (Exception ex)
                {
                    //
                    // Assert
                    //
                    Assert.IsTrue(ex.Message.Contains("An attempt was made to create an entity of type lead, but no id exists in the NewEntityDefaultIds Collection for it.\r\nEither the entity's Id was not populated as a part of initialization, or a call is needs to be added to to OrganizationServiceBuilder.WithIdsDefaultedForCreate(id)"));
                    return;
                }
                Assert.Fail("IOrganizationService should enforce Ids being defined");
            }
Beispiel #6
0
    protected override void Test(IOrganizationService service)
    {
        service = new OrganizationServiceBuilder(service)
                  .WithSalesOrderNumbersDefaulted()
                  .Build();
        // Execute Function for test
        var id = Example.ValidateAndCreateOrderAndDetail(service);

        Assert.IsNotNull(service.GetEntity <SalesOrder>(id).OrderNumber);
    }
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new Sample.FieldEncryptionPlugin(null, null);

                plugin.Container.Implement <ICache>().Using <Fakes.FakeCacheProvider>().WithOverwrite();
                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();

                var testQry = new QueryExpressionBuilder <Contact>()
                              .Select("department")
                              .WhereAll(e => e
                                        .IsActive()
                                        .WhereAll(e1 => e1
                                                  .Attribute("fullname").Is(ConditionOperator.Like, "# " + TestData.DecryptedValue + "%")))
                              .Build();


                var executionContext = new PluginExecutionContextBuilder()
                                       .WithRegisteredEvent(20, "RetrieveMultiple", Contact.EntityLogicalName)
                                       .WithInputParameter("Query", testQry)
                                       .Build();

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    executionContext,
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);

                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                // get query and verify that it is modified as expected.
                var outQuery = context.InputParameters["Query"] as QueryExpression;

                var criteria = outQuery.Criteria;

                Assert.AreEqual(LogicalOperator.Or, criteria.FilterOperator);
                Assert.AreEqual(0, criteria.Conditions.Count);
                Assert.AreEqual(1, criteria.Filters.Count);

                // check sub filter
                criteria = criteria.Filters[0];

                Assert.AreEqual(LogicalOperator.And, criteria.FilterOperator);
                Assert.AreEqual(2, criteria.Conditions.Count);
                Assert.AreEqual(0, criteria.Filters.Count);

                Assert.AreEqual("department", criteria.Conditions[0].AttributeName);
                Assert.AreEqual(TestData.EncryptedValue, criteria.Conditions[0].Values[0]);

                Assert.AreEqual("statecode", criteria.Conditions[1].AttributeName);
                Assert.AreEqual(0, criteria.Conditions[1].Values[0]);
            }
            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);
            }
            protected override void Test(IOrganizationService service)
            {
                //Test framework does not support the FetchXmlToQueryExpression so we fake the expected API result for the specified fetchXml.
                var fakedFetchQuery = new Microsoft.Xrm.Sdk.Query.QueryExpression()
                {
                    EntityName = "new_transactiondatarecord",
                    ColumnSet  = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "new_transactiondatarecordid" }),
                    Criteria   = new Microsoft.Xrm.Sdk.Query.FilterExpression
                    {
                        FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And,
                        Conditions     =
                        {
                            new Microsoft.Xrm.Sdk.Query.ConditionExpression("new_datafield1", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, "TestValue")
                        }
                    }
                };

                service = new OrganizationServiceBuilder()
                          .WithFakeExecute((s, r) => {
                    if (r.RequestName == "FetchXmlToQueryExpression")
                    {
                        FetchXmlToQueryExpressionResponse resp = new FetchXmlToQueryExpressionResponse();
                        resp.Results.Add("Query", fakedFetchQuery);
                        return(resp);
                    }
                    return(s.Execute(r));
                })
                          .Build();

                var executionContext   = GetExecutionContext(service);
                var serializer         = new DefaultSerializer();
                var transactionPointer = new RecordPointer <Guid>(Ids.ExistingTransaction.LogicalName, Ids.ExistingTransaction.EntityId);

                var transactionServiceFactory = Container.Resolve <ITransactionServiceFactory>();
                var transactionService        = transactionServiceFactory.CreateTransactionService(executionContext, false);

                var transaction = transactionService.LoadTransaction(executionContext, transactionPointer);

                var evaluatorType = new EvaluatorType.DataReccordQueryMatchEvaluator(
                    Ids.DataRecordQueryEvaluator.ToRecordPointer(), "TestEvaluator",
                    "S3.D365.Transactions",
                    "CCLLC.BTF.Process.CDS.EvaluatorType.DataReccordQueryMatchEvaluator");



                string parameterJson = "{\"FetchXml\":\"<fetch><entity name='new_transactiondatarecord'><filter type='and'><condition value='TestValue' attribute='new_datafield1' operator='eq'/></filter></entity></fetch>\"}";

                var parameters = serializer.CreateParamters(parameterJson);

                var result = evaluatorType.Evaluate(executionContext, parameters, transaction);

                Assert.AreEqual(true, result.Passed);
            }
        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);
                }
            }
        }
        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 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);
        }
Beispiel #13
0
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new TestPlugin(null, null);

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    new PluginExecutionContextBuilder()
                    .WithRegisteredEvent(40, "Create", "new_testentity")
                    .WithPrimaryEntityId(Guid.NewGuid())
                    .Build(),
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);
            }
Beispiel #14
0
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new Sample.FieldEncryptionPlugin(null, null);

                plugin.Container.Implement <ICache>().Using <Fakes.FakeCacheProvider>().WithOverwrite();
                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();


                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();


                var target = new Contact()
                {
                    Id         = ExistingIds.Contact.EntityId,
                    Department = TestData.EncryptedValue
                };

                var maskingInstructions = new Dictionary <string, EncryptedFieldService.MaskingInstruction>();

                maskingInstructions.Add("department", EncryptedFieldService.MaskingInstruction.Unmask);


                var executionContext = new PluginExecutionContextBuilder()
                                       .WithRegisteredEvent(40, "Retrieve", Contact.EntityLogicalName)
                                       .WithInputParameter("Target", target.ToEntityReference())
                                       .WithInputParameter("ColumnSet", new ColumnSet("display"))
                                       .WithOutputParameter("Entity", target)
                                       .WithSharedVariable("CCLLC.EncryptedFieldService.DecryptColumns", maskingInstructions)
                                       .Build();

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    executionContext,
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);


                var contextTarget = executionContext.OutputParameters["Entity"] as Contact;

                Assert.AreEqual(TestData.DecryptedValue, contextTarget.Department);
            }
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder()
                          .WithFakeExecute((s, r) => {
                    if (r.RequestName == "new_Action")
                    {
                        Assert.AreEqual(Ids.ExistingDataRecord.EntityId, (r["Target"] as EntityReference).Id);
                        Assert.AreEqual(Ids.ExistingTransaction.EntityId, (r["Transaction"] as EntityReference).Id);
                        OrganizationResponse resp = new OrganizationResponse();
                        resp.Results["IsTrue"]    = false;
                        resp.Results["Message"]   = "Action did not succeed.";
                        return(resp);
                    }
                    return(s.Execute(r));
                })
                          .Build();

                var executionContext   = GetExecutionContext(service);
                var serializer         = new DefaultSerializer();
                var transactionPointer = new RecordPointer <Guid>(Ids.ExistingTransaction.LogicalName, Ids.ExistingTransaction.EntityId);

                var transactionServiceFactory = Container.Resolve <ITransactionServiceFactory>();
                var transactionService        = transactionServiceFactory.CreateTransactionService(executionContext, false);

                var transaction = transactionService.LoadTransaction(executionContext, transactionPointer);


                var evaluatorType = new EvaluatorType.DataRecordActionEvaluator(
                    Ids.DataActionEvaluator.ToRecordPointer(),
                    "TestEvaluator",
                    "S3.D365.Transactions",
                    "CCLLC.BTF.Process.CDS.EvaluatorType.DataReccordActionEvaluator");

                string parameterJson = "{\"ActionName\":\"new_Action\"}";

                var parameters = serializer.CreateParamters(parameterJson);

                var result = evaluatorType.Evaluate(executionContext, parameters, transaction);

                Assert.AreEqual(false, result.Passed);
                Assert.AreEqual("Action did not succeed.", result.Message);
            }
        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);
        }
Beispiel #17
0
            protected override void Test(IOrganizationService service)
            {
                service = new OrganizationServiceBuilder(service)
                          .Build();

                var plugin = new Sample.FieldEncryptionPlugin(null, null);

                plugin.Container.Implement <ICache>().Using <Fakes.FakeCacheProvider>().WithOverwrite();
                plugin.Container.Implement <ISecretProviderFactory>().Using <Fakes.FakeSecretProviderFactory <Fakes.FakeSecretProvider> >().WithOverwrite();


                var target = new Contact()
                {
                    Id         = ExistingIds.Contact.EntityId,
                    Department = TestData.EncryptedValue
                };

                var executionContext = new PluginExecutionContextBuilder()
                                       .WithRegisteredEvent(20, "Retrieve", Contact.EntityLogicalName)
                                       .WithInputParameter("Target", target.ToEntityReference())
                                       .WithInputParameter("ColumnSet", new ColumnSet("department", "telephone1"))
                                       .WithOutputParameter("Entity", target)
                                       .Build();

                var serviceProvider = new ServiceProviderBuilder(
                    service,
                    executionContext,
                    new DebugLogger()).Build();

                plugin.Execute(serviceProvider);

                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                var columns = context.InputParameters["ColumnSet"] as ColumnSet;

                Assert.AreEqual(1, columns.Columns.Count);
                Assert.IsTrue(columns.Columns.Contains("department"));
            }
Beispiel #18
0
        private static void TestForPhoneNumber(IOrganizationService service, QueryExpression qe, FilterExpression accountFilter, string telephone)
        {
            accountFilter.WhereEqual(
                Account.Fields.Telephone1, telephone,
                LogicalOperator.Or,
                Account.Fields.Telephone2, telephone,
                LogicalOperator.Or,
                Account.Fields.Telephone3, telephone
                );

            var entity = service.GetFirstOrDefault(qe);

            Assert.IsNotNull(entity, $"{qe.EntityName} should have been found with matching telephone 1 number.");

            var account = service.GetFirst <Account>();

            account.Telephone2 = telephone;
            account.Telephone1 = telephone + "1";
            service.Update(account);
            entity = service.GetFirstOrDefault(qe);
            Assert.IsNotNull(entity, $"{qe.EntityName} should have been found with matching telephone 2 number.");

            account.Telephone3 = telephone;
            account.Telephone2 = telephone + "2";
            service.Update(account);
            entity = service.GetFirstOrDefault(qe);
            Assert.IsNotNull(entity, $"{qe.EntityName} should have been found with matching telephone 3 number.");

            service = new OrganizationServiceBuilder(service)
                      .WithEntityFilter <Account>(account.Id).Build();
            entity = service.GetFirstOrDefault(qe);
            Assert.IsNotNull(entity, $"{qe.EntityName} should have been found with matching telephone 3 number and Id.");

            account.Telephone3 += "A";
            service.Update(account);
            entity = service.GetFirstOrDefault(qe);
            Assert.IsNull(entity, $"{qe.EntityName} should have not have been found with a non-matching telephone 3 number and Id.");
        }
Beispiel #19
0
 protected override void InitializeTestData(IOrganizationService service)
 {
     service = new OrganizationServiceBuilder(service).WithSalesOrderNumbersDefaulted().Build();
     service.Create(new SalesOrder());
 }