Ejemplo n.º 1
0
        public void When_ordering_by_datetime_fields_expected_result_is_returned()
        {
            List<Entity> contactList = new List<Entity>();

            var now = DateTime.UtcNow;
            Entity contact1 = new Entity("contact");
            contact1.Id = Guid.NewGuid();
            contact1.Attributes["firstname"] = "Fred";
            contact1.Attributes["new_orderbyfield"] = now;

            Entity contact2 = new Entity("contact");
            contact2.Id = Guid.NewGuid();
            contact2.Attributes["firstname"] = "Jo";
            contact2.Attributes["new_orderbyfield"] = now.AddDays(1);

            contactList.Add(contact2);
            contactList.Add(contact1);

            var context = new XrmFakedContext();
            context.Initialize(contactList);
            var service = context.GetFakedOrganizationService();

            QueryExpression qry = new QueryExpression("contact");
            qry.ColumnSet = new ColumnSet(true);
            qry.AddOrder("new_orderbyfield", OrderType.Ascending);
            var results = service.RetrieveMultiple(qry);

            var firstResultValue = (DateTime)results.Entities[0]["new_orderbyfield"];

            Assert.Equal(now, firstResultValue);
        }
        public void When_Executing_Assign_Request_New_Owner_Should_Be_Assigned()
        {
            var oldOwner = new EntityReference("systemuser", Guid.NewGuid());
            var newOwner = new EntityReference("systemuser", Guid.NewGuid());

            var account = new Account
            {
                Id = Guid.NewGuid(),
                OwnerId = oldOwner
            };

            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

            var assignRequest = new AssignRequest
            {
                Target = account.ToEntityReference(),
                Assignee = newOwner
            };
            service.Execute(assignRequest);

            Assert.Equal(newOwner, account.OwnerId);
        }
Ejemplo n.º 3
0
        public void When_set_state_request_is_called_an_entity_is_updated()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var c = new Contact() {
                Id = Guid.NewGuid()
            }; 
            context.Initialize(new[] { c });

            var request = new SetStateRequest
            {
                EntityMoniker = c.ToEntityReference(),
                State = new OptionSetValue(69), 
                Status = new OptionSetValue(6969),
            };

            var response = service.Execute(request);

            //Retrieve record after update
            var contact = (from con in context.CreateQuery<Contact>()
                           where con.Id == c.Id
                           select con).FirstOrDefault();

            Assert.Equal((int) contact.StateCode.Value, 69);
            Assert.Equal((int) contact.StatusCode.Value, 6969);
        }
Ejemplo n.º 4
0
        public void When_ordering_by_money_fields_descending_expected_result_is_returned()
        {
            List<Entity> contactList = new List<Entity>();

            Entity contact1 = new Entity("contact");
            contact1.Id = Guid.NewGuid();
            contact1.Attributes["firstname"] = "Fred";
            contact1.Attributes["lastname"] = "Bloggs";
            contact1.Attributes["new_somefield"] = new Money(12345); // (decimal)678910 

            Entity contact2 = new Entity("contact");
            contact2.Id = Guid.NewGuid();
            contact2.Attributes["firstname"] = "Jo";
            contact2.Attributes["lastname"] = "Bloggs";
            contact2.Attributes["new_somefield"] = new Money(678910); // (decimal)678910 


            contactList.Add(contact2);
            contactList.Add(contact1);

            var context = new XrmFakedContext();
            context.Initialize(contactList);
            var service = context.GetFakedOrganizationService();

            QueryExpression qry = new QueryExpression("contact");
            qry.ColumnSet = new ColumnSet(true);
            qry.AddOrder("new_somefield", OrderType.Descending);
            var results = service.RetrieveMultiple(qry);

            var firstResultValue = results.Entities[0]["new_somefield"] as Money;

            Assert.Equal(678910M, firstResultValue.Value);
        }
Ejemplo n.º 5
0
        public void Should_Execute_Mock_For_OrganizationRequests()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var e = new Entity("Contact") { Id = Guid.NewGuid() };
            context.Initialize(new[] { e });
            context.AddExecutionMock<RetrieveEntityRequest>(RetrieveEntityMock);

            var inputs = new ParameterCollection
            {
                {"Target", e }
            };

            context.ExecutePluginWith<CustomMockPlugin>(inputs, new ParameterCollection(), new EntityImageCollection(), new EntityImageCollection());

            Assert.Equal("Successful", (string)e["response"]);
            Assert.DoesNotThrow(() => context.RemoveExecutionMock<RetrieveEntityRequest>());
        }
Ejemplo n.º 6
0
        public void Should_set_a_statecode_by_default_when_an_entity_record_is_added_to_the_context()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var c = new Contact()
            {
                Id = Guid.NewGuid()
            };
            context.Initialize(new[] { c });

            //Retrieve record after update
            var contact = (from con in context.CreateQuery<Contact>()
                           where con.Id == c.Id
                           select con).FirstOrDefault();

            Assert.Equal((int)contact.StateCode.Value, 0); //Active
        }
        public void When_executing_fetchxml_right_result_is_returned()
        {
            //This will test a query expression is generated and executed

            var ctx = new XrmFakedContext();
            ctx.Initialize(new List<Entity>()
            {
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo Messi", Telephone1 = "123" }, //should be returned
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo Messi", Telephone1 = "234" }, //should be returned
                new Contact() {Id = Guid.NewGuid(), FirstName = "Leo", Telephone1 = "789" }, //shouldnt
                new Contact() {Id = Guid.NewGuid(), FirstName = "Andrés", Telephone1 = "123" }, //shouldnt
            });

            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='fullname' />
                                    <attribute name='telephone1' />
                                    <attribute name='contactid' />
                                        <filter type='and'>
                                            <condition attribute='firstname' operator='like' value='%Leo%' />
                                                <filter type='or'>
                                                    <condition attribute='telephone1' operator='eq' value='123' />
                                                    <condition attribute='telephone1' operator='eq' value='234' />
                                                </filter>
                                        </filter>
                                  </entity>
                            </fetch>";

            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetchXml)
            };

            var service = ctx.GetFakedOrganizationService();
            var response = service.Execute(retrieveMultiple) as RetrieveMultipleResponse;

            Assert.Equal(2, response.EntityCollection.Entities.Count);

            //Executing the same via ExecuteMultiple returns also the same
            var response2 = service.RetrieveMultiple(retrieveMultiple.Query);
            Assert.Equal(2, response2.Entities.Count);
        }
Ejemplo n.º 8
0
        public void When_a_query_expression_without_pagination_is_executed_all_records_are_returned()
        {
            var context = new XrmFakedContext();

            //Create 20 contacts
            var contactList = new List<Entity>();

            for (var i= 0; i < 20; i++) {
                contactList.Add(new Entity("contact") { Id = Guid.NewGuid() });
            }

            context.Initialize(contactList);

            var qe = new QueryExpression() { EntityName = "contact" };
            qe.ColumnSet = new ColumnSet(true);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count == 20);
        }
Ejemplo n.º 9
0
        public void When_a_query_expression_with_topcount_is_executed_only_a_number_of_records_equals_to_the_page_size_is_returned()
        {
            var context = new XrmFakedContext();

            //Create 20 contacts
            var contactList = new List<Entity>();

            for (var i = 0; i < 20; i++)
            {
                contactList.Add(new Entity("contact") { Id = Guid.NewGuid() });
            }

            context.Initialize(contactList);

            var qe = new QueryExpression() { EntityName = "contact" };
            qe.ColumnSet = new ColumnSet(true);
            qe.TopCount = 10;
            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count == 10);
        }
Ejemplo n.º 10
0
        public void Should_not_override_a_statecode_already_initialized()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
            var service = context.GetFakedOrganizationService();

            var c = new Contact()
            {
                Id = Guid.NewGuid(),
            };

            c["statecode"] = new OptionSetValue(69); //As the StateCode is read only in the early bound entity, this is the only way of updating it
             
            context.Initialize(new[] { c });

            //Retrieve record after update
            var contact = (from con in context.CreateQuery<Contact>()
                           where con.Id == c.Id
                           select con).FirstOrDefault();

            Assert.Equal((int)contact.StateCode.Value, 69); //Set
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public void When_executing_a_query_expression_with_a_not_null_operator_right_result_is_returned()
        {
            var context  = new XrmFakedContext();
            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["fullname"] = "1 Contact";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["fullname"] = null;
            var contact3 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new List <Entity>()
            {
                contact1, contact2, contact3
            });

            var qe = new QueryExpression()
            {
                EntityName = "contact"
            };

            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria  = new FilterExpression(LogicalOperator.And);
            var condition = new ConditionExpression("fullname", ConditionOperator.NotNull);

            qe.Criteria.AddCondition(condition);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count() == 1);
        }
Ejemplo n.º 13
0
        public void When_filtering_by_a_money_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var context = new XrmFakedContext();

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

            var contactId1 = Guid.NewGuid();
            var contactId2 = Guid.NewGuid();

            var account1 = new Account();

            account1.Id        = Guid.NewGuid();
            account1.MarketCap = new Money(123.45m);

            var account2 = new Account();

            account2.Id        = Guid.NewGuid();
            account2.MarketCap = new Money(223.45m);

            context.Initialize(new List <Entity> {
                account1, account2
            });

            var fetchXml =
                "<fetch>" +
                "  <entity name='account'>" +
                "     <attribute name='name'/>" +
                "     <filter type='and'>" +
                "         <condition attribute='marketcap' operator='eq' value='123.45' />" +
                "     </filter>" +
                "  </entity>" +
                "</fetch>";
            var rows = context.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(rows.Entities.Count, 1);
        }
        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"));
        }
        public void When_executing_a_linq_query_with_equals_between_2_strings_with_date_format_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid, FirstName = "11.1"
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.FirstName == "11.1"
                               select c).FirstOrDefault();

                Assert.True(contact != null);
            }
        }
Ejemplo n.º 16
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());
        }
Ejemplo n.º 17
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);
        }
        public void It_Should_Execute_On_Custom_Action()
        {
            var context  = new XrmFakedContext();
            var template = "Hello ${{Value(\\\"subject\\\")}}";

            var email = new Entity
            {
                Id          = Guid.NewGuid(),
                LogicalName = "email",
                Attributes  =
                {
                    { "subject", "Demo" }
                }
            };

            context.Initialize(email);

            var inputParameters = new ParameterCollection
            {
                { "jsonInput", "{" +
                  $"\"template\": \"{template}\"," +
                  $"\"target\": {{\"Id\": \"{email.Id}\", \"LogicalName\": \"{email.LogicalName}\"}}" +
                  "}" }
            };

            var pluginContext = context.GetDefaultPluginContext();

            pluginContext.InputParameters  = inputParameters;
            pluginContext.OutputParameters = new ParameterCollection();

            context.ExecutePluginWith <XTLProcessor>(pluginContext);

            var expected = @"{""error"":null,""result"":""Hello Demo"",""success"":true,""traceLog"":""Processing token 'Value(\""subject\"")'\u000d\u000aInitiating interpreter\u000d\u000aProcessing handler Value\u000d\u000aSuccessfully processed handler Value\u000d\u000aReplacing token with 'Demo'\u000d\u000a""}";

            Assert.That(pluginContext.OutputParameters["jsonOutput"], Is.EqualTo(expected));
        }
Ejemplo n.º 19
0
        public void Should_Override_Execution_Mock()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var e = new Entity("Contact")
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new[] { e });
            context.AddExecutionMock <RetrieveEntityRequest>(RetrieveEntityMock);
            context.AddExecutionMock <RetrieveEntityRequest>(AnotherRetrieveEntityMock);

            var inputs = new ParameterCollection
            {
                { "Target", e }
            };

            context.ExecutePluginWith <CustomMockPlugin>(inputs, new ParameterCollection(), new EntityImageCollection(), new EntityImageCollection());

            Assert.Equal("Another", (string)e["response"]);
            Assert.DoesNotThrow(() => context.RemoveExecutionMock <RetrieveEntityRequest>());
        }
        public void When_filtering_by_a_boolean_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var context = new XrmFakedContext();

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

            var account1 = new Account();

            account1.Id         = Guid.NewGuid();
            account1.Name       = "Test 1";
            account1.DoNotEMail = false;

            var account2 = new Account();

            account2.Id         = Guid.NewGuid();
            account2.Name       = "Test 2";
            account2.DoNotEMail = true;

            context.Initialize(new List <Entity> {
                account1, account2
            });

            var fetchXml =
                "<fetch>" +
                "  <entity name='account'>" +
                "     <attribute name='name'/>" +
                "     <filter type='and'>" +
                "         <condition attribute='donotemail' operator='eq' value='0' />" +
                "     </filter>" +
                "  </entity>" +
                "</fetch>";
            var rows = context.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(rows.Entities.Count, 1);
            Assert.Equal(rows.Entities[0].ToEntity <Account>().Name, account1.Name);
        }
Ejemplo n.º 21
0
        public void When_executing_a_query_expression_with_in_operator_right_result_is_returned()
        {
            var context  = new XrmFakedContext();
            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["fullname"] = "McDonald"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["fullname"] = "King"; contact2["firstname"] = "First 2";
            var contact3 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["fullname"] = "King"; contact2["firstname"] = "First 2";

            context.Initialize(new List <Entity>()
            {
                contact1, contact2
            });

            var qe = new QueryExpression()
            {
                EntityName = "contact"
            };

            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria  = new FilterExpression(LogicalOperator.And);
            var condition = new ConditionExpression("fullname", ConditionOperator.In, new string[] { "McDonald", "King" });

            qe.Criteria.AddCondition(condition);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count() == 2);
        }
        public void DeleteAttachment_Delete_From_0_To_100000_No_Extensions()
        {
            //Arrange
            XrmFakedWorkflowContext workflowContext = new XrmFakedWorkflowContext();

            Entity note1 = new Entity("annotation")
            {
                Id             = Guid.NewGuid(),
                ["filesize"]   = 100000,
                ["filename"]   = "text.docx",
                ["isdocument"] = true
            };

            var inputs = new Dictionary <string, object>
            {
                { "NoteWithAttachment", note1.ToEntityReference() },
                { "DeleteSizeMax", 10000 },
                { "DeleteSizeMin", 0 },
                { "Extensions", null },
                { "AppendNotice", false }
            };

            XrmFakedContext xrmFakedContext = new XrmFakedContext();

            xrmFakedContext.Initialize(new List <Entity> {
                note1
            });

            const int expected = 1;

            //Act
            var result = xrmFakedContext.ExecuteCodeActivity <DeleteAttachment>(workflowContext, inputs);

            //Assert
            Assert.AreEqual(expected, result["NumberOfAttachmentsDeleted"]);
        }
Ejemplo n.º 23
0
        public static void When_a_query_by_a_boolean_attribute_is_executed_with_one_attribute_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var account = new Account()
            {
                Id = Guid.NewGuid(), Name = "Test", DoNotEMail = false
            };
            var account2 = new Account()
            {
                Id = Guid.NewGuid(), Name = "Other account!", DoNotEMail = true
            };

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

            var service = context.GetFakedOrganizationService();

            var query = new QueryByAttribute
            {
                EntityName = Account.EntityLogicalName,
                ColumnSet  = new ColumnSet("name")
            };

            query.AddAttributeValue("donotemail", false);

            //Execute using a request to test the OOB (XRM) message contracts
            RetrieveMultipleRequest request = new RetrieveMultipleRequest();

            request.Query = query;
            Collection <Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

            Assert.True(entityList.Count == 1);
            Assert.Equal(entityList[0]["name"].ToString(), "Test");
        }
Ejemplo n.º 24
0
        public void When_Querying_Using_LinQ_Results_Should_Appear()
        {
            var context = new XrmFakedContext();

            var account = new Account
            {
                Id = Guid.NewGuid()
            };

            var contact = new Contact
            {
                Id         = Guid.NewGuid(),
                Attributes = new AttributeCollection
                {
                    { "accountid", account.ToEntityReference() }
                }
            };

            context.Initialize(new Entity[] { account, contact });

            var contactResult = context.CreateQuery <Contact>().SingleOrDefault(con => con.Id == contact.Id);

            Assert.NotNull(contactResult);
        }
Ejemplo n.º 25
0
        public static void When_a_query_by_attribute_is_executed_with_one_null_attribute_it_is_not_returned()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

            var contact = new Contact
            {
                Id        = Guid.NewGuid(),
                FirstName = null,
                LastName  = "asdf"
            };

            fakedContext.Initialize(new List <Entity> {
                contact
            });

            QueryByAttribute query = new QueryByAttribute("contact");

            query.ColumnSet = new ColumnSet("firstname", "lastname");
            var results = fakedService.RetrieveMultiple(query);

            Assert.True(results.Entities[0].Attributes.ContainsKey("lastname"));
            Assert.False(results.Entities[0].Attributes.ContainsKey("firstname"));
        }
        public void When_OnlyDeactivated_WorkOrderExist_And_Passing_Correct_IotAlertId_Should_Return_Null()
        {
            XrmFakedContext fakedContext   = new XrmFakedContext();
            Entity          serviceRequest = new Entity("incident", Guid.NewGuid());
            Entity          workOrder      = new Entity("msdyn_workorder", Guid.NewGuid());

            workOrder["msdyn_servicerequest"] = serviceRequest.ToEntityReference();
            workOrder["statuscode"]           = new OptionSetValue((int)StatusCode_WO.Inactive);
            fakedContext.Initialize(new List <Entity>()
            {
                serviceRequest, workOrder
            });
            var inputs = new Dictionary <string, object>()
            {
                { "ServiceRequestId", serviceRequest.ToEntityReference() }
            };
            var outputParameter = fakedContext.ExecuteCodeActivity <GetWorkOrderRelatedServiceRequest>(inputs);
            var isExists        = (bool)outputParameter["IsExists"];

            Assert.IsFalse(isExists);
            var workOrderId = outputParameter["WorkOrderId"] as EntityReference;

            Assert.IsNull(workOrderId);
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
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));
        }
Ejemplo n.º 29
0
        public void When_executing_a_query_expression_with_an_attribute_in_columnset_that_doesnt_exists_no_value_is_returned_with_dynamic_entities()
        {
            var context  = new XrmFakedContext();
            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";

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

            account["name"] = "Account 1";

            contact1["parentcustomerid"] = account.ToEntityReference(); //Both contacts are related to the same account

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

            var qe = new QueryExpression()
            {
                EntityName = "contact"
            };

            //We only select fullname and parentcustomerid, firstname should not be included
            qe.ColumnSet = new ColumnSet(new string[] { "this attribute doesnt exists!" });

            XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            var list = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.False(list[0].Attributes.ContainsKey("this attribute doesnt exists!"));
        }
Ejemplo n.º 30
0
        public void When_initializing_with_two_entities_with_two_different_guids_the_context_will_have_both()
        {
            var context = new XrmFakedContext();
            var guid1   = Guid.NewGuid();
            var guid2   = Guid.NewGuid();

            IQueryable <Entity> data = new List <Entity>()
            {
                new Entity("account")
                {
                    Id = guid1
                },
                new Entity("account")
                {
                    Id = guid2
                }
            }.AsQueryable();

            context.Initialize(data);
            Assert.True(context.Data.Count == 1);
            Assert.True(context.Data["account"].Count == 2);
            Assert.Equal(context.Data["account"][guid1].Id, data.FirstOrDefault().Id);
            Assert.Equal(context.Data["account"][guid2].Id, data.LastOrDefault().Id);
        }
Ejemplo n.º 31
0
        public void FetchXml_Aggregate_Sum_Money()
        {
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' aggregate='true'>
                              <entity name='salesorderdetail'>
                                    <attribute name='priceperunit' alias='sum' aggregate='sum'/>
                                  </entity>
                            </fetch>";
            var ctx      = new XrmFakedContext();

            ctx.Initialize(new[] {
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid(), PricePerUnit = new Money(100m)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid(), PricePerUnit = new Money(100m)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid(),
                },                                                /* attribute missing */
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid(), PricePerUnit = null
                },
            });

            var collection = ctx.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(1, collection.Entities.Count);
            var ent = collection.Entities[0];

            Assert.IsType(typeof(Money), ent.GetAttributeValue <AliasedValue>("sum")?.Value);
            Assert.Equal(200m, (ent.GetAttributeValue <AliasedValue>("sum")?.Value as Money)?.Value);
        }
Ejemplo n.º 32
0
        public void When_ordering_by_money_fields_descending_expected_result_is_returned()
        {
            List <Entity> contactList = new List <Entity>();

            Entity contact1 = new Entity("contact");

            contact1.Id = Guid.NewGuid();
            contact1.Attributes["firstname"]     = "Fred";
            contact1.Attributes["lastname"]      = "Bloggs";
            contact1.Attributes["new_somefield"] = new Money(12345); // (decimal)678910

            Entity contact2 = new Entity("contact");

            contact2.Id = Guid.NewGuid();
            contact2.Attributes["firstname"]     = "Jo";
            contact2.Attributes["lastname"]      = "Bloggs";
            contact2.Attributes["new_somefield"] = new Money(678910); // (decimal)678910

            contactList.Add(contact2);
            contactList.Add(contact1);

            var context = new XrmFakedContext();

            context.Initialize(contactList);
            var service = context.GetFakedOrganizationService();

            QueryExpression qry = new QueryExpression("contact");

            qry.ColumnSet = new ColumnSet(true);
            qry.AddOrder("new_somefield", OrderType.Descending);
            var results = service.RetrieveMultiple(qry);

            var firstResultValue = results.Entities[0]["new_somefield"] as Money;

            Assert.Equal(678910M, firstResultValue.Value);
        }
Ejemplo n.º 33
0
        public void FetchXml_Aggregate_Dategroup_Month()
        {
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
                              <entity name='contact'>
                                    <attribute name='contactid' alias='count.contacts' aggregate='count' />
                                    <attribute name='birthdate' alias='group.dob' groupby='true' dategrouping='month' />
                                  </entity>
                            </fetch>";

            var ctx = new XrmFakedContext();

            ctx.Initialize(BirthdateContacts);

            var collection = ctx.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(3, collection.Entities.Count);
            var byMonth = collection.Entities.ToDictionary(x => x.GetAttributeValue <AliasedValue>("group.dob").Value as int?);

            Assert.Equal(new int?[] { 1, 2, 5 }, byMonth.Keys.OrderBy(x => x));

            Assert.Equal(2, byMonth[1].GetAttributeValue <AliasedValue>("count.contacts").Value);
            Assert.Equal(1, byMonth[2].GetAttributeValue <AliasedValue>("count.contacts").Value);
            Assert.Equal(1, byMonth[5].GetAttributeValue <AliasedValue>("count.contacts").Value);
        }
Ejemplo n.º 34
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);
        }
Ejemplo n.º 35
0
        public void When_updating_an_entity_Modified_On_Should_Also_Be_Updated()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

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

            var oldModifiedOn = (DateTime)e["modifiedon"];

            Thread.Sleep(1000);

            service.Update(e);
            var newModifiedOn = (DateTime)e["modifiedon"];

            Assert.NotEqual(oldModifiedOn, newModifiedOn);
        }
        public void When_querying_fetchxml_with_linked_entities_with_left_outer_join_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

            var account = new Account() {  Id = Guid.NewGuid(),  PrimaryContactId = contact.ToEntityReference() };
            var account2 = new Account()  { Id = Guid.NewGuid(), PrimaryContactId = null };

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

            var fetchXml = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='account'>
                        <attribute name='name' />
                        <attribute name='primarycontactid' />
                        <attribute name='telephone1' />
                        <attribute name='accountid' />
                        <order attribute='name' descending='false' />
                        <link-entity name='contact' from='contactid' to='primarycontactid' alias='aa' link-type='outer'>
                          <attribute name='firstname' />
                        </link-entity>
                        <filter type='and'>
                            <condition attribute='statecode' operator='eq' value='0' />
                        </filter>
                      </entity>
                    </fetch>
                ";

            //Translated correctly
            var queryExpression = XrmFakedContext.TranslateFetchXmlToQueryExpression(context, fetchXml);
            Assert.True(queryExpression.LinkEntities.Count == 1);

            var linkedEntity = queryExpression.LinkEntities[0];
            Assert.Equal(linkedEntity.JoinOperator, JoinOperator.LeftOuter);

            //Executed correctly
            var request = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml) };
            var response = ((RetrieveMultipleResponse)service.Execute(request));

            var entities = response.EntityCollection.Entities;
            Assert.True(entities.Count == 2);
            Assert.Equal("Lionel", (entities[0]["aa.firstname"] as AliasedValue).Value.ToString());
            Assert.False(entities[1].Attributes.ContainsKey("aa.firstname"));
        }
        public void When_filtering_by_a_money_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var contactId1 = Guid.NewGuid();
            var contactId2 = Guid.NewGuid();

            var account1 = new Account();
            account1.Id = Guid.NewGuid();
            account1.MarketCap = new Money(123.45m);

            var account2 = new Account();
            account2.Id = Guid.NewGuid();
            account2.MarketCap = new Money(223.45m);

            context.Initialize(new List<Entity> { account1, account2 });

            var fetchXml =
                 "<fetch>" +
                 "  <entity name='account'>" +
                 "     <attribute name='name'/>" +
                 "     <filter type='and'>" +
                 "         <condition attribute='marketcap' operator='eq' value='123.45' />" +
                 "     </filter>" +
                 "  </entity>" +
                 "</fetch>";
            var rows = context.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 1);
        }
        public void When_querying_the_same_entity_records_with_joins_no_collection_modified_exception_is_thrown()
        {
            var fakedContext = new XrmFakedContext { };
            var service = fakedContext.GetFakedOrganizationService();

            var entityAccount = new Account { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!", LogicalName = "account" };
            var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference() };

            var entityBusinessUnit = new BusinessUnit { Name = "TestBU", BusinessUnitId = Guid.NewGuid() };

            var initiatingUser = new SystemUser
            {
                Id = Guid.NewGuid(),
                FirstName = "TestUser",
                DomainName = "TestDomain",
                BusinessUnitId = entityBusinessUnit.ToEntityReference()
            };

            fakedContext.Initialize(new List<Entity>() {
               entityBusinessUnit,entityAccount,entityContact,initiatingUser
            });


            var fetchXml = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='systemuser'>
                        <attribute name='fullname' />
                         <attribute name='systemuserid' />
                         <attribute name='businessunitid' />
                         <filter type='and'>
                          <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='#userId#' />
                         </filter>
                            <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='bu' intersect='true' >
                                <attribute name='name' />
                            </link-entity>
                      </entity>
                    </fetch>
                ";

            var UserRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.Replace("#userId#", initiatingUser.Id.ToString())) };
            var response = ((RetrieveMultipleResponse)service.Execute(UserRequest));

            var entities = response.EntityCollection.Entities;
            Assert.True(entities.Count == 1);
            Assert.True(entities[0].Attributes.ContainsKey("bu.name"));
            Assert.IsType<AliasedValue>(entities[0]["bu.name"]);
            Assert.Equal("TestBU", (entities[0]["bu.name"] as AliasedValue).Value.ToString());
        }
Ejemplo n.º 39
0
        public static void Should_Only_Find_Correct_Faked_N_To_N_Records()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

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

            var testUser = new SystemUser
            {
                Id = userId
            };

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

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

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

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

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

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

            fakedService.Execute(request);

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

            fakedService.Execute(request2);

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

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

            var entityAccount = new Account { Id = Guid.NewGuid(), Name = "Test Account", LogicalName = "account" };
            var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference(), EMailAddress1 = "*****@*****.**" };

            var entityCase = new Incident
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = entityContact.ToEntityReference(),
                CustomerId = entityAccount.ToEntityReference(),
                Title = "Unit Test Case"
            };

            entityCase["statecode"] = new OptionSetValue((int) IncidentState.Active);

            fakedContext.Initialize(new List<Entity>() {
               entityAccount,entityContact, entityCase
            });


            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >
              <entity name='incident' >
                <attribute name='incidentid' />
                <attribute name='statecode' /> 
                <order attribute='createdon' descending='true' /> 
                 <filter type='and' > 
                  <condition attribute='statecode' operator='neq' value='2' /> 
                </filter>
              </entity>
            </fetch>";

            var rows = fakedContext.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 1);

        }
Ejemplo n.º 41
0
        public void Should_Apply_Left_Outer_Join_Filters_When_The_Right_hand_side_of_the_expression_was_found()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            // Date for filtering, we only want "expired" records, i.e. those that weren't set as regarding in any emails for this period and logically even exist this long
            var days = 5;

            var incident = new Incident
            {
                Id         = Guid.NewGuid(),
                Title      = "Test case",
                StatusCode = new OptionSetValue((int)IncidentState.Active)
            };

            var email = new Email
            {
                Id = Guid.NewGuid(),
                RegardingObjectId = incident.ToEntityReference(),
            };

            incident["createdon"] = DateTime.UtcNow.AddDays(-6);
            email["createdon"]    = DateTime.UtcNow.AddDays(10);

            context.Initialize(new List <Entity>()
            {
                incident, email
            });

            // Remove either incident createdon conditionexpression, or LinkEntities and the e-mail conditionexpression and it will pass
            // What this query expresses: Get all incidents, that are older than given number of days and that also didn't receive emails for this number of days
            var query = new QueryExpression
            {
                ColumnSet  = new ColumnSet(true),
                EntityName = Incident.EntityLogicalName,
                Criteria   =
                {
                    FilterOperator = LogicalOperator.And,
                    Filters        =
                    {
                        new FilterExpression
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression("statuscode", ConditionOperator.Equal,     new OptionSetValue((int)IncidentState.Active)),
                                new ConditionExpression("createdon",  ConditionOperator.LessEqual, DateTime.UtcNow.AddDays(-1 * days))
                            }
                        }
                    }
                },
                LinkEntities =
                {
                    new LinkEntity
                    {
                        LinkFromEntityName    = "incident",
                        LinkToEntityName      = "email",
                        LinkFromAttributeName = "incidentid",
                        LinkToAttributeName   = "regardingobjectid",
                        JoinOperator          = JoinOperator.LeftOuter,
                        LinkCriteria          = new FilterExpression
                        {
                            Filters =
                            {
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression("createdon", ConditionOperator.GreaterEqual, DateTime.UtcNow.AddDays(-1 * days))
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var incidents = service.RetrieveMultiple(query).Entities;

            Assert.Equal(1, incidents.Count);
        }
        public void When_execute_is_called_with_reverse_param_order()
        {
            var context = new XrmFakedContext();


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

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

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

            var orgSvc = context.GetFakedOrganizationService();

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

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

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

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

                var wrongAssociation = (from tu in ctx.TeamMembershipSet
                                        where tu.TeamId == userId &&
                                        tu.SystemUserId == teamId
                                        select tu).ToList();
                Assert.Equal(1, wrongAssociation.Count());
            }
        }
Ejemplo n.º 43
0
        public void When_ordering_by_guid_fields_expected_result_is_returned()
        {
            List<Entity> contactList = new List<Entity>();

            var g1 = new Guid(12, 0, 0, new byte[] {  new byte(), new byte(), new byte(), new byte(),
                                                      new byte(), new byte(), new byte(), new byte()  });
            var g2 = new Guid(24, 0, 0, new byte[] {  new byte(), new byte(), new byte(), new byte(),
                                                      new byte(), new byte(), new byte(), new byte()  });

            Entity contact1 = new Entity("contact");
            contact1.Id = Guid.NewGuid();
            contact1.Attributes["firstname"] = "Fred";
            contact1.Attributes["new_orderbyfield"] = g1;

            Entity contact2 = new Entity("contact");
            contact2.Id = Guid.NewGuid();
            contact2.Attributes["firstname"] = "Jo";
            contact2.Attributes["new_orderbyfield"] = g2;

            contactList.Add(contact2);
            contactList.Add(contact1);

            var context = new XrmFakedContext();
            context.Initialize(contactList);
            var service = context.GetFakedOrganizationService();

            QueryExpression qry = new QueryExpression("contact");
            qry.ColumnSet = new ColumnSet(true);
            qry.AddOrder("new_orderbyfield", OrderType.Ascending);
            var results = service.RetrieveMultiple(qry);

            var firstResultValue = (Guid)results.Entities[0]["new_orderbyfield"];

            Assert.Equal(g1, firstResultValue);
        }
Ejemplo n.º 44
0
        public void When_ordering_by_entity_reference_fields_expected_result_is_returned()
        {
            List<Entity> contactList = new List<Entity>();

            Entity contact1 = new Entity("contact");
            contact1.Id = Guid.NewGuid();
            contact1.Attributes["firstname"] = "Fred";
            contact1.Attributes["lastname"] = "Bloggs";
            contact1.Attributes["new_somefield"] = new EntityReference()
            {
                Id = Guid.NewGuid(),
                Name = "Jordi"
            };

            Entity contact2 = new Entity("contact");
            contact2.Id = Guid.NewGuid();
            contact2.Attributes["firstname"] = "Jo";
            contact2.Attributes["lastname"] = "Bloggs";
            contact2.Attributes["new_somefield"] = new EntityReference()
            {
                Id = Guid.NewGuid(),
                Name = "Skuba"
            };

            contactList.Add(contact2);
            contactList.Add(contact1);

            var context = new XrmFakedContext();
            context.Initialize(contactList);
            var service = context.GetFakedOrganizationService();

            QueryExpression qry = new QueryExpression("contact");
            qry.ColumnSet = new ColumnSet(true);
            qry.AddOrder("new_somefield", OrderType.Ascending);
            var results = service.RetrieveMultiple(qry);

            var firstResultValue = results.Entities[0]["new_somefield"] as EntityReference;

            Assert.Equal("Jordi", firstResultValue.Name);
        }
Ejemplo n.º 45
0
        public void FetchXml_Operator_Le_Execution()
        {
            var ctx = new XrmFakedContext();
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='address1_longitude' />
                                        <filter type='and'>
                                            <condition attribute='address1_longitude' operator='le' value='1.2345' />
                                        </filter>
                                  </entity>
                            </fetch>";
            var ct1 = new Contact() { Id = Guid.NewGuid(), Address1_Longitude = 1.23 };
            var ct2 = new Contact() { Id = Guid.NewGuid(), Address1_Longitude = 1.33 };
            var ct3 = new Contact() { Id = Guid.NewGuid(), Address1_Longitude = 1.2345 };
            ctx.Initialize(new[] { ct1, ct2, ct3 });
            var service = ctx.GetFakedOrganizationService();

            var collection = service.RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(2, collection.Entities.Count);
            Assert.Equal(1.23, collection.Entities[0]["address1_longitude"]);
            Assert.Equal(1.2345, collection.Entities[1]["address1_longitude"]);
        }
Ejemplo n.º 46
0
        public void FetchXml_Operator_On_Execution()
        {
            var ctx = new XrmFakedContext();
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='anniversary' />
                                        <filter type='and'>
                                            <condition attribute='anniversary' operator='on' value='2014-11-23' />
                                        </filter>
                                  </entity>
                            </fetch>";

            var date = new DateTime(2014, 11, 23);
            var ct1 = new Contact() { Id = Guid.NewGuid(), Anniversary = date };
            var ct2 = new Contact() { Id = Guid.NewGuid(), Anniversary = date.AddDays(1) };
            ctx.Initialize(new[] { ct1, ct2 });
            var service = ctx.GetFakedOrganizationService();

            var collection = service.RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(1, collection.Entities.Count);
            var retrievedDate = collection.Entities[0]["anniversary"] as DateTime?;
            Assert.Equal(2014, retrievedDate.Value.Year);
            Assert.Equal(11, retrievedDate.Value.Month);
            Assert.Equal(23, retrievedDate.Value.Day);
        }
        public void FetchXml_Operator_Yesterday_Execution()
        {
            var ctx = new XrmFakedContext();
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='anniversary' />
                                        <filter type='and'>
                                            <condition attribute='anniversary' operator='yesterday' />
                                        </filter>
                                  </entity>
                            </fetch>";

            var date = DateTime.Today;
            var ct1 = new Contact() { Id = Guid.NewGuid(), Anniversary = date }; //Shouldnt
            var ct2 = new Contact() { Id = Guid.NewGuid(), Anniversary = date.AddDays(-1) }; //Should be returned
            ctx.Initialize(new[] { ct1, ct2 });
            var service = ctx.GetFakedOrganizationService();

            var collection = service.RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(1, collection.Entities.Count);

            var retrievedDate = collection.Entities[0]["anniversary"] as DateTime?;
            Assert.Equal(retrievedDate, DateTime.Today.AddDays(-1));
        }
        public void FetchXml_Operator_NotBetween_Execution()
        {
            var ctx = new XrmFakedContext();
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='contact'>
                                    <attribute name='anniversary' />
                                        <filter type='and'>
                                            <condition attribute='anniversary' operator='not-between'>
                                                <value>2013-05-17 00:00:00</value>
                                                <value>2013-05-20 14:40:00</value>
                                            </condition>
                                        </filter>
                                  </entity>
                            </fetch>";

            var date = DateTime.Today;
            var ct1 = new Contact() { Id = Guid.NewGuid(), Anniversary = date }; //Should
            var ct2 = new Contact() { Id = Guid.NewGuid(), Anniversary = new DateTime(2013, 05, 19) }; //Shouldnt
            ctx.Initialize(new[] { ct1, ct2 });
            var service = ctx.GetFakedOrganizationService();

            var collection = service.RetrieveMultiple(new FetchExpression(fetchXml));

            Assert.Equal(1, collection.Entities.Count);

            var retrievedDate = collection.Entities[0]["anniversary"] as DateTime?;
            Assert.Equal(retrievedDate, date);
        }
Ejemplo n.º 49
0
        public void When_querying_by_an_attribute_which_wasnt_initialised_null_value_is_returned_for_early_bound_and_not_an_exception()
        {
            var ctx = new XrmFakedContext();
            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact));

            var service = ctx.GetFakedOrganizationService();
            ctx.Initialize(new List<Entity>() {
                new Contact() {
                    Id = Guid.NewGuid(), LastName = "Mcdonald" }
            });

            var name = "Mcdonald";

            using (var context = new XrmServiceContext(service))
            {
                var contacts = (from c in context.ContactSet
                                where c.FirstName == name || c.LastName == name
                                select new Contact { Id = c.Id, FirstName = c.FirstName, LastName = c.LastName }).ToList();

                Assert.Equal(1, contacts.Count);
                Assert.Null(contacts[0].FirstName);
            }
        }
        public void When_querying_fetchxml_with_linked_entities_linked_entity_properties_match_the_equivalent_linq_expression()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

            var account = new Account()
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = contact.ToEntityReference()
            };

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

            var fetchXml = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='account'>
                        <attribute name='name' />
                        <attribute name='primarycontactid' />
                        <attribute name='telephone1' />
                        <attribute name='accountid' />
                        <order attribute='name' descending='false' />
                        <link-entity name='contact' from='contactid' to='primarycontactid' alias='aa'>
                          <attribute name='firstname' />
                          <filter type='and'>
                            <condition attribute='firstname' operator='eq' value='Lionel' />
                          </filter>
                        </link-entity>
                      </entity>
                    </fetch>
                ";

            //Equivalent linq query
            using(var ctx = new XrmServiceContext(service))
            {
                var linqQuery = (from a in ctx.CreateQuery<Account>()
                                 join c in ctx.CreateQuery<Contact>() on a.PrimaryContactId.Id equals c.ContactId
                                 where c.FirstName == "Lionel"
                                 select new
                                 {
                                     Account = a,
                                     Contact = c
                                 }).ToList();

            }

            var queryExpression = XrmFakedContext.TranslateFetchXmlToQueryExpression(context, fetchXml);
            Assert.True(queryExpression.LinkEntities.Count == 1);

            var linkedEntity = queryExpression.LinkEntities[0];
            Assert.Equal(linkedEntity.LinkFromAttributeName, "primarycontactid");
            Assert.Equal(linkedEntity.LinkToAttributeName, "contactid");
            Assert.Equal(linkedEntity.JoinOperator, JoinOperator.Inner);

            var request = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml) };
            var response = ((RetrieveMultipleResponse)service.Execute(request));

            var entities = response.EntityCollection.Entities;
            Assert.True(entities.Count == 1);
            Assert.True(entities[0].Attributes.ContainsKey("aa.firstname"));
            Assert.IsType<AliasedValue>(entities[0]["aa.firstname"]);
            Assert.Equal("Lionel", (entities[0]["aa.firstname"] as AliasedValue).Value.ToString());
        }
        public void When_executing_fetchxml_with_count_attribute_only_that_number_of_results_is_returned()
        {
            //This will test a query expression is generated and executed

            var ctx = new XrmFakedContext();

            //Arrange
            var contactList = new List<Entity>();
            for(var i=0; i < 20; i++)
            {
                contactList.Add(new Contact() { Id = Guid.NewGuid() });
            }
            ctx.Initialize(contactList);

            //Act
            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='7'>
                              <entity name='contact'>
                                    <attribute name='fullname' />
                                    <attribute name='telephone1' />
                                    <attribute name='contactid' /> 
                                  </entity>
                            </fetch>";


            var retrieveMultiple = new RetrieveMultipleRequest()
            {
                Query = new FetchExpression(fetchXml)
            };

            var service = ctx.GetFakedOrganizationService();
            var response = service.Execute(retrieveMultiple) as RetrieveMultipleResponse;

            Assert.Equal(7, response.EntityCollection.Entities.Count);
        }
Ejemplo n.º 52
0
        public void Should_Not_Throw_Unable_To_Cast_AliasedValue_Exception()
        {
            var account1 = new Account()
            {
                Id = Guid.NewGuid(), Name = "1 Test", Address1_City = "1 City", Address1_StateOrProvince = "a2 State"
            };
            var account2 = new Account()
            {
                Id = Guid.NewGuid(), Name = "2 Test", Address1_City = "2 City", Address1_StateOrProvince = "b2 State"
            };
            var account3 = new Account()
            {
                Id = Guid.NewGuid(), Name = "3 Test", Address1_City = "2 City", Address1_StateOrProvince = "b1 State"
            };

            var contact1 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "1 Cont", LastName = "Cont 1", Address1_City = "1 City", ParentCustomerId = account1.ToEntityReference()
            };
            var contact2 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "2 Cont", LastName = "Cont 2", Address1_City = "1 City", ParentCustomerId = account2.ToEntityReference()
            };
            var contact3 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "3 Cont", LastName = "Cont 3", Address1_City = "1 City", ParentCustomerId = account3.ToEntityReference()
            };
            var contact4 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "4 Cont", LastName = "Cont 4", Address1_City = "2 City", ParentCustomerId = account1.ToEntityReference()
            };
            var contact5 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "5 Cont", LastName = "Cont 5", Address1_City = "2 City", ParentCustomerId = account2.ToEntityReference()
            };
            var contact6 = new Contact()
            {
                Id = Guid.NewGuid(), FirstName = "6 Cont", LastName = "Cont 6", Address1_City = "2 City", ParentCustomerId = account3.ToEntityReference()
            };

            var ctx = new XrmFakedContext();

            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact));

            var service = ctx.GetFakedOrganizationService();

            ctx.Initialize(new List <Entity>()
            {
                account1, account2, account3, contact1, contact2, contact3, contact4, contact5, contact6
            });

            QueryExpression query = new QueryExpression()
            {
                EntityName   = "contact",
                ColumnSet    = new ColumnSet(true),
                LinkEntities =
                {
                    new LinkEntity(Contact.EntityLogicalName,            Account.EntityLogicalName, "parentcustomerid", "accountid", JoinOperator.LeftOuter)
                    {
                        LinkCriteria = new FilterExpression()
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression("address1_city", ConditionOperator.Like,    "2%")
                            }
                        }
                    },
                    new LinkEntity(Contact.EntityLogicalName,            Contact.EntityLogicalName, "parentcustomerid", "contactid", JoinOperator.LeftOuter)
                    {
                        LinkCriteria = new FilterExpression()
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression("address1_city", ConditionOperator.Like,    "2%")
                            }
                        }
                    },
                }
            };

            EntityCollection entities = service.RetrieveMultiple(query);

            Assert.Equal(6, entities.Entities.Count);
        }
        public void When_filtering_by_a_guid_attribute_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var accountId = Guid.NewGuid();
            var license1 = new Entity("pl_license");
            license1.Id = Guid.NewGuid();
            license1.Attributes["pl_no"] = 1;
            license1.Attributes["pl_accountid"] = new EntityReference("account", accountId);

            var license2 = new Entity("pl_license");
            license2.Id = Guid.NewGuid();
            license2.Attributes["pl_no"] = 2;
            license2.Attributes["pl_accountid"] = new EntityReference("account", accountId);

            context.Initialize(new List<Entity> { license1, license2 });

            var fetchXml =
                 "<fetch>" +
                 "  <entity name='pl_license'>" +
                 "     <attribute name='pl_no'/>" +
                 "     <filter type='and'>" +
                 "         <condition attribute='pl_accountid' operator='eq' value='{0}' />" +
                 "     </filter>" +
                 "  </entity>" +
                 "</fetch>";
            fetchXml = string.Format(fetchXml, accountId);
            var rows = context.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 2);
        }
Ejemplo n.º 54
0
        public static void Should_Only_Find_Correct_Faked_N_To_N_Records()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetFakedOrganizationService();

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

            var testUser = new SystemUser
            {
                Id = userId
            };

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

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

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

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

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

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

            fakedService.Execute(request);

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

            fakedService.Execute(request2);

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

            var result = fakedService.RetrieveMultiple(query);

            Assert.NotEmpty(result.Entities);
            Assert.Equal(1, result.Entities.Count);
        }
        public void When_filtering_by_a_guid_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));

            var contactId1 = Guid.NewGuid();
            var contactId2 = Guid.NewGuid();

            var account1 = new Account();
            account1.Id = Guid.NewGuid();
            account1.PrimaryContactId = new EntityReference(Contact.EntityLogicalName, contactId1);

            var account2 = new Account();
            account2.Id = Guid.NewGuid();
            account2.PrimaryContactId = new EntityReference(Contact.EntityLogicalName, contactId2);

            context.Initialize(new List<Entity> { account1, account2 });

            var fetchXml =
                 "<fetch>" +
                 "  <entity name='account'>" +
                 "     <attribute name='name'/>" +
                 "     <filter type='and'>" +
                 "         <condition attribute='primarycontactid' operator='eq' value='{0}' />" +
                 "     </filter>" +
                 "  </entity>" +
                 "</fetch>";
            fetchXml = string.Format(fetchXml, contactId1);
            var rows = context.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 1);
        }
        public void IsBusinessDay_Week_Day_Holiday_User_Local()
        {
            //Arrange
            XrmFakedWorkflowContext workflowContext = new XrmFakedWorkflowContext();

            EntityCollection userSettings = new EntityCollection();
            Entity           userSetting  = new Entity("usersettings")
            {
                Id = Guid.NewGuid(),
                ["systemuserid"] = Guid.NewGuid(),
                ["timezonecode"] = 20
            };

            userSettings.Entities.Add(userSetting);

            EntityCollection calendarRules = new EntityCollection();
            Entity           calendarRule  = new Entity
            {
                LogicalName = "calendarRule",
                Id          = Guid.NewGuid(),
                Attributes  = new AttributeCollection()
            };

            calendarRule.Attributes.Add("name", "4th of July");
            calendarRule.Attributes.Add("starttime", new DateTime(2014, 7, 4, 0, 0, 0));
            calendarRule.Attributes.Add("duration", 1440);
            calendarRules.Entities.Add(calendarRule);

            Entity holidayCalendar = new Entity
            {
                Id          = new Guid("e9717a91-ba0a-e411-b681-6c3be5a8ad70"),
                LogicalName = "calendar",
                Attributes  = new AttributeCollection()
            };

            holidayCalendar.Attributes.Add("name", "Main Holiday Schedule");
            holidayCalendar.Attributes.Add("calendarrules", calendarRules);

            var inputs = new Dictionary <string, object>
            {
                { "DateToCheck", new DateTime(2014, 7, 4, 8, 48, 0, 0) },
                { "HolidayClosureCalendar", new EntityReference {
                      LogicalName = "calendar", Id = new Guid("e9717a91-ba0a-e411-b681-6c3be5a8ad70")
                  } },
                { "EvaluateAsUserLocal", true }
            };

            XrmFakedContext xrmFakedContext = new XrmFakedContext();

            xrmFakedContext.Initialize(new List <Entity> {
                userSetting, calendarRule, holidayCalendar
            });
            xrmFakedContext.CallerId = new EntityReference("systemuser", userSetting.GetAttributeValue <Guid>("systemuserid"));
            var fakeLocalTimeFromUtcTimeRequestExecutor = new FakeLocalTimeFromUtcTimeRequestExecutor(new DateTime(2014, 7, 4, 2, 48, 0, 0));

            xrmFakedContext.AddFakeMessageExecutor <LocalTimeFromUtcTimeRequest>(fakeLocalTimeFromUtcTimeRequestExecutor);

            const bool expected = false;

            //Act
            var result = xrmFakedContext.ExecuteCodeActivity <IsBusinessDay>(workflowContext, inputs);

            //Assert
            Assert.AreEqual(expected, result["ValidBusinessDay"]);
        }
Ejemplo n.º 57
0
        public void When_sorting_by_an_attribute_which_wasnt_initialised_an_exception_is_not_thrown()
        {
            var ctx = new XrmFakedContext();
            ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact));

            var service = ctx.GetFakedOrganizationService();
            ctx.Initialize(new List<Entity>() {
                new Contact() { Id = Guid.NewGuid(), FirstName = "Ronald", LastName = "Mcdonald" },
                new Contact() { Id = Guid.NewGuid(), LastName = "Jordan" }
            });

            using (var context = new XrmServiceContext(service))
            {
                var contacts = (from c in context.ContactSet
                                orderby c.FirstName
                                select new Contact { Id = c.Id, FirstName = c.FirstName, LastName = c.LastName }).ToList();

                Assert.Equal(2, contacts.Count);
                Assert.Null(contacts[0].FirstName);
            }
        }