public void When_the_create_task_activity_is_executed_a_task_is_created_in_the_context() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var guid1 = Guid.NewGuid(); var account = new Account() { Id = guid1 }; fakedContext.Initialize(new List<Entity>() { account }); //Inputs var inputs = new Dictionary<string, object>() { { "inputEntity", account.ToEntityReference() } }; var result = fakedContext.ExecuteCodeActivity<CreateTaskActivity>(inputs); //The wf creates an activity, so make sure it is created var tasks = (from t in fakedContext.CreateQuery<Task>() select t).ToList(); //The activity creates a taks Assert.True(tasks.Count == 1); var output = result["taskCreated"] as EntityReference; //Task created contains the account passed as the regarding Id Assert.True(tasks[0].RegardingObjectId != null && tasks[0].RegardingObjectId.Id.Equals(guid1)); //Same task created is returned Assert.Equal(output.Id, tasks[0].Id); }
public static IQueryable <Entity> TranslateQueryExpressionToLinq(XrmFakedContext context, QueryExpression qe) { if (qe == null) { return(null); } //Start form the root entity and build a LINQ query to execute the query against the In-Memory context: context.EnsureEntityNameExistsInMetadata(qe.EntityName); IQueryable <Entity> query = null; query = context.CreateQuery <Entity>(qe.EntityName); //Add as many Joins as linked entities foreach (LinkEntity le in qe.LinkEntities) { query = TranslateLinkedEntityToLinq(context, le, query, qe.ColumnSet); } // Compose the expression tree that represents the parameter to the predicate. ParameterExpression entity = Expression.Parameter(typeof(Entity)); var expTreeBody = TranslateQueryExpressionFiltersToExpression(qe, entity); Expression <Func <Entity, bool> > lambda = Expression.Lambda <Func <Entity, bool> >(expTreeBody, entity); query = query.Where(lambda); //Project the attributes in the root column set (must be applied after the where clause, not before!!) query = query.Select(x => x.ProjectAttributes(qe, context)); //Sort results if (qe.Orders != null) { foreach (var order in qe.Orders) { if (order.OrderType == OrderType.Ascending) { query = query.OrderBy(e => e.Attributes.ContainsKey(order.AttributeName) ? e.Attributes[order.AttributeName] : null, new XrmOrderByAttributeComparer()); } else { query = query.OrderByDescending(e => e.Attributes.ContainsKey(order.AttributeName) ? e.Attributes[order.AttributeName] : null, new XrmOrderByAttributeComparer()); } } } //Apply TopCount if (qe.TopCount != null) { query = query.Take(qe.TopCount.Value); } return(query); }
public void Querying_an_early_bound_entity_not_present_in_the_context_should_return_no_records() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); //Find the contact var contact = (from c in context.CreateQuery<Contact>() select c).ToList(); Assert.Equal(contact.Count, 0); }
public void When_creating_a_record_using_dynamic_entities_primary_key_should_be_populated() { var context = new XrmFakedContext(); Entity e = new Entity("new_myentity"); IOrganizationService service = context.GetFakedOrganizationService(); var id = service.Create(e); //Retrieve the record created var record = (from r in context.CreateQuery("new_myentity") select r).FirstOrDefault(); Assert.True(record.Attributes.ContainsKey("new_myentityid")); Assert.Equal(id, record["new_myentityid"]); }
public void When_the_followup_plugin_is_executed_for_an_account_it_should_create_a_new_task() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); //Needed to be able to return early bound entities var guid1 = Guid.NewGuid(); var target = new Entity("account") { Id = guid1 }; fakedContext.ExecutePluginWithTarget<FollowupPlugin>(target); //The plugin creates a followup activity, check that that one exists var tasks = (from t in fakedContext.CreateQuery<Task>() select t).ToList(); Assert.True(tasks.Count == 1); Assert.True(tasks[0]["subject"].Equals("Send e-mail to the new customer.")); }
public void After_querying_the_context_with_an_invalid_entity_name_exception_is_thrown() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var guid = Guid.NewGuid(); var data = new List<Entity>() { new Contact() { Id = guid } }.AsQueryable(); context.Initialize(data); Assert.Throws<Exception>(() => { var query = (from c in context.CreateQuery(" ") select c); }); }
public void Should_create_a_new_entity_when_calling_create() { var ctx = new XrmFakedContext(); var logSystem = A.Fake<IDetailedLog>(); var service = ctx.GetOrganizationService(); //Arrange var actions = new Actions(logSystem, service); var contact = new Entity("contact"); contact["fullname"] = "Lionel Messi"; //Act actions.Create(contact); //Assert var contactCreated = ctx.CreateQuery("contact").FirstOrDefault(); Assert.NotNull(contactCreated); Assert.Equal(contactCreated["fullname"], "Lionel Messi"); }
public void After_adding_a_contact_the_create_query_returns_it() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); var service = context.GetFakedOrganizationService(); var guid = Guid.NewGuid(); var data = new List<Entity>() { new Contact() { Id = guid } }.AsQueryable(); context.Initialize(data); //Find the contact var contact = (from c in context.CreateQuery<Contact>() where c.ContactId == guid select c).FirstOrDefault(); Assert.False(contact == null); Assert.Equal(guid, contact.Id); }
public void Should_delete_an_entisting_record_when_calling_delete() { var ctx = new XrmFakedContext(); var logSystem = A.Fake<IDetailedLog>(); var service = ctx.GetOrganizationService(); //Arrange var contact = new Entity("contact") { Id = Guid.NewGuid() }; contact["fullname"] = "Lionel Messi"; ctx.Initialize(new Entity[] { contact }); //Act var actions = new Actions(logSystem, service); actions.Delete(contact.Id, "contact"); //Assert var contacts = ctx.CreateQuery("contact").ToList(); Assert.Equal(0, contacts.Count); }
public void When_updating_an_entity_an_unchanged_attribute_remains_the_same() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account)); var existingAccount = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" }; context.Initialize(new List<Entity>() { existingAccount }); var service = context.GetFakedOrganizationService(); //Create a new entity class to update the name var accountToUpdate = new Account() { Id = existingAccount.Id }; accountToUpdate.Name = "Super Great Customer Name Updated!"; //Update the entity in the context service.Update(accountToUpdate); //Make sure existing entity still maintains AccountNumber property var account = context.CreateQuery<Account>().FirstOrDefault(); Assert.Equal(account.AccountNumber, "69"); }
public void When_creating_a_record_using_early_bound_entities_primary_key_should_be_populated() { var context = new XrmFakedContext(); var c = new Contact(); IOrganizationService service = context.GetFakedOrganizationService(); var id = service.Create(c); //Retrieve the record created var contact = (from con in context.CreateQuery<Contact>() select con).FirstOrDefault(); Assert.True(contact.Attributes.ContainsKey("contactid")); Assert.Equal(id, contact["contactid"]); }
public void Should_update_an_entity_when_calling_update() { var ctx = new XrmFakedContext(); var logSystem = A.Fake<IDetailedLog>(); var service = ctx.GetOrganizationService(); //Arrange var contact = new Entity("contact") { Id = Guid.NewGuid() }; contact["fullname"] = "Lionel Messi"; ctx.Initialize(new Entity[] { contact }); //Act var contactToUpdate = new Entity("contact") { Id = contact.Id }; contactToUpdate["fullname"] = "Luis Suárez"; var actions = new Actions(logSystem, service); actions.Update(contactToUpdate); //Assert var contacts = ctx.CreateQuery("contact").ToList(); Assert.Equal(1, contacts.Count); Assert.Equal(contacts[0]["fullname"], "Luis Suárez"); }
public void When_related_entities_and_relationship_are_used_child_entities_are_created() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); ctx.AddRelationship("order_details", new XrmFakedRelationship() { Entity1LogicalName = SalesOrder.EntityLogicalName, //Referenced Entity1Attribute = "salesorderid", //Pk Entity2LogicalName = SalesOrderDetail.EntityLogicalName, Entity2Attribute = "salesorderid", //Lookup attribute RelationshipType = XrmFakedRelationship.enmFakeRelationshipType.OneToMany }); var order = new SalesOrder(); var orderItems = new EntityCollection(new List<Entity>() { new SalesOrderDetail(), new SalesOrderDetail() }); // Add related order items so it can be created in one request order.RelatedEntities.Add(new Relationship { PrimaryEntityRole = EntityRole.Referenced, SchemaName = "order_details" }, orderItems); var request = new CreateRequest { Target = order }; var id = (service.Execute(request) as CreateResponse).id; var createdOrderDetails = ctx.CreateQuery<SalesOrderDetail>().ToList(); Assert.Equal(createdOrderDetails.Count, 2); Assert.Equal(createdOrderDetails[0].SalesOrderId.Id, id); Assert.Equal(createdOrderDetails[1].SalesOrderId.Id, id); }
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); }
public static IQueryable <Entity> TranslateLinkedEntityToLinq(XrmFakedContext context, LinkEntity le, IQueryable <Entity> query, ColumnSet previousColumnSet, string linkFromAlias = "") { var leAlias = string.IsNullOrWhiteSpace(le.EntityAlias) ? le.LinkToEntityName : le.EntityAlias; context.EnsureEntityNameExistsInMetadata(le.LinkFromEntityName); context.EnsureEntityNameExistsInMetadata(le.LinkToEntityName); if (!context.AttributeExistsInMetadata(le.LinkToEntityName, le.LinkToAttributeName)) { OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(le.LinkToAttributeName); } var inner = context.CreateQuery <Entity>(le.LinkToEntityName); //if (!le.Columns.AllColumns && le.Columns.Columns.Count == 0) //{ // le.Columns.AllColumns = true; //Add all columns in the joined entity, otherwise we can't filter by related attributes, then the Select will actually choose which ones we need //} if (string.IsNullOrWhiteSpace(linkFromAlias)) { linkFromAlias = le.LinkFromAttributeName; } else { linkFromAlias += "." + le.LinkFromAttributeName; } switch (le.JoinOperator) { case JoinOperator.Inner: case JoinOperator.Natural: query = query.Join(inner, outerKey => outerKey.KeySelector(linkFromAlias, context), innerKey => innerKey.KeySelector(le.LinkToAttributeName, context), (outerEl, innerEl) => outerEl .JoinAttributes(innerEl, new ColumnSet(true), leAlias, context)); break; case JoinOperator.LeftOuter: query = query.GroupJoin(inner, outerKey => outerKey.KeySelector(le.LinkFromAttributeName, context), innerKey => innerKey.KeySelector(le.LinkToAttributeName, context), (outerEl, innerElemsCol) => new { outerEl, innerElemsCol }) .SelectMany(x => x.innerElemsCol.DefaultIfEmpty() , (x, y) => x.outerEl .JoinAttributes(y, new ColumnSet(true), leAlias, context)); break; default: //This shouldn't be reached as there are only 3 types of Join... throw new PullRequestException(string.Format("The join operator {0} is currently not supported. Feel free to implement and send a PR.", le.JoinOperator)); } //Process nested linked entities recursively foreach (LinkEntity nestedLinkedEntity in le.LinkEntities) { if (string.IsNullOrWhiteSpace(le.EntityAlias)) { le.EntityAlias = le.LinkToEntityName; } query = TranslateLinkedEntityToLinq(context, nestedLinkedEntity, query, le.Columns, le.EntityAlias); } return(query); }
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_updating_an_entity_only_one_entity_is_updated() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account)); var existingAccount = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" }; var otherExistingAccount = new Account() { Id = Guid.NewGuid(), Name = "Devil Customer", AccountNumber = "666" }; context.Initialize(new List<Entity>() { existingAccount, otherExistingAccount }); var service = context.GetFakedOrganizationService(); //Create a new entity class to update the first account var accountToUpdate = new Account() { Id = existingAccount.Id }; accountToUpdate.Name = "Super Great Customer Name Updated!"; //Update the entity in the context service.Update(accountToUpdate); //Make other account wasn't updated var account = context.CreateQuery<Account>().Where(e => e.Id == otherExistingAccount.Id).FirstOrDefault(); Assert.Equal(account.Name, "Devil Customer"); }
public void Querying_a_dynamic_using_type_should_use_the_entity_entity_logical_name_attribute() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); //Find the contact var contact = (from c in context.CreateQuery("contact") select c).ToList(); Assert.Equal(contact.Count, 0); }
public void Querying_a_dynamic_entity_not_present_in_the_context_should_return_no_records() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); //Find the contact var contact = (from c in context.CreateQuery("contact") select c).ToList(); Assert.Equal(contact.Count, 0); }
public void When_updating_an_entity_using_organization_context_changes_should_be_saved() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account)); var existingAccount = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" }; context.Initialize(new List<Entity>() { existingAccount }); var service = context.GetFakedOrganizationService(); using (var ctx = new OrganizationServiceContext(service)) { existingAccount.Name = "Super Great Customer Name Updated!"; ctx.Attach(existingAccount); ctx.UpdateObject(existingAccount); ctx.SaveChanges(); } //Make other account wasn't updated var account = context.CreateQuery<Account>().Where(e => e.Id == existingAccount.Id).FirstOrDefault(); Assert.Equal(account.Name, "Super Great Customer Name Updated!"); }
public void When_the_followup_plugin_is_executed_for_an_account_after_create_it_should_create_a_new_task_with_a_regardingid() { var fakedContext = new XrmFakedContext(); fakedContext.ProxyTypesAssembly = Assembly.GetExecutingAssembly(); //Needed to be able to return early bound entities var guid1 = Guid.NewGuid(); var target = new Entity("account") { Id = guid1 }; ParameterCollection inputParameters = new ParameterCollection(); inputParameters.Add("Target", target); ParameterCollection outputParameters = new ParameterCollection(); outputParameters.Add("id", guid1); fakedContext.ExecutePluginWith<FollowupPlugin>(inputParameters, outputParameters, null, null); //The plugin creates a followup activity, check that that one exists var tasks = (from t in fakedContext.CreateQuery<Task>() select t).ToList(); Assert.True(tasks.Count == 1); Assert.True(tasks[0].Subject.Equals("Send e-mail to the new customer.")); Assert.True(tasks[0].RegardingObjectId != null && tasks[0].RegardingObjectId.Id.Equals(guid1)); }