예제 #1
0
        public void No_Invoice_And_Price_Overriden_Is_False_Result_0()
        {
            var context = new XrmFakedContext()
            {
                InitializationLevel = EntityInitializationLevel.PerEntity
            };
            IOrganizationService service = context.GetOrganizationService();

            List <Entity> initialEntities = new List <Entity>();

            Entity invoiceDetail = new Entity("invoicedetail");

            invoiceDetail.Id = Guid.NewGuid();
            invoiceDetail["ispriceoverridden"] = false;
            initialEntities.Add(invoiceDetail);

            context.Initialize(initialEntities);
            Entity testPostCreate = service.Retrieve(invoiceDetail.LogicalName, invoiceDetail.Id, new ColumnSet(true));

            Assert.Equal(new Money(0m), testPostCreate["priceperunit"]);
            Assert.Equal(1m, testPostCreate["quantity"]);
            Assert.Equal(new Money(0m), testPostCreate["amount"]);
            Assert.Equal(new Money(0m), testPostCreate["extendedamount"]);
        }
        public void Existing_Assembly_With_No_Plugins_Should_Update_Assembly_With_New_Plugins()
        {
            var context    = new XrmFakedContext();
            var orgService = context.GetOrganizationService();

            context.Initialize(new List <Entity>()
            {
                UpdateSdkMessage,
                CreateSdkMessage,
                UpdateContactMessageFilter,
                UpdateAccountMessageFilter,
                CreateContactMessageFilter
            });

            var pluginWrapper = new PluginWrapper();

            pluginWrapper.RegisterPlugins(SampleFullPluginManifest, orgService);

            var postRegisteredPluginTypes =
                (from p in context.CreateQuery <PluginType>()
                 select p).ToList();

            postRegisteredPluginTypes.Should().HaveCount(2);
        }
예제 #3
0
        public void MoneyType()
        {
            // MoneyType            totaltax                           invoice
            XrmFakedContext fakedContext = SupportMethods.SetupPrimitiveFakedService(
                SupportMethods.InvoiceLogicalName,
                SupportMethods.InvoiceDisplayName,
                SupportMethods.GetMoneyTypeEntity());

            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.InvoiceLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.InvoiceDisplayName, 1033);
                entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");

                entityMetadata.Attributes.First(a => a.LogicalName == "totaltax").SetSealedPropertyValue("DisplayName", new Label("Total Tax", 1033));
                entityMetadata.Attributes.First(a => a.LogicalName == "invoiceid").SetSealedPropertyValue("DisplayName", new Label("Invoice", 1033));

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.GetMoneyTypeFetch());
            Assert.AreEqual(
                DataBuilder.BuildSchemaXML().InnerXml,
                SupportMethods.GetMoneyTypeExpectedSchema());
        }
예제 #4
0
        public void DateTimeType()
        {
            // DateTimeType         publishon                          knowledgearticle
            XrmFakedContext fakedContext = SupportMethods.SetupPrimitiveFakedService(
                SupportMethods.KnowledgeArticleLogicalName,
                SupportMethods.KnowledgeArticleDisplayName,
                SupportMethods.GetDateTimeTypeEntity());

            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.KnowledgeArticleLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.KnowledgeArticleDisplayName, 1033);
                entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "title");

                entityMetadata.Attributes.First(a => a.LogicalName == "publishon").SetSealedPropertyValue("DisplayName", new Label("Publish On", 1033));
                entityMetadata.Attributes.First(a => a.LogicalName == "knowledgearticleid").SetSealedPropertyValue("DisplayName", new Label("Knowledge Article", 1033));

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.GetDateTimeTypeFetch());
            Assert.AreEqual(
                DataBuilder.BuildSchemaXML().InnerXml,
                SupportMethods.GetDateTimeTypeExpectedSchema());
        }
        public void TestRetrieveMultipleWithNull()
        {
            Entity testEntity = new Entity("testentity");

            testEntity["field"] = null;
            testEntity.Id       = Guid.NewGuid();

            XrmFakedContext      context = new XrmFakedContext();
            IOrganizationService service = context.GetOrganizationService();

            context.Initialize(
                new List <Entity>()
            {
                testEntity
            }
                );

            QueryExpression contactQuery = new QueryExpression("testentity");

            contactQuery.ColumnSet = new ColumnSet("field");
            EntityCollection result = service.RetrieveMultiple(contactQuery);

            Assert.False(result.Entities[0].Contains("field"));
        }
예제 #6
0
        public void Should_Not_Change_Context_Objects_Without_Update_And_Retrieve_Multiple()
        {
            var entityId = Guid.NewGuid();
            var context  = new XrmFakedContext();
            var service  = context.GetOrganizationService();

            context.Initialize(new[] {
                new Account
                {
                    Id   = entityId,
                    Name = "Adventure Works"
                }
            });

            Account firstRetrieve, secondRetrieve = null;

            using (var ctx = new XrmServiceContext(service))
            {
                firstRetrieve = ctx.CreateQuery <Account>()
                                .Where(a => a.AccountId == entityId)
                                .FirstOrDefault();
            }

            using (var ctx = new XrmServiceContext(service))
            {
                secondRetrieve = ctx.CreateQuery <Account>()
                                 .Where(a => a.AccountId == entityId)
                                 .FirstOrDefault();
            }

            firstRetrieve.Name = "Updated locally";

            Assert.False(firstRetrieve == secondRetrieve);
            Assert.Equal("Updated locally", firstRetrieve.Name);
            Assert.Equal("Adventure Works", secondRetrieve.Name);
        }
예제 #7
0
        public static void Should_Throw_When_Relationship_Not_Set_In_Metadata()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetOrganizationService();

            var account = new Entity(Account.EntityLogicalName);

            account.Id = Guid.NewGuid();
            fakedContext.Initialize(account);

            var request = new RetrieveRequest
            {
                Target               = account.ToEntityReference(),
                ColumnSet            = new ColumnSet(true),
                RelatedEntitiesQuery = new RelationshipQueryCollection
                {
                    { new Relationship("any"), new QueryExpression() }
                }
            };

            var exception = Assert.Throws <Exception>(() => fakedService.Execute(request));

            Assert.Equal("Relationship \"any\" does not exist in the metadata cache.", exception.Message);
        }
예제 #8
0
        public void BuAndOrgAreReturnedWhenUserBelongsToBuAndOrg()
        {
            var businessUnit = new Entity("businessunit")
            {
                Id = Guid.NewGuid()
            };

            var user = new Entity("systemuser")
            {
                Id = Guid.NewGuid(),
                ["businessunitid"] = businessUnit.ToEntityReference(),
                ["organizationid"] = (Guid?)organization_.Id
            };

            var dbContent = new List <Entity> {
                user,
                businessUnit,
                organization_
            };

            var context = new XrmFakedContext()
            {
                CallerId = user.ToEntityReference()
            };

            context.Initialize(dbContent);

            var service = context.GetOrganizationService();

            var req      = new WhoAmIRequest();
            var response = service.Execute(req) as WhoAmIResponse;

            Assert.Equal(user.Id, response.UserId);
            Assert.Equal(businessUnit.Id, response.BusinessUnitId);
            Assert.Equal(organization_.Id, response.OrganizationId);
        }
예제 #9
0
        public void When_a_non_existing_member_is_added_to_an_existing_list_exception_is_thrown()
        {
            var ctx     = new XrmFakedContext();
            var service = ctx.GetOrganizationService();

            var list = new Crm.List()
            {
                Id              = Guid.NewGuid(),
                ListName        = "Some list",
                CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account)
            };

            ctx.Initialize(new List <Entity>
            {
                list
            });

            AddMemberListRequest request = new AddMemberListRequest();

            request.EntityId = Guid.NewGuid();
            request.ListId   = list.ToEntityReference().Id;

            Assert.Throws <FaultException <OrganizationServiceFault> >(() => service.Execute(request));
        }
예제 #10
0
        public void TestThatPageInfoTotalRecordCountWorksWithPaging()
        {
            XrmFakedContext      context         = new XrmFakedContext();
            IOrganizationService service         = context.GetOrganizationService();
            List <Entity>        initialEntities = new List <Entity>();

            for (int i = 0; i < 100; i++)
            {
                Entity e = new Entity("entity");
                e.Id = Guid.NewGuid();
                initialEntities.Add(e);
            }

            context.Initialize(initialEntities);

            QueryExpression query = new QueryExpression("entity");

            query.PageInfo.ReturnTotalRecordCount = true;
            query.PageInfo.PageNumber             = 1;
            query.PageInfo.Count = 10;

            EntityCollection result = service.RetrieveMultiple(query);

            Assert.Equal(10, result.Entities.Count);
            Assert.Equal(100, result.TotalRecordCount);
            Assert.True(result.MoreRecords);

            query.PageInfo.PageNumber++;
            query.PageInfo.Count        = 20;
            query.PageInfo.PagingCookie = result.PagingCookie;

            result = service.RetrieveMultiple(query);
            Assert.Equal(20, result.Entities.Count);
            Assert.Equal(100, result.TotalRecordCount);
            Assert.True(result.MoreRecords);
        }
예제 #11
0
        public void TestThatPageInfoTotalRecordCountWorks()
        {
            XrmFakedContext      context         = new XrmFakedContext();
            IOrganizationService service         = context.GetOrganizationService();
            List <Entity>        initialEntities = new List <Entity>();

            Entity e = new Entity("entity");

            e.Id          = Guid.NewGuid();
            e["retrieve"] = true;
            initialEntities.Add(e);

            Entity e2 = new Entity("entity");

            e2.Id          = Guid.NewGuid();
            e2["retrieve"] = true;
            initialEntities.Add(e2);

            Entity e3 = new Entity("entity");

            e3.Id          = Guid.NewGuid();
            e3["retrieve"] = false;
            initialEntities.Add(e3);

            context.Initialize(initialEntities);

            QueryExpression query = new QueryExpression("entity");

            query.PageInfo.ReturnTotalRecordCount = true;
            query.Criteria.AddCondition("retrieve", ConditionOperator.Equal, true);
            EntityCollection result = service.RetrieveMultiple(query);

            Assert.Equal(2, result.Entities.Count);
            Assert.Equal(2, result.TotalRecordCount);
            Assert.False(result.MoreRecords);
        }
        public void When_calling_retrieve_entity_with_a_fake_entity_metadata_that_one_is_returned()
        {
            var ctx     = new XrmFakedContext();
            var service = ctx.GetOrganizationService();

            var entityMetadata = new EntityMetadata()
            {
                LogicalName    = Account.EntityLogicalName,
                IsCustomizable = new BooleanManagedProperty(true)
            };

            ctx.InitializeMetadata(entityMetadata);

            var request = new RetrieveEntityRequest()
            {
                EntityFilters = EntityFilters.Entity,
                LogicalName   = Account.EntityLogicalName
            };

            var response = service.Execute(request);

            Assert.IsType <RetrieveEntityResponse>(response);
            Assert.True((response as RetrieveEntityResponse).EntityMetadata.IsCustomizable.Value);
        }
예제 #13
0
        public void SingleEntity_AllPluginsDisabled()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            fakedContext.Initialize(SupportMethods.GetSingleEntity_AllPluginsDisabledEntity());
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var entityMetadata         = fakedContext.GetEntityMetadataByName(SupportMethods.AccountLogicalName);
                entityMetadata.DisplayName = new Label(SupportMethods.AccountDisplayName, 1033);
                entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");

                entityMetadata.Attributes.First(a => a.LogicalName == "name").SetSealedPropertyValue("DisplayName", new Label("Account Name", 1033));
                entityMetadata.Attributes.First(a => a.LogicalName == "accountid").SetSealedPropertyValue("DisplayName", new Label("Account", 1033));
                entityMetadata.Attributes.First(a => a.LogicalName == "accountid").SetSealedPropertyValue("AttributeType", AttributeTypeCode.Uniqueidentifier);

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.SetPluginsDisabled(true);
            DataBuilder.AppendData(SupportMethods.GetSingleEntity_AllPluginsDisabledFetch());
            Assert.AreEqual(
                DataBuilder.BuildSchemaXML().InnerXml,
                SupportMethods.GetSingleEntity_AllPluginsDisabledEntityExpectedSchema());
        }
예제 #14
0
        public void TestRetriveMultipleWithLinkEntityWithAlternateNullField()
        {
            // ARRANGE

            List <Entity> initialEntities = new List <Entity>();

            Entity parentEntity = new Entity("parent");

            parentEntity["parentname"] = "parent name";
            parentEntity.Id            = Guid.NewGuid();
            initialEntities.Add(parentEntity);

            // create the first child which has the "myvalue" field set to "value"
            Entity childEntity1 = new Entity("child");

            childEntity1["parent"]  = parentEntity.ToEntityReference();
            childEntity1["name"]    = "entity1";
            childEntity1["myvalue"] = "value";
            childEntity1.Id         = Guid.NewGuid();
            initialEntities.Add(childEntity1);

            // create the second child which has the "myvalue" field set to null
            Entity childEntity2 = new Entity("child");

            childEntity2["parent"]  = parentEntity.ToEntityReference();
            childEntity2["name"]    = "entity2";
            childEntity2["myvalue"] = null;
            childEntity2.Id         = Guid.NewGuid();
            initialEntities.Add(childEntity2);

            XrmFakedContext      context = new XrmFakedContext();
            IOrganizationService service = context.GetOrganizationService();

            context.Initialize(initialEntities);

            // the query selects the "parent" entity, and joins to the "child" entities
            QueryExpression query = new QueryExpression("parent");

            query.ColumnSet = new ColumnSet("parentname");

            LinkEntity link = new LinkEntity("parent", "child", "parentid", "parent", JoinOperator.Inner);

            link.EntityAlias = "c";
            link.Columns     = new ColumnSet("name", "myvalue");

            query.LinkEntities.Add(link);

            // ACT

            DataCollection <Entity> results = service.RetrieveMultiple(query).Entities;

            // ASSERT

            // fields for the first entity work as expected...
            string entity1Name  = results[0].GetAttributeValue <AliasedValue>("c.name").Value as string;
            string entity1Value = results[0].GetAttributeValue <AliasedValue>("c.myvalue").Value as string;

            Assert.Equal("entity1", entity1Name);
            Assert.Equal("value", entity1Value);

            // fields for the second entity do not.
            // The child "name" field is correct, but the "myvalue" field is returning the value of the previous
            // entity when it should be returning null
            string entity2Name  = results[1].GetAttributeValue <AliasedValue>("c.name").Value as string;
            string entity2Value = results[1].GetAttributeValue <AliasedValue>("c.myvalue").Value as string;

            // this works fine:
            Assert.Equal("entity2", entity2Name);

            // this fails (entity2Value is "value")
            Assert.Equal(null, entity2Value);
        }
        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 OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = (AddListMembersListRequest)request;

            if (req.ListId == null || req.ListId == Guid.Empty)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "ListId parameter is required");
            }

            if (req.MemberIds == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "MemberIds parameter is required");
            }

            var service = ctx.GetOrganizationService();

            //Find the list
            var list = ctx.CreateQuery("list")
                       .Where(e => e.Id == req.ListId)
                       .FirstOrDefault();

            if (list == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), string.Format("List with Id {0} wasn't found", req.ListId.ToString()));
            }

            //Find the member
            if (!list.Attributes.ContainsKey("createdfromcode"))
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), string.Format("List with Id {0} must have a CreatedFromCode attribute defined and it has to be an option set value.", req.ListId.ToString()));
            }

            if (list["createdfromcode"] != null && !(list["createdfromcode"] is OptionSetValue))
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), string.Format("List with Id {0} must have a CreatedFromCode attribute defined and it has to be an option set value.", req.ListId.ToString()));
            }

            var    createdFromCodeValue = (list["createdfromcode"] as OptionSetValue).Value;
            string memberEntityName     = "";

            switch (createdFromCodeValue)
            {
            case (int)ListCreatedFromCode.Account:
                memberEntityName = "account";
                break;

            case (int)ListCreatedFromCode.Contact:
                memberEntityName = "contact";
                break;

            case (int)ListCreatedFromCode.Lead:
                memberEntityName = "lead";
                break;

            default:
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), string.Format("List with Id {0} must have a supported CreatedFromCode value (Account, Contact or Lead).", req.ListId.ToString()));
            }

            foreach (var memberId in req.MemberIds)
            {
                var member = ctx.CreateQuery(memberEntityName)
                             .Where(e => e.Id == memberId)
                             .FirstOrDefault();

                if (member == null)
                {
                    throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), string.Format("Member of type {0} with Id {1} wasn't found", memberEntityName, memberId.ToString()));
                }

                //create member list
                var listmember = new Entity("listmember");
                listmember["listid"]   = new EntityReference("list", req.ListId);
                listmember["entityid"] = new EntityReference(memberEntityName, memberId);

                service.Create(listmember);
            }

            return(new AddListMembersListResponse());
        }
예제 #17
0
        public void When_executing_a_query_expression_with_null_operator_and_early_bound_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var service = context.GetOrganizationService();

            var account1 = new Account()
            {
                Id = Guid.NewGuid(), Name = "1 Test"
            };
            var account2 = new Account()
            {
                Id = Guid.NewGuid(), Name = "2 Test"
            };
            var account3 = new Account()
            {
                Id = Guid.NewGuid(), Name = "3 Test"
            };
            var account4 = new Account()
            {
                Id = Guid.NewGuid(), Name = "4 Test"
            };
            var account5 = new Account()
            {
                Id = Guid.NewGuid(), Name = "5 Test"
            };
            var account6 = new Account()
            {
                Id = Guid.NewGuid(), Name = "6 Test"
            };
            var account7 = new Account()
            {
                Id = Guid.NewGuid()
            };
            var account8 = new Account()
            {
                Id = Guid.NewGuid(), Name = null
            };
            var account9 = new Account()
            {
                Id = Guid.NewGuid(), Name = "Another name"
            };

            List <Account> initialAccs = new List <Account>()
            {
                account1, account2, account3, account4, account5, account6, account7, account8, account9
            };

            context.Initialize(initialAccs);

            QueryExpression query = new QueryExpression()
            {
                EntityName = "account",
                ColumnSet  = new ColumnSet(true),
                Criteria   = new FilterExpression()
                {
                    Conditions =
                    {
                        new ConditionExpression("name", ConditionOperator.Null)
                    }
                }
            };

            EntityCollection ec = service.RetrieveMultiple(query);

            Assert.True(ec.Entities.Count == 2);
        }
예제 #18
0
        public void OnPreValidateAssocoateOwnerTeamCheckTeamExists_Success()
        {
            //Ok, this is going to be our test method body

            //But before doing anything...

            //  FakeXrmEasy is based on the state-based testing paradigm, 
            //  which is made of, roughly, 3 easy steps:

            //1) We define the initial state of our test.

            //2) Then, we execute the piece of logic which we want to test, 
            //   which will produce a new state, the final state.

            //3) Finally, we verify that the final state is the expected state (assertions).

            //Let's implement those now

            // 1) Define the initial state
            // -----------------------------------------------------------------------

            //  Our initial state is going to be stored in what we call a faked context:

            var context = new XrmFakedContext();

            //You can think of a context like an Organisation database which stores entities In Memory.

            //We can also use TypedEntities but we need to tell the context where to look for them, 
            //this could be done, easily, like this:

            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            //We have to define our initial state now, 
            //by calling the Initialize method, which expects a list of entities.

            var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" };

            context.Initialize(new List<Entity>() {
                account
            });

            //With the above example, we initialized our context with a single account record

            // 2) Execute our logic
            // -----------------------------------------------------------------------
            //
            // We need to get a faked organization service first, by calling this method:

            var service = context.GetOrganizationService();

            // That line is the most powerful functionality of FakeXrmEasy
            // That method has returned a reference to an OrganizationService 
            // which you could pass to your plugins, codeactivities, etc, 
            // and, from now on, every create, update, delete, even queries, etc
            // will be reflected in our In Memory context

            // In a nutshell, everything is already mocked for you... cool, isn't it?

            // Now... 

            // To illustrate this...

            // Let's say we have a super simple piece of logic which updates an account's name

            // Let's do it!

            var accountToUpdate = new Account() { Id = account.Id };
            accountToUpdate.Name = "A new faked name!";

            service.Update(accountToUpdate);

            // Done!

            //We have successfully executed the code we want to test..

            // Now...

            // The final step is...

            // 3) Verify final state is the expected state
            // -----------------------------------------------------------------------
            //

            //We are going to use Xunit assertions.

            var updatedAccountName = context.CreateQuery<Account>()
                                    .Where(e => e.Id == account.Id)
                                    .Select(a => a.Name)
                                    .FirstOrDefault();


            //And finally, validate the account has the expected name
            Assert.Equals("A new faked name!", updatedAccountName);

            // And we are DONE!

            // We have successfully implemented our first test!
        }
예제 #19
0
        public void MultipleSourcesOfMetadata_SchemaImported()
        {
            var fakedContext = new XrmFakedContext();

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

            Guid   targetGuid = Guid.Parse("f0205357-124a-4b5a-9163-5cca2b3d3e8d");
            Entity AccountWithExternalLookup = new Entity("account", Guid.Parse("832193cb-f381-47c0-b059-662bdfcf1261"));

            AccountWithExternalLookup["createdby"] = new EntityReference("systemuser", targetGuid);

            Entity SystemUser = new Entity("systemuser", Guid.Parse("16b8a7ea-7d3f-4856-85a1-59f98ffcfafe"));

            SystemUser["firstname"] = "Andrew";
            SystemUser["lastname"]  = "Vogel";

            fakedContext.Initialize(new List <Entity>()
            {
                AccountWithExternalLookup, SystemUser
            });
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var logicalName    = ((RetrieveEntityRequest)req).LogicalName;
                var entityMetadata = fakedContext.GetEntityMetadataByName(logicalName);

                switch (entityMetadata.LogicalName)
                {
                case SupportMethods.AccountLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.AccountDisplayName, 1033);
                    entityMetadata.Attributes.First(a => a.LogicalName == "createdby").SetSealedPropertyValue("DisplayName", new Label("Created By", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "createdby").SetSealedPropertyValue("Targets", new String[] { "contact" });
                    entityMetadata.Attributes.First(a => a.LogicalName == "accountid").SetSealedPropertyValue("DisplayName", new Label("Account", 1033));
                    break;

                case SupportMethods.UserLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.UserDisplayName, 1033);
                    entityMetadata.Attributes.First(a => a.LogicalName == "firstname").SetSealedPropertyValue("DisplayName", new Label("First Name", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "lastname").SetSealedPropertyValue("DisplayName", new Label("Last Name", 1033));
                    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");
                    break;

                case SupportMethods.ThemeLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ThemeDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "themeid").SetSealedPropertyValue("DisplayName", new Label("Theme", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "isdefaulttheme").SetSealedPropertyValue("DisplayName", new Label("Default Theme", 1033));
                    break;

                case SupportMethods.IncidentLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.IncidentDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "title");
                    entityMetadata.Attributes.First(a => a.LogicalName == "incidentid").SetSealedPropertyValue("DisplayName", new Label("Case", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("DisplayName", new Label("Customer", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Customer);
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("Targets", new String[] { "account", "contact" });
                    break;

                case SupportMethods.ResourceRequirementDetailLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ResourceRequirementDetailDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "msdyn_name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_hours").SetSealedPropertyValue("DisplayName", new Label("Hours", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_hours").SetSealedPropertyValue("IsCustomAttribute", true);
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_resourcerequirementdetailid").SetSealedPropertyValue("DisplayName", new Label("Resource Requirement Detail", 1033));
                    break;

                case SupportMethods.PurchaseOrderProductLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.PurchaseOrderProductDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "msdyn_name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_quantity").SetSealedPropertyValue("DisplayName", new Label("Quantity", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_quantity").SetSealedPropertyValue("IsCustomAttribute", true);
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_purchaseorderproductid").SetSealedPropertyValue("DisplayName", new Label("Purchase Order Product", 1033));
                    break;

                case SupportMethods.InvoiceLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.InvoiceDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "invoiceid").SetSealedPropertyValue("DisplayName", new Label("Invoice", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "totaltax").SetSealedPropertyValue("DisplayName", new Label("Total Tax", 1033));
                    break;

                case SupportMethods.ApprovalLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ApprovalDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "subject");
                    entityMetadata.Attributes.First(a => a.LogicalName == "activityid").SetSealedPropertyValue("DisplayName", new Label("Activity", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customers").SetSealedPropertyValue("DisplayName", new Label("Customers", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customers").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.PartyList);
                    break;

                case SupportMethods.SecurityRoleLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.SecurityRoleDisplayName, 1033);
                    entityMetadata.Attributes.First(a => a.LogicalName == "roleid").SetSealedPropertyValue("DisplayName", new Label("Role", 1033));
                    break;

                case SupportMethods.KnowledgeArticleLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.KnowledgeArticleDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "title");
                    entityMetadata.Attributes.First(a => a.LogicalName == "keywords").SetSealedPropertyValue("DisplayName", new Label("Keywords", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "keywords").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Memo);
                    entityMetadata.Attributes.First(a => a.LogicalName == "knowledgearticleid").SetSealedPropertyValue("DisplayName", new Label("Knowledge Article", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "publishon").SetSealedPropertyValue("DisplayName", new Label("Publish On", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "expirationstateid").SetSealedPropertyValue("DisplayName", new Label("Expiration State Id", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "previousarticlecontentid").SetSealedPropertyValue("DisplayName", new Label("Previous Article Content ID", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "previousarticlecontentid").SetSealedPropertyValue("Targets", new String[] { "knowledgearticle" });
                    entityMetadata.Attributes.First(a => a.LogicalName == "ownerid").SetSealedPropertyValue("DisplayName", new Label("Owner", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "ownerid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Owner);
                    entityMetadata.Attributes.First(a => a.LogicalName == "expiredreviewoptions").SetSealedPropertyValue("DisplayName", new Label("Expired Review Options", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "statecode").SetSealedPropertyValue("DisplayName", new Label("Status", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "statuscode").SetSealedPropertyValue("DisplayName", new Label("Status Reason", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "stageid").SetSealedPropertyValue("DisplayName", new Label("Stage Id", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "stageid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Uniqueidentifier);
                    entityMetadata.Attributes.First(a => a.LogicalName == "description").SetSealedPropertyValue("DisplayName", new Label("Short Description", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "articlepublicnumber").SetSealedPropertyValue("DisplayName", new Label("Article Public Number", 1033));
                    break;

                default:
                    break;
                }

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder db = new DataBuilder(fakedService);

            db.AppendData("<fetch><entity name='account'><attribute name='accountid'/><attribute name='createdby'/></entity></fetch>");

            db.AppendData(SupportMethods.GetBooleanTypeExpectedData(), SupportMethods.GetBooleanTypeExpectedSchema());
            db.AppendData(SupportMethods.GetCustomerTypeExpectedData(), SupportMethods.GetCustomerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDateTimeTypeExpectedData(), SupportMethods.GetDateTimeTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDecimalTypeExpectedData(), SupportMethods.GetDecimalTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDoubleTypeExpectedData(), SupportMethods.GetDoubleTypeExpectedSchema());
            db.AppendData(SupportMethods.GetIntegerTypeExpectedData(), SupportMethods.GetIntegerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetLookupTypeExpectedData(), SupportMethods.GetLookupTypeExpectedSchema());
            db.AppendData(SupportMethods.GetMemoTypeExpectedData(), SupportMethods.GetMemoTypeExpectedSchema());
            db.AppendData(SupportMethods.GetMoneyTypeExpectedData(), SupportMethods.GetMoneyTypeExpectedSchema());
            db.AppendData(SupportMethods.GetOwnerTypeExpectedData(), SupportMethods.GetOwnerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetPartyListTypeExpectedData(), SupportMethods.GetPartyListTypeExpectedSchema());
            db.AppendData(SupportMethods.GetPicklistTypeExpectedData(), SupportMethods.GetPicklistTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStateTypeExpectedData(), SupportMethods.GetStateTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStatusTypeExpectedData(), SupportMethods.GetStatusTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStringTypeExpectedData(), SupportMethods.GetStringTypeExpectedSchema());
            db.AppendData(SupportMethods.GetUniqueIdentifierTypeExpectedData(), SupportMethods.GetUniqueIdentifierTypeExpectedSchema());
            db.AppendData(SupportMethods.Getm2mRelationshipTypeExpectedData(), SupportMethods.Getm2mRelationshipTypeExpectedSchema());

            db.AppendData("<fetch><entity name='systemuser'><attribute name='systemuserid'/><attribute name='firstname'/><attribute name='lastname'/></entity></fetch>");

            db.SetIdentifier("systemuser", "systemuserid");

            Assert.AreEqual(
                db.BuildSchemaXML().InnerXml,
                SupportMethods.LoadXmlFile("../../lib/Configurations/MultipleSourcesOfMetadata_schema.xml"));
        }
예제 #20
0
        public void MultipleSourcesOfMetadata_DataImported()
        {
            var fakedContext = new XrmFakedContext();

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

            Guid   targetGuid = Guid.Parse("f0205357-124a-4b5a-9163-5cca2b3d3e8d");
            Entity AccountWithExternalLookup = new Entity("account", Guid.Parse("832193cb-f381-47c0-b059-662bdfcf1261"));

            AccountWithExternalLookup["createdby"] = new EntityReference("systemuser", targetGuid);

            Entity SystemUser = new Entity("systemuser", Guid.Parse("16b8a7ea-7d3f-4856-85a1-59f98ffcfafe"));

            SystemUser["firstname"] = "Andrew";
            SystemUser["lastname"]  = "Vogel";

            fakedContext.Initialize(new List <Entity>()
            {
                AccountWithExternalLookup, SystemUser
            });
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var logicalName    = ((RetrieveEntityRequest)req).LogicalName;
                var entityMetadata = fakedContext.GetEntityMetadataByName(logicalName);

                switch (entityMetadata.LogicalName)
                {
                case SupportMethods.AccountLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.AccountDisplayName, 1033);
                    entityMetadata.Attributes.First(a => a.LogicalName == "createdby").SetSealedPropertyValue("DisplayName", new Label("Created By", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "createdby").SetSealedPropertyValue("Targets", new String[] { "contact" });
                    entityMetadata.Attributes.First(a => a.LogicalName == "accountid").SetSealedPropertyValue("DisplayName", new Label("Account", 1033));
                    break;

                case SupportMethods.UserLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.UserDisplayName, 1033);
                    entityMetadata.Attributes.First(a => a.LogicalName == "firstname").SetSealedPropertyValue("DisplayName", new Label("First Name", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "lastname").SetSealedPropertyValue("DisplayName", new Label("Last Name", 1033));
                    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");
                    break;

                case SupportMethods.ThemeLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ThemeDisplayName, 1033);
                    break;

                case SupportMethods.IncidentLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.IncidentDisplayName, 1033);
                    break;

                case SupportMethods.ResourceRequirementDetailLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ResourceRequirementDetailDisplayName, 1033);
                    break;

                case SupportMethods.PurchaseOrderProductLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.PurchaseOrderProductDisplayName, 1033);
                    break;

                case SupportMethods.InvoiceLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.InvoiceDisplayName, 1033);
                    break;

                case SupportMethods.ApprovalLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ApprovalDisplayName, 1033);
                    break;

                case SupportMethods.SecurityRoleLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.SecurityRoleDisplayName, 1033);
                    break;

                default:
                    break;
                }

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder db = new DataBuilder(fakedService);

            db.AppendData("<fetch><entity name='account'><attribute name='accountid'/><attribute name='createdby'/></entity></fetch>");

            db.AppendData(SupportMethods.GetBooleanTypeExpectedData(), SupportMethods.GetBooleanTypeExpectedSchema());
            db.AppendData(SupportMethods.GetCustomerTypeExpectedData(), SupportMethods.GetCustomerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDateTimeTypeExpectedData(), SupportMethods.GetDateTimeTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDecimalTypeExpectedData(), SupportMethods.GetDecimalTypeExpectedSchema());
            db.AppendData(SupportMethods.GetDoubleTypeExpectedData(), SupportMethods.GetDoubleTypeExpectedSchema());
            db.AppendData(SupportMethods.GetIntegerTypeExpectedData(), SupportMethods.GetIntegerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetLookupTypeExpectedData(), SupportMethods.GetLookupTypeExpectedSchema());
            db.AppendData(SupportMethods.GetMemoTypeExpectedData(), SupportMethods.GetMemoTypeExpectedSchema());
            db.AppendData(SupportMethods.GetMoneyTypeExpectedData(), SupportMethods.GetMoneyTypeExpectedSchema());
            db.AppendData(SupportMethods.GetOwnerTypeExpectedData(), SupportMethods.GetOwnerTypeExpectedSchema());
            db.AppendData(SupportMethods.GetPartyListTypeExpectedData(), SupportMethods.GetPartyListTypeExpectedSchema());
            db.AppendData(SupportMethods.GetPicklistTypeExpectedData(), SupportMethods.GetPicklistTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStateTypeExpectedData(), SupportMethods.GetStateTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStatusTypeExpectedData(), SupportMethods.GetStatusTypeExpectedSchema());
            db.AppendData(SupportMethods.GetStringTypeExpectedData(), SupportMethods.GetStringTypeExpectedSchema());
            db.AppendData(SupportMethods.GetUniqueIdentifierTypeExpectedData(), SupportMethods.GetUniqueIdentifierTypeExpectedSchema());
            db.AppendData(SupportMethods.Getm2mRelationshipTypeExpectedData(), SupportMethods.Getm2mRelationshipTypeExpectedSchema());

            db.AppendData("<fetch><entity name='systemuser'><attribute name='systemuserid'/><attribute name='firstname'/><attribute name='lastname'/></entity></fetch>");

            db.SetIdentifier("systemuser", "systemuserid");

            Assert.AreEqual(
                db.BuildDataXML().InnerXml,
                SupportMethods.LoadXmlFile("../../lib/Configurations/MultipleSourcesOfMetadata_data.xml"));
        }
예제 #21
0
        public void AllEntities_SomePluginsDisabled_MixedIdentifiers()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly);
            fakedContext.Initialize(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersEntity());
            fakedContext.AddExecutionMock <RetrieveEntityRequest>(req =>
            {
                var logicalName    = ((RetrieveEntityRequest)req).LogicalName;
                var entityMetadata = fakedContext.GetEntityMetadataByName(logicalName);

                switch (entityMetadata.LogicalName)
                {
                case SupportMethods.ApprovalLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ApprovalDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "subject");
                    entityMetadata.Attributes.First(a => a.LogicalName == "activityid").SetSealedPropertyValue("DisplayName", new Label("Activity", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customers").SetSealedPropertyValue("DisplayName", new Label("Customers", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customers").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.PartyList);
                    break;

                case SupportMethods.IncidentLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.IncidentDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "title");
                    entityMetadata.Attributes.First(a => a.LogicalName == "incidentid").SetSealedPropertyValue("DisplayName", new Label("Case", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("DisplayName", new Label("Customer", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Customer);
                    entityMetadata.Attributes.First(a => a.LogicalName == "customerid").SetSealedPropertyValue("Targets", new String[] { "account", "contact" });
                    break;

                case SupportMethods.InvoiceLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.InvoiceDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "invoiceid").SetSealedPropertyValue("DisplayName", new Label("Invoice", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "totaltax").SetSealedPropertyValue("DisplayName", new Label("Total Tax", 1033));
                    break;

                case SupportMethods.KnowledgeArticleLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.KnowledgeArticleDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "title");
                    entityMetadata.Attributes.First(a => a.LogicalName == "keywords").SetSealedPropertyValue("DisplayName", new Label("Keywords", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "keywords").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Memo);
                    entityMetadata.Attributes.First(a => a.LogicalName == "knowledgearticleid").SetSealedPropertyValue("DisplayName", new Label("Knowledge Article", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "publishon").SetSealedPropertyValue("DisplayName", new Label("Publish On", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "expirationstateid").SetSealedPropertyValue("DisplayName", new Label("Expiration State Id", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "previousarticlecontentid").SetSealedPropertyValue("DisplayName", new Label("Previous Article Content ID", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "previousarticlecontentid").SetSealedPropertyValue("Targets", new String[] { "knowledgearticle" });
                    entityMetadata.Attributes.First(a => a.LogicalName == "ownerid").SetSealedPropertyValue("DisplayName", new Label("Owner", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "ownerid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Owner);
                    entityMetadata.Attributes.First(a => a.LogicalName == "expiredreviewoptions").SetSealedPropertyValue("DisplayName", new Label("Expired Review Options", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "statecode").SetSealedPropertyValue("DisplayName", new Label("Status", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "statuscode").SetSealedPropertyValue("DisplayName", new Label("Status Reason", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "stageid").SetSealedPropertyValue("DisplayName", new Label("Stage Id", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "stageid").SetSealedPropertyValue("AttributeType", Sdk.Metadata.AttributeTypeCode.Uniqueidentifier);
                    entityMetadata.Attributes.First(a => a.LogicalName == "description").SetSealedPropertyValue("DisplayName", new Label("Short Description", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "articlepublicnumber").SetSealedPropertyValue("DisplayName", new Label("Article Public Number", 1033));
                    break;

                case SupportMethods.PurchaseOrderProductLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.PurchaseOrderProductDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "msdyn_name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_quantity").SetSealedPropertyValue("DisplayName", new Label("Quantity", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_quantity").SetSealedPropertyValue("IsCustomAttribute", true);
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_purchaseorderproductid").SetSealedPropertyValue("DisplayName", new Label("Purchase Order Product", 1033));
                    break;

                case SupportMethods.ResourceRequirementDetailLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ResourceRequirementDetailDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "msdyn_name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_hours").SetSealedPropertyValue("DisplayName", new Label("Hours", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_hours").SetSealedPropertyValue("IsCustomAttribute", true);
                    entityMetadata.Attributes.First(a => a.LogicalName == "msdyn_resourcerequirementdetailid").SetSealedPropertyValue("DisplayName", new Label("Resource Requirement Detail", 1033));
                    break;

                case SupportMethods.ThemeLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.ThemeDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "themeid").SetSealedPropertyValue("DisplayName", new Label("Theme", 1033));
                    entityMetadata.Attributes.First(a => a.LogicalName == "isdefaulttheme").SetSealedPropertyValue("DisplayName", new Label("Default Theme", 1033));
                    break;

                default:
                    break;
                }

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

            IOrganizationService fakedService = fakedContext.GetOrganizationService();

            DataBuilder DataBuilder = new DataBuilder(fakedService);

            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersThemeFetch());
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersIncidentFetch());
            DataBuilder.SetPluginsDisabled("incident", true);
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersKnowledgeArticleFetch());
            DataBuilder.SetIdentifier(SupportMethods.KnowledgeArticleLogicalName, "articlepublicnumber");
            DataBuilder.SetPluginsDisabled("knowledgearticle", true);
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersResourceRequirementDetailFetch());
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersPurchaseOrderProductFetch());
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersInvoiceFetch());
            DataBuilder.AppendData(SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersApprovalFetch());
            Assert.AreEqual(
                DataBuilder.BuildSchemaXML().InnerXml,
                SupportMethods.GetAllEntities_SomePluginsDisabled_MixedIdentifiersExpectedSchema());
        }
예제 #22
0
        public void When_There_Are_Multiple_LinkedEntities_With_The_Same_Entitiy_And_One_Has_An_Alias_The_Output_EntityAlias_Should_All_Be_Suffixed_With_Incrementally_Ignoring_The_Aliased_One()
        {
            var context = new XrmFakedContext();
            var service = context.GetOrganizationService();

            var entities = new List <Entity>();

            var user1 = new SystemUser
            {
                Id           = Guid.NewGuid(),
                ["fullname"] = "User1"
            };

            entities.Add(user1);

            var user2 = new SystemUser
            {
                Id             = Guid.NewGuid(),
                ["fullname"]   = "User2",
                ["modifiedby"] = user1.ToEntityReference()
            };

            entities.Add(user2);

            var user3 = new SystemUser
            {
                Id             = Guid.NewGuid(),
                ["fullname"]   = "User3",
                ["modifiedby"] = user2.ToEntityReference()
            };

            entities.Add(user3);

            var user4 = new SystemUser
            {
                Id             = Guid.NewGuid(),
                ["fullname"]   = "User4",
                ["modifiedby"] = user3.ToEntityReference()
            };

            entities.Add(user4);

            context.Initialize(entities);

            var query = new QueryExpression(SystemUser.EntityLogicalName)
            {
                LinkEntities =
                {
                    new LinkEntity(SystemUser.EntityLogicalName,                 SystemUser.EntityLogicalName, "modifiedby", "systemuserid", JoinOperator.Inner)
                    {
                        Columns      = new ColumnSet("fullname"),
                        LinkEntities =
                        {
                            new LinkEntity(SystemUser.EntityLogicalName,         SystemUser.EntityLogicalName,         "modifiedby", "systemuserid", JoinOperator.Inner)
                            {
                                EntityAlias  = "systemuserwithalias",
                                Columns      = new ColumnSet("fullname"),
                                LinkEntities =
                                {
                                    new LinkEntity(SystemUser.EntityLogicalName, SystemUser.EntityLogicalName, "modifiedby",         "systemuserid", JoinOperator.Inner)
                                    {
                                        Columns = new ColumnSet("fullname")
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var result          = service.RetrieveMultiple(query);
            var resultingEntity = result.Entities[0];

            Assert.Equal(3, resultingEntity.Attributes.Count);
            Assert.Equal("User3", ((AliasedValue)resultingEntity["systemuser1.fullname"]).Value);
            Assert.Equal("User2", ((AliasedValue)resultingEntity["systemuserwithalias.fullname"]).Value);
            Assert.Equal("User1", ((AliasedValue)resultingEntity["systemuser2.fullname"]).Value);
        }
        public static void When_using_proxy_types_assembly_multi_select_option_set_metadata_is_inferred_from_injected_metadata_as_a_fallback()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var record1 = new Entity("contact")
            {
                Id = Guid.NewGuid(),
                ["new_injectedmultiselectoptionset"] = new OptionSetValueCollection(
                    new[]
                {
                    new OptionSetValue(100001),
                    new OptionSetValue(100002)
                })
            };

            var record2 = new Entity("contact")
            {
                Id = Guid.NewGuid(),
                ["new_injectedmultiselectoptionset"] = new OptionSetValueCollection(
                    new[]
                {
                    new OptionSetValue(100002),
                    new OptionSetValue(100003)
                })
            };

            fakedContext.Initialize(new List <Entity>()
            {
                record1, record2
            });

            var entityMetadata = new EntityMetadata()
            {
                LogicalName = "contact"
            };

            var injectedAttribute = new MultiSelectPicklistAttributeMetadata()
            {
                LogicalName = "new_injectedmultiselectoptionset"
            };

            entityMetadata.SetAttribute(injectedAttribute);
            fakedContext.InitializeMetadata(entityMetadata);

            var guid = Guid.NewGuid();

            //Empty context (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetOrganizationService();

            var contacts = service.RetrieveMultiple(new QueryExpression(Contact.EntityLogicalName)
            {
                Criteria = new FilterExpression()
                {
                    Conditions =
                    {
                        new ConditionExpression("new_injectedmultiselectoptionset", ConditionOperator.In, new[] { 100002, 100003 })
                    }
                }
            });

            Assert.True(contacts.Entities.Count == 1);
        }
예제 #24
0
        public void m2mRelationshipType()
        {
            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 logicalName    = ((RetrieveEntityRequest)req).LogicalName;
                var entityMetadata = fakedContext.GetEntityMetadataByName(logicalName);

                switch (entityMetadata.LogicalName)
                {
                case 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");
                    break;

                case SupportMethods.SecurityRoleLogicalName:
                    entityMetadata.DisplayName = new Label(SupportMethods.SecurityRoleDisplayName, 1033);
                    entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name");
                    entityMetadata.Attributes.First(a => a.LogicalName == "roleid").SetSealedPropertyValue("DisplayName", new Label("Role", 1033));
                    break;

                default:
                    break;
                }

                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-000d3a192311'/></filter></entity></fetch>");

            var dataXml = DataBuilder.BuildDataXML();

            Assert.AreEqual(
                dataXml.InnerXml,
                SupportMethods.Getm2mRelationshipTypeExpectedData());
        }
예제 #25
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as InitializeFromRequest;

            if (req == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Cannot execute InitializeFromRequest without the request");
            }

            //TODO: Implement logic to filter mapping attributes based on the req.TargetFieldType
            if (req.TargetFieldType != TargetFieldType.All)
            {
                throw PullRequestException.PartiallyNotImplementedOrganizationRequest(req.GetType(), "logic for filtering attributes based on TargetFieldType other than All is missing");
            }

            var service          = ctx.GetOrganizationService();
            var fetchXml         = string.Format(FetchMappingsByEntity, req.EntityMoniker.LogicalName, req.TargetEntityName);
            var mapping          = service.RetrieveMultiple(new FetchExpression(fetchXml));
            var sourceAttributes = mapping.Entities.Select(a => a.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString()).ToArray();
            var columnSet        = sourceAttributes.Length == 0 ? new ColumnSet(true) : new ColumnSet(sourceAttributes);
            var source           = service.Retrieve(req.EntityMoniker.LogicalName, req.EntityMoniker.Id, columnSet);

            var entity = new Entity
            {
                LogicalName = req.TargetEntityName,
                Id          = Guid.Empty
            };

            if (mapping.Entities.Count > 0)
            {
                foreach (var attr in source.Attributes)
                {
                    var mappingEntity = mapping.Entities.FirstOrDefault(e => e.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString() == attr.Key);
                    if (mappingEntity == null)
                    {
                        continue;
                    }
                    var targetAttribute = mappingEntity.GetAttributeValue <AliasedValue>("attributemap.targetattributename").Value.ToString();
                    entity[targetAttribute] = attr.Value;

                    var isEntityReference = string.Equals(attr.Key, source.LogicalName + "id", StringComparison.CurrentCultureIgnoreCase);
                    if (isEntityReference)
                    {
                        entity[targetAttribute] = new EntityReference(source.LogicalName, (Guid)attr.Value);
                    }
                    else
                    {
                        entity[targetAttribute] = attr.Value;
                    }
                }
            }

            var response = new InitializeFromResponse
            {
                Results =
                {
                    ["Entity"] = entity
                }
            };

            return(response);
        }
        public void Setp()
        {
            fakedContext      = new XrmFakedContext();
            trace             = new TestTracingService();
            service           = fakedContext.GetOrganizationService();
            fakedContext.Data = new Dictionary <string, Dictionary <Guid, Entity> >();

            #region Roles
            var roles    = new Dictionary <Guid, Entity>();
            var sysAdmin = new Entity("role");
            sysAdmin["roleid"] = sysAdminId;
            sysAdmin["name"]   = "System Administrator";
            sysAdmin.Id        = sysAdminId;
            roles.Add(sysAdminId, sysAdmin);

            var sysCustomizer = new Entity("role");
            sysCustomizer["roleid"] = sysAdminId;
            sysCustomizer["name"]   = "System Customizer";
            sysCustomizer.Id        = sysCustomizerId;
            roles.Add(sysCustomizerId, sysCustomizer);

            #endregion roles

            #region Users
            var users = new Dictionary <Guid, Entity>();

            var u2 = new Entity("systemuser");
            u2["systemuserid"] = u2Id;
            users.Add(u2Id, u2);

            var u1 = new Entity("systemuser");
            u1["systemuserid"] = u1Id;
            users.Add(u1Id, u1);

            #endregion Users

            #region  system user roles
            var systemUserRoles = new Dictionary <Guid, Entity>();

            #region user 2
            var u2SysAdmin = new Entity("systemuserroles");
            u2SysAdmin["systemuserid"] = new EntityReference("systemuser", u2Id);
            u2SysAdmin["roleid"]       = new EntityReference("role", sysAdminId);
            var u2SysAdminId = Guid.NewGuid();
            u2SysAdmin["systemuserroleid"] = u2SysAdminId;
            systemUserRoles.Add(u2SysAdminId, u2SysAdmin);

            var u2SysCustomizer = new Entity("systemuserroles");
            u2SysCustomizer["systemuserid"] = new EntityReference("systemuser", u1Id);
            u2SysCustomizer["roleid"]       = new EntityReference("role", sysCustomizerId);
            var u2SysCustomizerId = Guid.NewGuid();
            u2SysCustomizer["systemuserroleid"] = u2SysCustomizerId;
            systemUserRoles.Add(u2SysCustomizerId, u2SysCustomizer);

            #endregion user 2

            #endregion system user roles

            fakedContext.Data.Add("role", roles);
            fakedContext.Data.Add("systemuser", users);
            fakedContext.Data.Add("systemuserroles", systemUserRoles);
        }
예제 #27
0
        public void When_I_run_connection_fetchXml_it_should_return_all_matching_record1id()
        {
            // Arrange
            // Create Contacts
            var contact = new Entity("contact");

            contact.Id = Guid.NewGuid();
            contact.Attributes.Add("firstname", "First");
            contact.Attributes.Add("lastname", "User");
            contact.Attributes.Add("statecode", new OptionSetValue(0));

            // Create Other User
            var otherContact = new Entity("contact");

            otherContact.Id = Guid.NewGuid();
            otherContact.Attributes.Add("firstname", "Other");
            otherContact.Attributes.Add("lastname", "User");
            otherContact.Attributes.Add("statecode", new OptionSetValue(0));

            // Connection Role
            var conRole = new Entity("connectionrole");

            conRole.Id = Guid.NewGuid();
            conRole.Attributes.Add("name", "Contact");
            conRole.Attributes.Add("statecode", new OptionSetValue(0));

            // Create connection with disclosure AND CONTACT
            var conn = new Entity("connection");

            conn.Id = Guid.NewGuid();
            conn.Attributes.Add("record1id", contact.ToEntityReference());      // discloser
            conn.Attributes.Add("record2id", otherContact.ToEntityReference()); // contact
            conn.Attributes.Add("record2roleid", conRole.ToEntityReference());  // Connection Role
            conn.Attributes.Add("statecode", new OptionSetValue(0));

            // Create Faked Context
            var ctx = new XrmFakedContext();

            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Connection));
            //ctx.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            ctx.Initialize(new List <Entity>()
            {
                contact, otherContact, conRole, conn
            });

            // Fetch Xml
            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                      <entity name='connection'>
                                                        <attribute name='record2id' />
                                                        <attribute name='record2roleid' />
                                                        <attribute name='connectionid' />
                                                        <attribute name='record1id' />
                                                        <filter type='and'>
                                                          <condition attribute='record1id' operator='eq' uitype='contact' value= '{0}' />
                                                          <condition attribute='statecode' operator='eq' value='0' />
                                                        </filter>
                                                        <link-entity name='contact' from='contactid' to='record2id' alias='ah'>
                                                          <filter type='and'>
                                                            <condition attribute='lastname' operator='not-null' />
                                                            <condition attribute='statecode' operator='eq' value='0' />
                                                          </filter>
                                                        </link-entity>
                                                      </entity>
                                                    </fetch>";

            fetchXml = string.Format(fetchXml, contact.Id);

            // Act
            EntityCollection getConnectionListResults = ctx.GetOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));


            // Assert
            Assert.True(getConnectionListResults.Entities.Count > 0);
        }
예제 #28
0
        private static IOrganizationService Arrange()
        {
            Account account = new Account();

            account.Id   = new Guid("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
            account.Name = "Goggle ltd";

            Contact contact = new Contact();

            contact.Id               = new Guid("cccccccc-cccc-cccc-cccc-cccccccccccc");
            contact.FirstName        = "Test";
            contact.LastName         = "Contact 1";
            contact.ParentCustomerId = account.ToEntityReference();

            gbp_globecountry country = new gbp_globecountry()
            {
                Id       = Guid.NewGuid(),
                gbp_name = "United Kingdom",
                gbp_code = "GB"
            };

            gbp_customaddress customAddress = new gbp_customaddress()
            {
                Id = new Guid("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
                gbp_addresstype = new OptionSetValue(3),
                gbp_country     = country.ToEntityReference(),
            };
            var ugh = new gbp_gbp_customaddress_contact()
            {
                Id = new Guid("12345678-0000-0000-0000-000000000000")
            };

            ugh.Attributes["contactid"]           = contact.Id;
            ugh.Attributes["gbp_customaddressid"] = customAddress.Id;

            var context = new XrmFakedContext();

            context.AddRelationship("gbp_gbp_customaddress_contact",
                                    new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.ManyToMany,
                IntersectEntity    = "gbp_gbp_customaddress_contact",
                Entity1LogicalName = gbp_customaddress.EntityLogicalName,
                Entity1Attribute   = "gbp_customaddressid",
                Entity2LogicalName = Contact.EntityLogicalName,
                Entity2Attribute   = "contactid"
            });


            /*
             * this doen't work, need to step through the code to see what the query is doing
             * or maybe determine if it's an n:1
             */
            context.AddRelationship("contact_customer_accounts",
                                    new XrmFakedRelationship()
            {
                RelationshipType   = XrmFakedRelationship.enmFakeRelationshipType.OneToMany,
                IntersectEntity    = "contact_customer_accounts",
                Entity1LogicalName = Contact.EntityLogicalName,
                Entity1Attribute   = "parentcustomerid",
                Entity2LogicalName = Account.EntityLogicalName,
                Entity2Attribute   = "accountid",
            });


            context.Initialize(new List <Entity>()
            {
                account, contact, customAddress, ugh
            });

            var fakedService = context.GetOrganizationService();

            return(fakedService);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as QualifyLeadRequest;

            var orgService = ctx.GetOrganizationService();

            if (req.LeadId == null)
            {
                throw new Exception("Lead Id must be set in request.");
            }

            var leads = (from l in ctx.CreateQuery("lead")
                         where l.Id == req.LeadId.Id
                         select l);

            var leadsCount = leads.Count();

            if (leadsCount != 1)
            {
                throw new Exception(string.Format("Number of Leads by given LeadId should be 1. Instead it is {0}.", leadsCount));
            }

            // Made here to get access to CreatedEntities collection
            var response = new QualifyLeadResponse();

            response["CreatedEntities"] = new EntityReferenceCollection();

            // Create Account
            if (req.CreateAccount) // ParentAccount
            {
                var account = new Entity("account")
                {
                    Id = Guid.NewGuid()
                };
                account.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(account);
                response.CreatedEntities.Add(account.ToEntityReference());
            }

            // Create Contact
            if (req.CreateContact)
            {
                var contact = new Entity("contact")
                {
                    Id = Guid.NewGuid()
                };
                contact.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(contact);
                response.CreatedEntities.Add(contact.ToEntityReference());
            }

            // Create Opportunity
            if (req.CreateOpportunity)
            {
                var opportunity = new Entity("opportunity")
                {
                    Id = Guid.NewGuid()
                };

                // Set OpportunityCurrencyId if given
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycurrencyid.aspx
                if (req.OpportunityCurrencyId != null)
                {
                    opportunity.Attributes["transactioncurrencyid"] = req.OpportunityCurrencyId;
                }

                // Associate Account or Contact with Opportunity
                // MSDN link:
                // https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest.opportunitycustomerid.aspx
                if (req.OpportunityCustomerId != null)
                {
                    var logicalName = req.OpportunityCustomerId.LogicalName;

                    // Associate Account or Contact
                    if (logicalName.Equals("account") || logicalName.Equals("contact"))
                    {
                        opportunity.Attributes["customerid"] = req.OpportunityCustomerId;
                    }
                    // Wrong Entity was given as parameter
                    else
                    {
                        throw new Exception(string.Format("Opportunity Customer Id should be connected with Account or Contact. Instead OpportunityCustomerId was given with Entity.LogicalName = {0}", logicalName));
                    }
                }

                opportunity.Attributes["originatingleadid"] = req.LeadId;
                orgService.Create(opportunity);
                response.CreatedEntities.Add(opportunity.ToEntityReference());
            }

            // Actual Lead
            var lead = leads.First();

            lead.Attributes["statuscode"] = new OptionSetValue(req.Status.Value);
            orgService.Update(lead);

            return(response);
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var service = ctx.GetOrganizationService();

            var reviseQuoteRequest = request as ReviseQuoteRequest;

            if (reviseQuoteRequest == null)
            {
                throw new Exception("You did not pass a ReviseQuoteRequest!");
            }

            var oldQuoteId = reviseQuoteRequest.QuoteId;

            if (oldQuoteId == Guid.Empty)
            {
                throw new Exception("QuoteId needs to be set!");
            }

            var oldQuote = service.Retrieve("quote", oldQuoteId, new ColumnSet(true));

            var revisedQuote = new Entity
            {
                LogicalName = "quote",
                Id          = Guid.NewGuid()
            };

            var columnSet      = reviseQuoteRequest.ColumnSet;
            var quoteBlackList = new List <string> {
                "quoteid", "statuscode", "statecode", "createdon", "createdby"
            };

            foreach (var attribute in oldQuote.Attributes)
            {
                if (quoteBlackList.Contains(attribute.Key))
                {
                    continue;
                }

                if (columnSet.AllColumns || columnSet.Columns.Contains(attribute.Key))
                {
                    revisedQuote[attribute.Key] = attribute.Value;
                }
            }

            service.Create(revisedQuote);

            var quoteLines = service.RetrieveMultiple(new QueryExpression("quotedetail")
            {
                ColumnSet = new ColumnSet(true),
                Criteria  = new FilterExpression(LogicalOperator.And)
                {
                    Conditions = { new ConditionExpression("quoteid", ConditionOperator.Equal, oldQuote.ToEntityReference()) }
                }
            }).Entities.ToList();

            foreach (var quoteDetail in quoteLines)
            {
                var revisedDetail = new Entity
                {
                    LogicalName = "quotedetail",
                    Id          = Guid.NewGuid(),
                    Attributes  = new AttributeCollection
                    {
                        { "quoteid", revisedQuote.ToEntityReference() }
                    }
                };

                var quoteDetailBlackList = new List <string> {
                    "quoteid", "quotedetailid", "createdon", "createdby"
                };

                foreach (var attribute in quoteDetail.Attributes)
                {
                    if (quoteDetailBlackList.Contains(attribute.Key))
                    {
                        continue;
                    }

                    revisedDetail[attribute.Key] = attribute.Value;
                }

                service.Create(revisedDetail);
            }

            var response = new ReviseQuoteResponse();

            revisedQuote = service.Retrieve(revisedQuote.LogicalName, revisedQuote.Id, new ColumnSet(true));

            response.Results["Entity"] = revisedQuote;

            return(response);
        }