public void When_doing_a_crm_linq_query_with_an_equals_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Jordi")
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));

                matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName == "Jordi" //Using now equality operator
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
            }
            
        }
        public void When_doing_a_crm_linq_query_and_proxy_types_and_a_selected_attribute_returned_projected_entity_is_thesubclass()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName.Equals("Jordi")
                               select new
                               {
                                   FirstName = c.FirstName,
                                   CrmRecord = c
                               }).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
                Assert.IsAssignableFrom(typeof(Contact), matches[0].CrmRecord);
                Assert.True(matches[0].CrmRecord.GetType() == typeof(Contact));

            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region Boilerplate
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);

            var tracing = executionContext.GetExtension <ITracingService>();
            #endregion

            var  entityIdString = EntityId.Get(executionContext);
            Guid entityId       = Guid.Empty;

            if (!Guid.TryParse(entityIdString, out entityId))
            {
                Succeeded.Set(executionContext, false);
                ErrorMessage.Set(executionContext, $"Guid {entityIdString} is not a valid GUID.");
                return;
            }

            var teamName = TeamName.Get(executionContext);
            using (var ctx = new XrmServiceContext(service))
            {
                var team = (from t in ctx.CreateQuery <Team>()
                            where t.Name == teamName
                            select t).FirstOrDefault();

                if (team == null)
                {
                    Succeeded.Set(executionContext, false);
                    ErrorMessage.Set(executionContext, $"Team {teamName} not found.");
                    return;
                }

                var logicalName = EntityName.Get(executionContext);
                var reference   = (from r in ctx.CreateQuery(logicalName)
                                   where (Guid)r[$"{logicalName}id"] == entityId
                                   select r).FirstOrDefault();

                if (reference == null)
                {
                    Succeeded.Set(executionContext, false);
                    ErrorMessage.Set(executionContext, $"Entity Reference with logical name {logicalName} and id {entityIdString} wasn't found.");
                    return;
                }

                //Assign otherwise
                var assignRequest = new AssignRequest()
                {
                    Assignee = team.ToEntityReference(),
                    Target   = reference.ToEntityReference()
                };
                service.Execute(assignRequest);
            }


            Succeeded.Set(executionContext, true);
        }
        public void When_querying_early_bound_entities_attribute_not_initialised_returns_null_in_joins()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var role = new Role()
            {
                Id = Guid.NewGuid()
            };
            var parentRole = new Role()
            {
                Id = Guid.NewGuid()
            };

            context.Initialize(new[] { role, parentRole });

            using (var ctx = new XrmServiceContext(service))
            {
                var roleResult = (from r in ctx.CreateQuery <Role>()
                                  join parent in ctx.CreateQuery <Role>() on r.ParentRoleId.Id equals parent.RoleId.Value
                                  select r).FirstOrDefault();

                Assert.Equal(roleResult, null);
            }
        }
        public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();

            var relationship = new XrmFakedRelationship()
            {
                IntersectEntity    = "accountleads",
                Entity1Attribute   = "accountid",
                Entity2Attribute   = "leadid",
                Entity1LogicalName = "account",
                Entity2LogicalName = "lead"
            };

            context.AddRelationship("accountleads", relationship);

            var service = context.GetFakedOrganizationService();

            using (var ctx = new XrmServiceContext(service))
            {
                var account = new Account()
                {
                    Name = "Test account"
                };
                ctx.AddObject(account);

                var contact = new Lead()
                {
                    FirstName = "Jane", LastName = "Doe"
                };
                ctx.AddRelatedObject(account, new Relationship("accountleads"), contact);
                var result = ctx.SaveChanges();

                var resultaccount = ctx.CreateQuery <Account>()
                                    .ToList()
                                    .FirstOrDefault();

                Assert.NotNull(resultaccount);
                Assert.Equal("Test account", resultaccount.Name);

                var reaultlead = ctx.CreateQuery <Lead>()
                                 .ToList()
                                 .FirstOrDefault();

                Assert.NotNull(reaultlead);
                Assert.Equal("Jane", reaultlead.FirstName);
                Assert.Equal("Doe", reaultlead.LastName);

                var relationshipRecords = ctx.CreateQuery("accountleads")
                                          .ToList();
                Assert.NotEmpty(relationshipRecords);
            }
        }
Esempio n. 6
0
        public void When_executing_a_linq_query_with_equals_between_2_activityparties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId  = Guid.NewGuid();
            var activityId = Guid.NewGuid();

            var partyRecord = new ActivityParty()
            {
                Id         = Guid.NewGuid(),
                ActivityId = new EntityReference(Email.EntityLogicalName, activityId),
                PartyId    = new EntityReference(Contact.EntityLogicalName, contactId)
            };

            fakedContext.Initialize(new List <Entity>()
            {
                new Email()
                {
                    Id = activityId, ActivityId = activityId, Subject = "Test email"
                },
                new ActivityPointer()
                {
                    Id = Guid.NewGuid(), ActivityId = activityId
                },
                partyRecord,
                new ActivityPointer()
                {
                    Id = Guid.NewGuid()
                },                                             //To test also nulls
                new ActivityParty()
                {
                    Id = Guid.NewGuid()
                }                                           //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var activities = (from pointer in ctx.CreateQuery <Email>()
                                  join party in ctx.CreateQuery <ActivityParty>() on pointer.ActivityId.Value equals party.ActivityId.Id
                                  // from party in ctx.CreateQuery<ActivityParty>() //on pointer.ActivityId.Value equals party.ActivityId.Id
                                  where party.PartyId.Id == contactId
                                  select pointer).ToList();

                Assert.True(activities.Count == 1);
            }
        }
Esempio n. 7
0
        public List <Entities.Subscriber> GetSubscribers(string listId)
        {
            try
            {
                List <Contact> subscribers = (from m in context.CreateQuery <ListMember>()
                                              join c in context.CreateQuery <Contact>() on m.EntityId.Id equals c.Id
                                              where m.ListId.Equals(listId)
                                              select c).ToList();

                return((List <Entities.Subscriber>)Mapper.Map <IList <Contact>, IList <Entities.Subscriber> >(subscribers));
            }
            catch (Exception e)
            {
                throw new Exception("Get marketing lists CRM (" + e.Message.ToString() + ")");
            }
        }
        public static void When_using_proxy_types_assembly_the_attribute_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact") { Id = Guid.NewGuid() }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact") { Id = Guid.NewGuid() }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

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

            var guid = Guid.NewGuid();

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

            var service = fakedContext.GetFakedOrganizationService();

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

                Assert.True(contact.Count == 1);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region Bolierplate
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);

            var tracing = executionContext.GetExtension <ITracingService>();
            #endregion

            var parameterName = ParameterName.Get(executionContext);
            using (var ctx = new XrmServiceContext(service))
            {
                var parameter = (from p in ctx.CreateQuery <ultra_systemparameter>()
                                 where p.ultra_name == parameterName
                                 select p.ultra_parametervalue)
                                .FirstOrDefault();

                if (parameter != null)
                {
                    ParameterValue.Set(executionContext, parameter);
                }
            }
        }
        protected override GenericResult ConcreteExecute(IOrganizationService service)
        {
            var contact     = PhoneCall.RegardingObjectId;
            var phoneNumber = PhoneCall.PhoneNumber;

            //query to create a phone history only if the pair [phonenumber, contact] doesn't exist
            using (var ctx = new XrmServiceContext(service))
            {
                var exists = (from ph in ctx.CreateQuery <ultra_phonecallhistory>()
                              where ph.ultra_contactid.Id == contact.Id
                              where ph.ultra_phonenumber == phoneNumber
                              select ph).FirstOrDefault() != null;

                if (!exists)
                {
                    //Create phone history record
                    var phoneHistory = new ultra_phonecallhistory()
                    {
                        ultra_contactid    = contact,
                        ultra_phonenumber  = phoneNumber,
                        ultra_lastcalldate = DateTime.Now
                    };
                    phoneHistory.Id = service.Create(phoneHistory);

                    //Phonecall then assigned to the created phonecall history
                    PhoneCall.ultra_phonecallhistoryid = phoneHistory.ToEntityReference();
                }
            }

            return(GenericResult.Succeed());
        }
Esempio n. 11
0
        public void When_executing_a_linq_query_with_equals_between_2_date_times_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid, BirthDate = new DateTime(2015, 02, 26, 3, 42, 59)
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.BirthDate != null && c.BirthDate == new DateTime(2015, 02, 26, 3, 42, 59)
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public static void When_using_proxy_types_assembly_the_finding_attribute_metadata_fails_if_neither_proxy_type_or_injected_metadata_exist()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["injectedAttribute"] = "Contact 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["injectedAttribute"] = "Contact 2";

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

            var guid = Guid.NewGuid();

            var service = fakedContext.GetOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                Assert.Throws <Exception>(() => (from c in ctx.CreateQuery <Contact>()
                                                 where c["injectedAttribute"].Equals("Contact 1")
                                                 select c).ToList());
            }
        }
Esempio n. 13
0
        public void When_doing_a_crm_linq_query_with_a_an_and_filter_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var taskId    = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            //Contact is related to first account, but because first account is not related to itself then the query must return 0 records
            fakedContext.Initialize(new List <Entity>()
            {
                new Task()
                {
                    Id = taskId, StatusCode = new OptionSetValue(2)
                },                                                              //Completed
                new Task()
                {
                    Id = Guid.NewGuid()
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from t in ctx.CreateQuery <Task>()
                               where t.StatusCode != null && t.StatusCode.Value == 2
                               select t).ToList();

                Assert.True(matches.Count == 1);
            }
        }
Esempio n. 14
0
        public void When_executing_a_linq_query_with_equals_between_2_booleans_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid, IsBackofficeCustomer = true
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.IsBackofficeCustomer != null && c.IsBackofficeCustomer.Value == true
                               where c.IsBackofficeCustomer.Value
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 15
0
        public void When_doing_a_crm_linq_query_with_an_optionset_with_nulls_against_nulls_in_where_filter_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = contactId, StatusCode = new OptionSetValue(1)
                },
                new Contact()
                {
                    Id = Guid.NewGuid(), StatusCode = null
                },
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               where c.StatusCode == null
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
Esempio n. 16
0
        public void When_executing_a_linq_query_with_equals_between_2_moneys_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new SalesOrderDetail()
                {
                    Id = guid, BaseAmount = new Money(1.1M)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid()
                }                                              //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <SalesOrderDetail>()
                               where c.BaseAmount == new Money(1.1M)
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 17
0
        public void When_executing_a_linq_query_with_equals_between_2_boolean_managed_properties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Report()
                {
                    Id = guid, IsCustomizable = new BooleanManagedProperty(true)
                },
                new Report()
                {
                    Id = Guid.NewGuid()
                }                                    //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Report>()
                               where c.IsCustomizable.Value == true
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 18
0
        public void When_doing_a_crm_linq_query_with_an_entity_reference_with_nulls_against_nulls_in_where_filter_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = accountId
                },
                new Contact()
                {
                    Id = Guid.NewGuid(),
                    ParentCustomerId = null
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               where c.ParentCustomerId == null
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
Esempio n. 19
0
        public void When_doing_a_crm_linq_query_with_a_not_contains_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1        = Guid.NewGuid();
            var guid2        = Guid.NewGuid();
            var guid3        = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid1, FirstName = "Jordi Garcia"
                },
                new Contact()
                {
                    Id = guid2, FirstName = "Javi Garcia"
                },
                new Contact()
                {
                    Id = guid3, FirstName = "Other"
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               where !c.FirstName.Contains("Garcia")
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Other"));
            }
        }
        public static void When_using_proxy_types_assembly_the_attribute_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact1 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact")
            {
                Id = Guid.NewGuid()
            }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

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

            var guid = Guid.NewGuid();

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

            var service = fakedContext.GetOrganizationService();

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

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 21
0
        public void When_using_typed_entities_ProxyTypesAssembly_is_not_mandatory()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

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

            //Linq 2 Query Expression
            using (var ctx = new XrmServiceContext(service))
            {
                var contacts = (from con in ctx.CreateQuery <Contact>()
                                select con).ToList();

                Assert.Equal(contacts.Count, 1);
            }

            //Query faked context directly
            var ex = Record.Exception(() => context.CreateQuery <Contact>());

            Assert.Null(ex);
        }
Esempio n. 22
0
        public void When_executing_a_linq_query_with_equals_between_2_guids_result_is_returned()
        {
            var fakedContext       = new XrmFakedContext();
            var productId          = Guid.NewGuid();
            var salesOrderDetailId = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new SalesOrderDetail()
                {
                    Id = salesOrderDetailId, ProductId = new EntityReference(Product.EntityLogicalName, productId)
                },
                new SalesOrderDetail()
                {
                    Id = Guid.NewGuid()
                }                                              //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from s in ctx.CreateQuery <SalesOrderDetail>()
                               where s.SalesOrderDetailId == salesOrderDetailId
                               select s).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 23
0
        public void When_executing_a_linq_query_with_equals_between_2_optionsets_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var productId    = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = Guid.NewGuid(), StatusCode = new OptionSetValue(1)
                },
                new Account()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from a in ctx.CreateQuery <Account>()
                               where a.StatusCode == new OptionSetValue(1)
                               select a).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_an_entity_is_returned_formatted_values_are_also_cloned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

            account["statecode"] = new OptionSetValue(0);

            var formattedValues = new FormattedValueCollection();

            formattedValues.Add("statecode", "Active");
            account.Inject("FormattedValues", formattedValues);

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery <Account>()
                         select acc).FirstOrDefault();

                Assert.True(a.FormattedValues != null);
                Assert.True(a.FormattedValues.Contains("statecode"));
                Assert.Equal("Active", a.FormattedValues["statecode"]);
            }
        }
        public void When_an_optionset_is_retrieved_where_its_value_is_an_enum_formatted_value_is_returned()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

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

            account["statecode"] = AccountState.Active;

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery <Account>()
                         select acc).FirstOrDefault();

                Assert.True(a.FormattedValues != null);
                Assert.True(a.FormattedValues.Contains("statecode"));
                Assert.Equal("Active", a.FormattedValues["statecode"]);
            }
        }
        public void When_doing_a_crm_linq_query_and_proxy_types_projection_must_be_applied_after_where_clause()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = "Jordi", LastName = "Montana" },
                new Contact() { Id = guid2, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.LastName == "Montana"  //Should be able to filter by a non-selected attribute
                               select new
                               {
                                   FirstName = c.FirstName
                               }).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName.Equals("Jordi"));
            }
        }
Esempio n. 27
0
        public void When_doing_a_crm_linq_query_with_a_not_null_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1        = Guid.NewGuid();
            var guid2        = Guid.NewGuid();
            var guid3        = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid1, FirstName = null
                },
                new Contact()
                {
                    Id = guid2
                },                            //FirstName attribute omitted
                new Contact()
                {
                    Id = guid3, FirstName = "Other"
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               where c.FirstName != null
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName == "Other");
            }
        }
Esempio n. 28
0
        public void CheckPhoneCallHistory()
        {
            string crmCon = ConfigurationManager.ConnectionStrings["crm"].ConnectionString;

            using (CrmServiceClient svc = new CrmServiceClient(crmCon))
            {
                Contact c = new Contact();
                c.FirstName   = "Wael";
                c.LastName    = Guid.NewGuid().ToString();
                c.MobilePhone = new Random().Next(100000000, 200000000).ToString();

                c.Id = svc.Create(c);

                PhoneCall p = new PhoneCall();
                p.RegardingObjectId = c.ToEntityReference();
                p.PhoneNumber       = c.MobilePhone;

                p.Id = svc.Create(p);

                using (var ctx = new XrmServiceContext(svc))
                {
                    var exists = (from ph in ctx.CreateQuery <ultra_phonecallhistory>()
                                  where ph.ultra_contactid.Id == c.Id
                                  where ph.ultra_phonenumber == c.MobilePhone
                                  select ph).FirstOrDefault() != null;

                    Assert.IsTrue(exists);
                }
            }
        }
Esempio n. 29
0
        public void When_doing_a_crm_linq_query_with_a_less_than_or_equal_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1        = Guid.NewGuid();
            var guid2        = Guid.NewGuid();
            var guid3        = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid1, NumberOfChildren = 3
                },
                new Contact()
                {
                    Id = guid2, NumberOfChildren = 1
                },
                new Contact()
                {
                    Id = guid3, NumberOfChildren = 2
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               where c.NumberOfChildren.Value <= 3
                               select c).ToList();

                Assert.True(matches.Count == 3);
            }
        }
Esempio n. 30
0
        public void When_executing_a_linq_query_with_equals_between_2_longs_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid         = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Contact()
                {
                    Id = guid
                },
                new Contact()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            fakedContext.Data["contact"][guid]["versionnumber"] = long.MaxValue; //Couldn´t be set by the Proxy types but set here just for testing long data types

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery <Contact>()
                               where c.VersionNumber == long.MaxValue
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 31
0
        public void When_executing_a_linq_query_with_equals_between_2_doubles_result_is_returned()
        {
            var fakedContext      = new XrmFakedContext();
            var guid              = Guid.NewGuid();
            var barcelonaLatitude = 41.387128;

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = guid, Address1_Latitude = barcelonaLatitude
                },
                new Account()
                {
                    Id = Guid.NewGuid()
                }                                     //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from a in ctx.CreateQuery <Account>()
                               where a.Address1_Latitude == barcelonaLatitude
                               select a).ToList();

                Assert.True(contact.Count == 1);
            }
        }
Esempio n. 32
0
        public void When_a_member_is_added_to_an_existing_list_member_is_added_successfully_lead()
        {
            var ctx     = new XrmFakedContext();
            var service = ctx.GetOrganizationService();

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

            var lead = new Lead()
            {
                Id = Guid.NewGuid()
            };

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

            AddListMembersListRequest addListMembersListRequest = new AddListMembersListRequest
            {
                MemberIds = new[]
                {
                    lead.Id
                },
                ListId = list.ToEntityReference().Id
            };

            service.Execute(addListMembersListRequest);

            using (var context = new XrmServiceContext(service))
            {
                var member = (from lm in context.CreateQuery <ListMember>()
                              join l in context.CreateQuery <Crm.List>() on lm.ListId.Id equals l.ListId.Value
                              join le in context.CreateQuery <Lead>() on lm.EntityId.Id equals le.LeadId.Value
                              where lm.EntityId.Id == lead.Id
                              where lm.ListId.Id == list.Id
                              select lm
                              ).FirstOrDefault();

                Assert.NotNull(member);
            }
        }
Esempio n. 33
0
        public void When_doing_a_join_with_filter_then_can_filter_by_the_joined_entity_attributes()
        {
            //REVIEW: Different implementations of the ConditionExpression class in Microsoft.Xrm.Sdk (which has EntityName property for versions >= 2013)

            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId  = Guid.NewGuid();
            var accountId  = Guid.NewGuid();
            var accountId2 = Guid.NewGuid();

            //Contact is related to first account, but because first account is not related to itself then the query must return 0 records
            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = accountId, Name = "Account1"
                },
                new Account()
                {
                    Id = accountId2, Name = "Account2"
                },
                new Contact()
                {
                    Id = contactId, ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId),
                    NumberOfChildren = 2, FirstName = "Contact"
                },
                new Contact()
                {
                    Id = Guid.NewGuid(), ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId2)
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               join account in ctx.CreateQuery <Account>() on c.ParentCustomerId.Id equals account.AccountId
                               where account.Name == "Account1"
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_calling_context_add_addrelated_and_save_changes_entities_are_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();

            var relationship = new XrmFakedRelationship()
            {
                IntersectEntity = "accountleads",
                Entity1Attribute = "accountid",
                Entity2Attribute = "leadid",
                Entity1LogicalName = "account",
                Entity2LogicalName = "lead"
            };
            context.AddRelationship("accountleads", relationship);

            var service = context.GetFakedOrganizationService();

            using (var ctx = new XrmServiceContext(service))
            {
                var account = new Account() { Name = "Test account" };
                ctx.AddObject(account);

                var contact = new Lead() { FirstName = "Jane", LastName = "Doe" };
                ctx.AddRelatedObject(account, new Relationship("accountleads"), contact);
                var result = ctx.SaveChanges();

                var resultaccount = ctx.CreateQuery<Account>()
                                       .ToList()
                                       .FirstOrDefault();

                Assert.NotNull(resultaccount);
                Assert.Equal("Test account", resultaccount.Name);

                var reaultlead = ctx.CreateQuery<Lead>()
                                    .ToList()
                                    .FirstOrDefault();

                Assert.NotNull(reaultlead);
                Assert.Equal("Jane", reaultlead.FirstName);
                Assert.Equal("Doe", reaultlead.LastName);

                var relationshipRecords = ctx.CreateQuery("accountleads")
                                             .ToList();
                Assert.NotEmpty(relationshipRecords);
            }
        }
Esempio n. 35
0
        public void When_doing_a_crm_linq_query_with_a_leftjoin_with_a_where_expression_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();

            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            fakedContext.Initialize(new List <Entity>()
            {
                new Account()
                {
                    Id = accountId
                },
                new Contact()
                {
                    Id = contactId, ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId),
                    NumberOfChildren = 2
                },
                new Contact()
                {
                    Id = Guid.NewGuid(), ParentCustomerId = null, NumberOfChildren = 2
                },
                new Contact()
                {
                    Id = Guid.NewGuid(), ParentCustomerId = null, NumberOfChildren = 3
                }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery <Contact>()
                               join a in ctx.CreateQuery <Account>() on c.ParentCustomerId.Id equals a.AccountId into joinedAccounts
                               from account in joinedAccounts.DefaultIfEmpty()
                               where c.NumberOfChildren == 2
                               select c).ToList();

                Assert.True(matches.Count == 2);
            }
        }
        public void When_calling_context_add_and_save_changes_entity_is_added_to_the_faked_context()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            using(var ctx = new XrmServiceContext(service))
            {
                ctx.AddObject(new Account() { Name = "Test account" });
                ctx.SaveChanges();

                var account = ctx.CreateQuery<Account>()
                            .ToList()
                            .FirstOrDefault();

                Assert.Equal("Test account", account.Name);
            }
        }
        public static void When_using_proxy_types_assembly_the_entity_metadata_is_inferred_from_the_proxy_types_assembly()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();
           
            //Empty contecxt (no Initialize), but we should be able to query any typed entity without an entity not found exception

            var service = fakedContext.GetFakedOrganizationService();

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

                Assert.True(contact.Count == 0);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_strings_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, FirstName = "Jordi" }
            });

            var service = fakedContext.GetFakedOrganizationService();

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

                Assert.True(contact != null);
            }
        }
        public void When_doing_a_crm_linq_query_a_retrievemultiple_with_a_queryexpression_is_called()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, FirstName = "Jordi" }
            });

            var service = fakedContext.GetFakedOrganizationService();

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


            }
            A.CallTo(() => service.Execute(A<OrganizationRequest>.That.Matches(x => x is RetrieveMultipleRequest && ((RetrieveMultipleRequest)x).Query is QueryExpression))).MustHaveHappened();
        }
        public void When_executing_a_linq_query_with_equals_between_2_boolean_managed_properties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Report() { Id = guid, IsCustomizable = new BooleanManagedProperty(true) },
                new Report() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Report>()
                               where c.IsCustomizable.Value == true
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_booleans_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid, IsBackofficeCustomer = true},
                new Contact() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<Contact>()
                               where c.IsBackofficeCustomer != null && c.IsBackofficeCustomer.Value == true
                               where c.IsBackofficeCustomer.Value
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_an_optionset_is_retrieved_where_its_value_is_an_enum_formatted_value_doesnt_contain_key_if_value_was_null()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var account = new Account() { Id = Guid.NewGuid() };
            account["statecode"] = null;

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

            using (var ctx = new XrmServiceContext(service))
            {
                var a = (from acc in ctx.CreateQuery<Account>()
                         select acc).FirstOrDefault();

                Assert.Equal(0, a.FormattedValues.Count);
                Assert.False(a.FormattedValues.Contains("statecode"));
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_guids_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var productId = Guid.NewGuid();
            var salesOrderDetailId = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new SalesOrderDetail() { Id = salesOrderDetailId, ProductId = new EntityReference(Product.EntityLogicalName, productId) },
                new SalesOrderDetail() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from s in ctx.CreateQuery<SalesOrderDetail>()
                               where s.SalesOrderDetailId == salesOrderDetailId
                               select s).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        public void When_doing_a_join_with_filter_then_can_filter_by_the_joined_entity_attributes()
        {
            //REVIEW: Different implementations of the ConditionExpression class in Microsoft.Xrm.Sdk (which has EntityName property for versions >= 2013)
             
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();
            var accountId2 = Guid.NewGuid();

            //Contact is related to first account, but because first account is not related to itself then the query must return 0 records
            fakedContext.Initialize(new List<Entity>() {
                new Account() { Id = accountId, Name="Account1" },
                new Account() { Id = accountId2, Name = "Account2" },
                new Contact() { Id = contactId, ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId),
                                                NumberOfChildren = 2, FirstName = "Contact" },
                new Contact() {Id = Guid.NewGuid(), ParentCustomerId =  new EntityReference(Account.EntityLogicalName, accountId2) }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               join account in ctx.CreateQuery<Account>() on c.ParentCustomerId.Id equals account.AccountId
                               where account.Name == "Account1"
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_and_selecting_an_entire_object_all_attributes_are_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contact = new Contact() { Id = Guid.NewGuid(), FirstName = "Chuck" };
            var parentAccount = new Account()
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = contact.ToEntityReference()
            };
            var account = new Account()
            {
                Id = Guid.NewGuid(),
                ParentAccountId = parentAccount.ToEntityReference()
            };

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

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from childAccount in ctx.CreateQuery<Account>()
                               join childsParentAccount in ctx.CreateQuery<Account>() on childAccount.ParentAccountId.Id equals childsParentAccount.AccountId
                               join primaryContact in ctx.CreateQuery<Contact>() on childsParentAccount.PrimaryContactId.Id equals primaryContact.ContactId
                               select new
                               {
                                   Contact = primaryContact
                               }).ToList();

                Assert.True(matches.Count == 1);
                Assert.Equal(matches[0].Contact.Attributes.Count, 6 + 1);
            }
        }
        public void When_doing_a_crm_linq_query_with_2_and_filters_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var taskId = Guid.NewGuid();
            var accountId = Guid.NewGuid();
            var euroId = Guid.NewGuid();

            //Contact is related to first account, but because first account is not related to itself then the query must return 0 records
            fakedContext.Initialize(new List<Entity>() {
                new Task() { Id = taskId, StatusCode = new OptionSetValue(1), 
                                          TransactionCurrencyId = new EntityReference(TransactionCurrency.EntityLogicalName, euroId) }, 
                new Task() { Id = Guid.NewGuid()  }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from t in ctx.CreateQuery<Task>()
                               where t.StatusCode != null && t.StatusCode.Value == 1
                               where t.TransactionCurrencyId != null && t.TransactionCurrencyId.Id == euroId
                               select t).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_that_produces_a_filter_expression_plus_condition_expression_at_same_level_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var taskId = Guid.NewGuid();
            var accountId = Guid.NewGuid();
            var euroId = Guid.NewGuid();

            //Contact is related to first account, but because first account is not related to itself then the query must return 0 records
            fakedContext.Initialize(new List<Entity>() {
                new Task() { Id = taskId, StatusCode = new OptionSetValue(1), 
                                          TransactionCurrencyId = new EntityReference(TransactionCurrency.EntityLogicalName, euroId) }, 
                new Task() { Id = Guid.NewGuid(), StatusCode = new OptionSetValue(2), 
                                          TransactionCurrencyId = new EntityReference(TransactionCurrency.EntityLogicalName, euroId) }, 
                
                new Task() { Id = Guid.NewGuid()  }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from t in ctx.CreateQuery<Task>()
                               where t.StatusCode != null && (
                                            t.StatusCode.Value == 1 || t.StatusCode.Value == 2)
                                        //StatusCode != null is converted into a ConditionExpression plus
                                        //t.StatusCode.Value == 1 || t.StatusCode.Value == 2 is converted into a FilterExpression
                               where t.TransactionCurrencyId != null && t.TransactionCurrencyId.Id == euroId
                                        //Second where is converted as FilterExpression, but without a sibling condition
                               select t).ToList();

                Assert.True(matches.Count == 2);
            }
        }
        public void When_doing_a_crm_linq_query_with_an_intersect_entity_and_2_levels_of_joins_and_where_clauses_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var parentRole = new Role() { Id = Guid.NewGuid(), Name = "System Administrator" };
            var role = new Role() { Id = Guid.NewGuid(), Name = "Sys Admin" };
            var user = new SystemUser() { Id = Guid.NewGuid(), FirstName = "Jordi" };
            var systemRole = new SystemUserRoles() { Id = Guid.NewGuid() };
            
            

            role["parentroleid"] = parentRole.ToEntityReference();
            systemRole["systemuserid"] = user.ToEntityReference();
            systemRole["roleid"] = role.ToEntityReference();

            
            fakedContext.Initialize(new List<Entity>() {
                user, systemRole, role, parentRole
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from sr in ctx.CreateQuery<SystemUserRoles>()
                               join r in ctx.CreateQuery<Role>() on sr.RoleId equals r.RoleId
                               join u in ctx.CreateQuery<SystemUser>() on sr.SystemUserId equals u.SystemUserId

                               where u.FirstName == "Jordi"
                               where r.Name == "Sys Admin"
                               select sr).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_with_a_not_null_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();
            var guid3 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, FirstName = null },
                new Contact() { Id = guid2 }, //FirstName attribute omitted
                new Contact() { Id = guid3, FirstName = "Other" }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.FirstName != null
                               select c).ToList();

                Assert.True(matches.Count == 1);
                Assert.True(matches[0].FirstName == "Other");
            }
        }
        public void When_doing_a_crm_linq_query_with_an_optionset_with_nulls_against_nulls_in_where_filter_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = contactId, StatusCode = new OptionSetValue(1) },
                new Contact() { Id = Guid.NewGuid(), StatusCode = null },
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.StatusCode == null
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_with_an_innerjoin_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Account() { Id = accountId },
                new Contact() { Id = contactId, 
                                ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId) },
                new Contact() { Id = Guid.NewGuid(), 
                                ParentCustomerId = null }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               join a in ctx.CreateQuery<Account>() on c.ParentCustomerId.Id equals a.AccountId
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_with_an_entity_reference_with_nulls_against_nulls_in_where_filter_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Account() { Id = accountId },
                new Contact() { Id = Guid.NewGuid(), 
                                ParentCustomerId = null }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.ParentCustomerId == null
                               select c).ToList();

                Assert.True(matches.Count == 1);
            }
        }
        public void When_doing_a_crm_linq_query_with_a_less_than_or_equal_operator_record_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid1 = Guid.NewGuid();
            var guid2 = Guid.NewGuid();
            var guid3 = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Contact() { Id = guid1, NumberOfChildren = 3 },
                new Contact() { Id = guid2, NumberOfChildren = 1 },
                new Contact() { Id = guid3, NumberOfChildren = 2 }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               where c.NumberOfChildren.Value <= 3
                               select c).ToList();

                Assert.True(matches.Count == 3);
            }
        }
        public void When_querying_early_bound_entities_attribute_not_initialised_returns_null_in_joins()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var role = new Role() { Id = Guid.NewGuid() };
            var parentRole = new Role() { Id = Guid.NewGuid() };

            context.Initialize(new[] { role, parentRole });

            using(var ctx = new XrmServiceContext(service))
            {
                var roleResult = (from r in ctx.CreateQuery<Role>()
                                    join parent in ctx.CreateQuery<Role>() on r.ParentRoleId.Id equals parent.RoleId.Value
                                   select r).FirstOrDefault();

                Assert.Equal(roleResult, null);
            }
        }
        public void When_using_typed_entities_ProxyTypesAssembly_is_not_mandatory()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            var c = new Contact() { Id = Guid.NewGuid(), FirstName = "Jordi" };
            context.Initialize(new List<Entity>() { c });

            //Linq 2 Query Expression
            using (var ctx = new XrmServiceContext(service))
            {
                var contacts = (from con in ctx.CreateQuery<Contact>()
                                select con).ToList();

                Assert.Equal(contacts.Count, 1);
            }

            //Query faked context directly
            Assert.DoesNotThrow(() => context.CreateQuery<Contact>());
        }
        public void When_doing_a_crm_linq_query_with_a_leftjoin_with_a_where_expression_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var accountId = Guid.NewGuid();

            fakedContext.Initialize(new List<Entity>() {
                new Account() { Id = accountId },
                new Contact() { Id = contactId, ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId),
                                                NumberOfChildren = 2},
                new Contact() { Id = Guid.NewGuid(), ParentCustomerId = null, NumberOfChildren = 2 },
                new Contact() { Id = Guid.NewGuid(), ParentCustomerId = null, NumberOfChildren = 3 }
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var matches = (from c in ctx.CreateQuery<Contact>()
                               join a in ctx.CreateQuery<Account>() on c.ParentCustomerId.Id equals a.AccountId into joinedAccounts
                               from account in joinedAccounts.DefaultIfEmpty()
                               where c.NumberOfChildren == 2
                               select c).ToList();

                Assert.True(matches.Count == 2);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_activityparties_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly();

            var contactId = Guid.NewGuid();
            var activityId = Guid.NewGuid();

            var partyRecord = new ActivityParty()
            {
                Id = Guid.NewGuid(),
                ActivityId = new EntityReference(Email.EntityLogicalName, activityId),
                PartyId = new EntityReference(Contact.EntityLogicalName, contactId)
            };

            fakedContext.Initialize(new List<Entity>() {
                new Email() { Id = activityId, ActivityId = activityId, Subject = "Test email"},
                new ActivityPointer () { Id = Guid.NewGuid(), ActivityId = activityId },
                partyRecord,
                new ActivityPointer() { Id = Guid.NewGuid()},  //To test also nulls
                new ActivityParty() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var activities = (from pointer in ctx.CreateQuery<Email>()
                                  join party in ctx.CreateQuery<ActivityParty>() on pointer.ActivityId.Value equals party.ActivityId.Id
                                 // from party in ctx.CreateQuery<ActivityParty>() //on pointer.ActivityId.Value equals party.ActivityId.Id
                                    where party.PartyId.Id == contactId
                                  select pointer).ToList();

                Assert.True(activities.Count == 1);
            }
        }
        public void When_executing_a_linq_query_with_equals_between_2_moneys_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var guid = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new SalesOrderDetail() { Id = guid, BaseAmount = new Money(1.1M) },
                new SalesOrderDetail() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from c in ctx.CreateQuery<SalesOrderDetail>()
                               where c.BaseAmount == new Money(1.1M)
                               select c).ToList();

                Assert.True(contact.Count == 1);
            }
        }
        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);
        }
        public void When_executing_a_linq_query_with_equals_between_2_optionsets_result_is_returned()
        {
            var fakedContext = new XrmFakedContext();
            var productId = Guid.NewGuid();
            fakedContext.Initialize(new List<Entity>() {
                new Account() { Id = Guid.NewGuid(), StatusCode = new OptionSetValue(1) },
                new Account() { Id = Guid.NewGuid()}  //To test also nulls
            });

            var service = fakedContext.GetFakedOrganizationService();

            using (XrmServiceContext ctx = new XrmServiceContext(service))
            {
                var contact = (from a in ctx.CreateQuery<Account>()
                               where a.StatusCode == new OptionSetValue(1)
                               select a).ToList();

                Assert.True(contact.Count == 1);
            }
        }