public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var assignRequest = (AssignRequest)request; var target = assignRequest.Target; var assignee = assignRequest.Assignee; if (target == null) { throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), "Can not assign without target"); } if (assignee == null) { throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), "Can not assign without assignee"); } var service = ctx.GetFakedOrganizationService(); var assignment = new Entity { LogicalName = target.LogicalName, Id = target.Id, Attributes = new AttributeCollection { { "ownerid", assignee } } }; service.Update(assignment); return new AssignResponse(); }
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); }
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_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); }
public void When_execute_is_called_with_a_null_request_exception_is_thrown() { var context = new XrmFakedContext(); var executor = new AssociateRequestExecutor(); AssociateRequest req = null; Assert.Throws<Exception>(() => executor.Execute(req, context)); }
public static void ProjectAttributes(Entity e, Entity projected, LinkEntity le, XrmFakedContext context) { var sAlias = string.IsNullOrWhiteSpace(le.EntityAlias) ? le.LinkToEntityName : le.EntityAlias; if (le.Columns.AllColumns && le.Columns.Columns.Count == 0) { foreach (var attKey in e.Attributes.Keys) { if(attKey.StartsWith(sAlias + ".")) { projected[attKey] = e[attKey]; } } } else { foreach (var attKey in le.Columns.Columns) { var linkedAttKey = sAlias + "." + attKey; if (e.Attributes.ContainsKey(linkedAttKey)) projected[linkedAttKey] = e[linkedAttKey]; } } foreach (var nestedLinkedEntity in le.LinkEntities) { ProjectAttributes(e, projected, nestedLinkedEntity, context); } }
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); }
public void When_translating_a_fetch_xml_attribute_node_must_have_a_name_attribute() { var ctx = new XrmFakedContext(); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><attribute></attribute></entity></fetch>")); Assert.DoesNotThrow(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><attribute name='firstname'></attribute></entity></fetch>")); }
public void When_execute_is_called_with_a_null_target_exception_is_thrown() { var context = new XrmFakedContext(); var executor = new AssignRequestExecutor(); AssignRequest req = new AssignRequest() { Target = null }; Assert.Throws<FaultException<OrganizationServiceFault>>(() => executor.Execute(req, context)); }
public void When_execute_is_called_with_a_null_target_exception_is_thrown() { var context = new XrmFakedContext(); var executor = new AssociateRequestExecutor(); var req = new AssociateRequest() { Target = null, Relationship = new Relationship("fakeRelationship") }; context.AddRelationship("fakeRelationship", new XrmFakedRelationship()); Assert.Throws<Exception>(() => executor.Execute(req, context)); }
public void When_translating_a_fetch_xml_expression_first_node_must_be_a_fetch_element_otherwise_exception_is_thrown() { var ctx = new XrmFakedContext(); Assert.DoesNotThrow(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'></entity></fetch>")); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<attribute></attribute>")); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<entity></entity>")); }
public static Entity ProjectAttributes(this Entity e, QueryExpression qe, XrmFakedContext context) { if (qe.ColumnSet == null) return e; if (qe.ColumnSet.AllColumns) { return e; //return all the original attributes } else { //Return selected list of attributes in a projected entity Entity projected = null; //However, if we are using proxy types, we must create a instance of the appropiate class if (context.ProxyTypesAssembly != null) { var subClassType = context.FindReflectedType(e.LogicalName); if (subClassType != null) { var instance = Activator.CreateInstance(subClassType); projected = (Entity)instance; projected.Id = e.Id; } else projected = new Entity(e.LogicalName) { Id = e.Id }; //fallback to generic type if type not found } else projected = new Entity(e.LogicalName) { Id = e.Id }; foreach (var attKey in qe.ColumnSet.Columns) { //Check if attribute really exists in metadata if (!context.AttributeExistsInMetadata(e.LogicalName, attKey)) { OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(attKey); } if (e.Attributes.ContainsKey(attKey)) projected[attKey] = e[attKey]; else { projected[attKey] = null; } } //Plus attributes from joins foreach(var le in qe.LinkEntities) { ProjectAttributes(e, projected, le, context); } //foreach (var attKey in e.Attributes.Keys) //{ // if(e[attKey] is AliasedValue && !projected.Attributes.ContainsKey(attKey)) // projected[attKey] = e[attKey]; //} return projected; } }
public void When_translating_a_fetch_xml_order_node_must_have_2_attributes() { var ctx = new XrmFakedContext(); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><order></order></entity></fetch>")); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><order attribute=''></order></entity></fetch>")); Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><order descending=''></order></entity></fetch>")); Assert.DoesNotThrow(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<fetch><entity name='contact'><order attribute='firstname' descending='true'></order></entity></fetch>")); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var associateRequest = request as AssociateRequest; var service = ctx.GetFakedOrganizationService(); if (associateRequest == null) { throw new Exception("Only associate request can be processed!"); } var associateRelationship = associateRequest.Relationship; var relationShipName = associateRelationship.SchemaName; var fakeRelationShip = ctx.GetRelationship(relationShipName); if (fakeRelationShip == null) { throw new Exception(string.Format("Relationship {0} does not exist in the metadata cache", relationShipName)); } if (associateRequest.Target == null) { throw new Exception("Association without target is invalid!"); } foreach (var relatedEntityReference in associateRequest.RelatedEntities) { if (fakeRelationShip.RelationshipType == XrmFakedRelationship.enmFakeRelationshipType.ManyToMany) { var association = new Entity(fakeRelationShip.IntersectEntity) { Attributes = new AttributeCollection { { fakeRelationShip.Entity1Attribute, associateRequest.Target.Id }, { fakeRelationShip.Entity2Attribute, relatedEntityReference.Id } } }; service.Create(association); } else { //One to many //Get entity to update var entityToUpdate = new Entity(relatedEntityReference.LogicalName) { Id = relatedEntityReference.Id }; entityToUpdate[fakeRelationShip.Entity2Attribute] = associateRequest.Target; service.Update(entityToUpdate); } } return new AssociateResponse (); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var createRequest = (CreateRequest)request; var service = ctx.GetFakedOrganizationService(); service.Create(createRequest.Target); return new CreateResponse(); }
public void When_calling_insert_option_set_value_without_optionsetname_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new InsertOptionValueRequest() { Label = new Label("Yeah! This is a fake label!", 0) }; Assert.Throws<Exception>(() => service.Execute(req)); }
public void When_calling_publish_xml_exception_is_raised_if_parameter_xml_is_blank() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new PublishXmlRequest() { ParameterXml = "" }; Assert.Throws<Exception>(() => service.Execute(req)); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var req = request as WhoAmIRequest; var response = new WhoAmIResponse { Results = new ParameterCollection { { "UserId", ctx.CallerId.Id } } }; return response; }
public void When_calling_publish_xml_no_exception_is_raised() { var ctx = new XrmFakedContext(); var service = ctx.GetFakedOrganizationService(); var req = new PublishXmlRequest() { ParameterXml = "<somexml></somexml>" }; Assert.DoesNotThrow(() => service.Execute(req)); }
public void When_translating_a_fetch_xml_expression_queryexpression_name_matches_entity_node() { var ctx = new XrmFakedContext(); var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='contact'> </entity> </fetch>"; var query = XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, fetchXml); Assert.True(query.EntityName.Equals("contact")); }
public static void When_retrieve_attribute_request_is_called_an_exception_is_not_thrown() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); RetrieveAttributeRequest req = new RetrieveAttributeRequest() { EntityLogicalName = "account", LogicalName = "name" }; Assert.Throws<PullRequestException>(() => service.Execute(req)); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var req = request as PublishXmlRequest; if(string.IsNullOrWhiteSpace(req.ParameterXml)) { throw new Exception(string.Format("ParameterXml property must not be blank.")); } return new PublishXmlResponse() { }; }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var createRequest = (CreateRequest)request; var service = ctx.GetFakedOrganizationService(); var guid = service.Create(createRequest.Target); return new CreateResponse() { ResponseName = "Create", Results = new ParameterCollection { { "id", guid } } }; }
public void When_arithmetic_values_are_used_proxy_types_assembly_is_required() { var ctx = new XrmFakedContext(); var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='contact'> <attribute name='fullname' /> <filter type='and'> <condition attribute='address1_longitude' operator='gt' value='1.2345' /> </filter> </entity> </fetch>"; Assert.Throws<Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, fetchXml)); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var deleteRequest = (DeleteRequest)request; var target = deleteRequest.Target; if (target == null) { throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), "Can not delete without target"); } var service = ctx.GetFakedOrganizationService(); service.Delete(target.LogicalName, target.Id); return new DeleteResponse(); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var disassociateRequest = request as DisassociateRequest; var service = ctx.GetFakedOrganizationService(); if (disassociateRequest == null) { throw new Exception("Only disassociate request can be processed!"); } var relationShipName = disassociateRequest.Relationship.SchemaName; var relationShip = ctx.GetRelationship(relationShipName); if (relationShip == null) { throw new Exception(string.Format("Relationship {0} does not exist in the metadata cache", relationShipName)); } if (disassociateRequest.Target == null) { throw new Exception("Disassociation without target is invalid!"); } foreach (var relatedEntity in disassociateRequest.RelatedEntities) { var query = new QueryExpression(relationShip.IntersectEntity) { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression(LogicalOperator.And) }; query.Criteria.AddCondition(new ConditionExpression(relationShip.Entity1Attribute, ConditionOperator.Equal, disassociateRequest.Target.Id)); query.Criteria.AddCondition(new ConditionExpression(relationShip.Entity2Attribute, ConditionOperator.Equal, relatedEntity.Id)); var results = service.RetrieveMultiple(query); if (results.Entities.Count == 1) { service.Delete(relationShip.IntersectEntity, results.Entities.First().Id); } } return new DisassociateResponse(); }
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 Should_Execute_Subsequent_Requests() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var account1 = new Account { Id = Guid.NewGuid(), Name = "Acc1" }; var account2 = new Account { Id = Guid.NewGuid(), Name = "Acc2" }; var executeMultipleRequest = new ExecuteMultipleRequest { Settings = new ExecuteMultipleSettings { ReturnResponses = true }, Requests = new OrganizationRequestCollection { new CreateRequest { Target = account1 }, new CreateRequest { Target = account2 } } }; var response = service.Execute(executeMultipleRequest) as ExecuteMultipleResponse; Assert.False(response.IsFaulted); Assert.NotEmpty(response.Responses); Assert.NotNull(service.Retrieve(Account.EntityLogicalName, account1.Id, new ColumnSet(true))); Assert.NotNull(service.Retrieve(Account.EntityLogicalName, account2.Id, new ColumnSet(true))); }
public void Conversion_to_entityreference_is_correct() { var ctx = new XrmFakedContext(); ctx.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Contact)); var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='contact'> <attribute name='fullname' /> <filter type='and'> <condition attribute='accountid' operator='eq' value='71831D66-8820-446A-BCEB-BCE14D12B216' /> </filter> </entity> </fetch>"; var query = XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, fetchXml); Assert.IsType<EntityReference>(query.Criteria.Conditions[0].Values[0]); }
public void When_translating_a_fetch_xml_unknown_elements_throw_an_exception() { var ctx = new XrmFakedContext(); Assert.Throws <Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "<thisdoesntexist></thisdoesntexist>")); }
public void SetUp() { this.context = new XrmFakedContext(); this.service = this.context.GetOrganizationService(); }
/// <summary> /// Default constructor. /// </summary> public OrganizationServiceHelperFixture() { Context = new XrmFakedContext(); Service = Context.GetFakedOrganizationService(); Helper = new OrgServiceHelper(Service, (string s) => { }, true); }
public void m2mRelationshipType() { var fakedContext = new XrmFakedContext(); fakedContext.InitializeMetadata(typeof(CrmEarlyBound.CrmServiceContext).Assembly); fakedContext.Initialize(SupportMethods.Getm2mRelationshipTypeEntities()); fakedContext.AddRelationship("systemuserroles_association", new XrmFakedRelationship { IntersectEntity = "systemuserroles", Entity1LogicalName = "systemuser", Entity1Attribute = "systemuserid", Entity2LogicalName = "role", Entity2Attribute = "roleid" }); var AssociateRequest = SupportMethods.Getm2mRelationshipTypeAssociateRequest(); IOrganizationService fakedService = fakedContext.GetOrganizationService(); fakedService.Execute(AssociateRequest); fakedContext.AddExecutionMock <RetrieveEntityRequest>(req => { var logicalName = ((RetrieveEntityRequest)req).LogicalName; var entityMetadata = fakedContext.GetEntityMetadataByName(logicalName); switch (entityMetadata.LogicalName) { case SupportMethods.UserLogicalName: entityMetadata.DisplayName = new Label(SupportMethods.UserDisplayName, 1033); entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "fullname"); entityMetadata.Attributes.First(a => a.LogicalName == "systemuserid").SetSealedPropertyValue("DisplayName", new Label("User", 1033)); entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("IntersectEntityName", "systemuserroles"); entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("Entity2LogicalName", "role"); entityMetadata.ManyToManyRelationships.First(m => m.SchemaName == "systemuserroles_association").SetSealedPropertyValue("Entity2IntersectAttribute", "roleid"); break; case SupportMethods.SecurityRoleLogicalName: entityMetadata.DisplayName = new Label(SupportMethods.SecurityRoleDisplayName, 1033); entityMetadata.SetSealedPropertyValue("PrimaryNameAttribute", "name"); entityMetadata.Attributes.First(a => a.LogicalName == "roleid").SetSealedPropertyValue("DisplayName", new Label("Role", 1033)); break; default: break; } var response = new RetrieveEntityResponse() { Results = new ParameterCollection { { "EntityMetadata", entityMetadata } } }; return(response); }); DataBuilder DataBuilder = new DataBuilder(fakedService); DataBuilder.AppendData("<fetch><entity name='systemuser'><attribute name='systemuserid'/><link-entity name='systemuserroles' from='systemuserid' to='systemuserid' intersect='true'><link-entity name='role' from='roleid' to='roleid'/><attribute name='roleid'/></link-entity><filter><condition attribute='systemuserid' operator='eq' value='00e7b0b9-1ace-e711-a970-000d3a192311'/></filter></entity></fetch>"); var schemaXml = DataBuilder.BuildSchemaXML(); Assert.AreEqual( schemaXml.InnerXml, SupportMethods.Getm2mRelationshipTypeExpectedSchema()); }
public void Invoice_Product_Pricelist_UoM_And_Price_Overriden_Is_False_Price_Is_In_ProductPriceLevel_Quantity_3_AddsAmountToInvoice() { XrmFakedContext context = new XrmFakedContext(); IOrganizationService service = context.GetOrganizationService(); List <Entity> initialEntities = new List <Entity>(); Entity uom = new Entity("unitofmeasure"); uom.Id = Guid.NewGuid(); initialEntities.Add(uom); Entity priceLevel = new Entity("pricelevel"); priceLevel.Id = Guid.NewGuid(); priceLevel["amount"] = new Money(10m); initialEntities.Add(priceLevel); Entity invoice = new Entity("invoice"); invoice.Id = Guid.NewGuid(); invoice["pricelevelid"] = priceLevel.ToEntityReference(); invoice["totalamount"] = new Money(40m); initialEntities.Add(invoice); Entity product = new Entity("product"); product.Id = Guid.NewGuid(); initialEntities.Add(product); Entity productPriceLevel = new Entity("productpricelevel"); productPriceLevel.Id = Guid.NewGuid(); productPriceLevel["amount"] = new Money(10m); productPriceLevel["pricelevelid"] = priceLevel.ToEntityReference(); productPriceLevel["productid"] = product.ToEntityReference(); productPriceLevel["uomid"] = uom.ToEntityReference(); initialEntities.Add(productPriceLevel); //another productpricelevel to ensure that the request takes the correct one Entity productPriceLevel2 = new Entity("productpricelevel"); productPriceLevel2.Id = Guid.NewGuid(); productPriceLevel2["amount"] = new Money(15m); productPriceLevel2["pricelevelid"] = new EntityReference("pricelevel", Guid.NewGuid()); productPriceLevel2["productid"] = product.ToEntityReference(); productPriceLevel2["uomid"] = uom.ToEntityReference(); initialEntities.Add(productPriceLevel2); Entity invoiceDetail = new Entity("invoicedetail"); invoiceDetail.Id = Guid.NewGuid(); invoiceDetail["ispriceoverridden"] = false; invoiceDetail["invoiceid"] = invoice.ToEntityReference(); invoiceDetail["productid"] = product.ToEntityReference(); invoiceDetail["uomid"] = uom.ToEntityReference(); invoiceDetail["quantity"] = 3m; initialEntities.Add(invoiceDetail); context.Initialize(initialEntities); Entity testPostCreate = service.Retrieve(invoiceDetail.LogicalName, invoiceDetail.Id, new ColumnSet(true)); Assert.Equal(new Money(10m), testPostCreate["priceperunit"]); Assert.Equal(3m, testPostCreate["quantity"]); Assert.Equal(new Money(3m * 10m), testPostCreate["amount"]); Assert.Equal(new Money(3m * 10m), testPostCreate["extendedamount"]); Entity testPostInvoiceCreate = service.Retrieve(invoice.LogicalName, invoice.Id, new ColumnSet(true)); Assert.Equal(new Money(40m + 3m * 10m), testPostInvoiceCreate["totalamount"]); }
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 OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var req = (AddListMembersListRequest)request; if (req.MemberIds == null) { FakeOrganizationServiceFault.Throw(ErrorCodes.InvalidArgument, "Required field 'MemberIds' is missing"); } if (req.ListId == Guid.Empty) { FakeOrganizationServiceFault.Throw(ErrorCodes.InvalidArgument, "Expected non-empty Guid."); } var service = ctx.GetOrganizationService(); //Find the list var list = ctx.CreateQuery("list") .Where(e => e.Id == req.ListId) .FirstOrDefault(); if (list == null) { FakeOrganizationServiceFault.Throw(ErrorCodes.IsvAborted, string.Format("List with Id {0} wasn't found", req.ListId.ToString())); } //Find the member if (!list.Attributes.ContainsKey("createdfromcode")) { FakeOrganizationServiceFault.Throw(ErrorCodes.IsvUnExpected, string.Format("List with Id {0} must have a CreatedFromCode attribute defined and it has to be an option set value.", req.ListId.ToString())); } if (list["createdfromcode"] != null && !(list["createdfromcode"] is OptionSetValue)) { FakeOrganizationServiceFault.Throw(ErrorCodes.IsvUnExpected, string.Format("List with Id {0} must have a CreatedFromCode attribute defined and it has to be an option set value.", req.ListId.ToString())); } var createdFromCodeValue = (list["createdfromcode"] as OptionSetValue).Value; string memberEntityName = ""; switch (createdFromCodeValue) { case (int)ListCreatedFromCode.Account: memberEntityName = "account"; break; case (int)ListCreatedFromCode.Contact: memberEntityName = "contact"; break; case (int)ListCreatedFromCode.Lead: memberEntityName = "lead"; break; default: FakeOrganizationServiceFault.Throw(ErrorCodes.IsvUnExpected, string.Format("List with Id {0} must have a supported CreatedFromCode value (Account, Contact or Lead).", req.ListId.ToString())); break; } foreach (var memberId in req.MemberIds) { var member = ctx.CreateQuery(memberEntityName) .Where(e => e.Id == memberId) .FirstOrDefault(); if (member == null) { FakeOrganizationServiceFault.Throw(ErrorCodes.IsvAborted, string.Format("Member of type {0} with Id {1} wasn't found", memberEntityName, memberId.ToString())); } //create member list var listmember = new Entity("listmember"); listmember["listid"] = new EntityReference("list", req.ListId); listmember["entityid"] = new EntityReference(memberEntityName, memberId); service.Create(listmember); } return(new AddListMembersListResponse()); }
public void It_Should_Create_Sub_Record_Table_With_Url_And_Custom_Link_Text() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var tracing = context.GetFakeTracingService(); var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), Attributes = { { "firstname", "Frodo" } } }; var task = new Entity { LogicalName = "task", Id = new Guid("76f167d6-35b3-44ae-b2a0-9373dee13e82"), Attributes = { { "subject", "Task 1" }, { "description", "Description 1" }, { "regardingobjectid", contact.ToEntityReference() } } }; var task2 = new Entity { LogicalName = "task", Id = new Guid("5c0370f2-9b79-4abc-86d6-09260d5bbfed"), Attributes = { { "subject", "Task 2" }, { "description", "Description 2" }, { "regardingobjectid", contact.ToEntityReference() } } }; SetupContext(context); context.Initialize(new Entity[] { contact, task, task2 }); var formula = "RecordTable(Fetch(\"<fetch no-lock='true'><entity name='task'><attribute name='description' /><attribute name='subject' /><filter><condition attribute='regardingobjectid' operator='eq' value='{0}' /></filter></entity></fetch>\"), \"task\", Array(\"subject\", \"description\"), { addRecordUrl: true, linkText: \"Link\" })"; var expected = @"<table> <tr><th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">Subject Label</th> <th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">Description Label</th> <th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">URL</th> </tr> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Task 1</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Description 1</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;""><a href=""https://test.local/main.aspx?etn=task&id=76f167d6-35b3-44ae-b2a0-9373dee13e82&newWindow=true&pagetype=entityrecord"">Link</a></td> </tr> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Task 2</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Description 2</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;""><a href=""https://test.local/main.aspx?etn=task&id=5c0370f2-9b79-4abc-86d6-09260d5bbfed&newWindow=true&pagetype=entityrecord"">Link</a></td> </tr> </table>".Replace("\r", "").Replace("\n", ""); var result = new XTLInterpreter(formula, contact, new OrganizationConfig { OrganizationUrl = "https://test.local" }, service, tracing).Produce(); Assert.That(result.Replace("\r", "").Replace("\n", ""), Is.EqualTo(expected)); }
public static object GetConditionExpressionValueCast(string value, XrmFakedContext ctx, string sEntityName, string sAttributeName) { if (ctx.ProxyTypesAssembly != null) { //We have proxy types so get appropiate type value based on entity name and attribute type var reflectedType = ctx.FindReflectedType(sEntityName); if (reflectedType != null) { var attributeType = ctx.FindReflectedAttributeType(reflectedType, sAttributeName); if (attributeType != null) { try { return(GetValueBasedOnType(attributeType, value)); } catch (Exception e) { throw new Exception(string.Format("When trying to parse value for entity {0} and attribute {1}: {2}", sEntityName, sAttributeName, e.Message)); } } } } //Try parsing a guid Guid gOut = Guid.Empty; if (Guid.TryParse(value, out gOut)) { return(gOut); } //Try checking if it is a numeric value, cause, from the fetchxml it //would be impossible to know the real typed based on the string value only // ex: "123" might compared as a string, or, as an int, it will depend on the attribute // data type, therefore, in this case we do need to use proxy types bool bIsNumeric = false; bool bIsDateTime = false; double dblValue = 0.0; decimal decValue = 0.0m; int intValue = 0; if (double.TryParse(value, out dblValue)) { bIsNumeric = true; } if (decimal.TryParse(value, out decValue)) { bIsNumeric = true; } if (int.TryParse(value, out intValue)) { bIsNumeric = true; } DateTime dtValue = DateTime.MinValue; if (DateTime.TryParse(value, out dtValue)) { bIsDateTime = true; } if (bIsNumeric || bIsDateTime) { throw new Exception("When using arithmetic values in Fetch a ProxyTypesAssembly must be used in order to know which types to cast values to."); } //Default value return(value); }
public void Testing_191() { // create a contact var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), }; // link a child to the contact var child = new Entity { LogicalName = "child", Id = Guid.NewGuid(), Attributes = new AttributeCollection { { "contactid", new EntityReference("contact", contact.Id) } } }; // link a pet to the child var pet = new Entity { LogicalName = "pet", Id = Guid.NewGuid(), Attributes = new AttributeCollection { { "childid", new EntityReference("child", child.Id) } } }; // initialise var context = new XrmFakedContext(); context.Initialize(new[] { contact, child, pet }); var service = context.GetFakedOrganizationService(); // join contact and child and pet var query2 = new QueryExpression("contact"); LinkEntity link2 = new LinkEntity() { LinkFromEntityName = "contact", LinkFromAttributeName = "contactid", LinkToEntityName = "child", LinkToAttributeName = "contactid", JoinOperator = JoinOperator.LeftOuter, Columns = new ColumnSet("contactid") }; query2.LinkEntities.Add(link2); LinkEntity link22 = new LinkEntity() { LinkFromEntityName = "child", LinkFromAttributeName = "childid", LinkToEntityName = "pet", LinkToAttributeName = "childid", JoinOperator = JoinOperator.LeftOuter, Columns = new ColumnSet("childid") }; link2.LinkEntities.Add(link22); var count2 = service.RetrieveMultiple(query2).Entities.Count; Console.WriteLine(count2); // returns 1 record var results = service.RetrieveMultiple(query2); Assert.Equal(true, results.Entities[0].Attributes.ContainsKey("child.contactid")); Assert.Equal(true, results.Entities[0].Attributes.ContainsKey("pet.childid")); //test fails unless link22 is Inner join }
public Entity Initialize(Entity e, XrmFakedContext ctx, bool isManyToManyRelationshipEntity = false) { return(this.Initialize(e, Guid.NewGuid(), ctx, isManyToManyRelationshipEntity)); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { RetrieveSharedPrincipalsAndAccessRequest req = (RetrieveSharedPrincipalsAndAccessRequest)request; return(ctx.AccessRightsRepository.RetrieveSharedPrincipalsAndAccess(req.Target)); }
public void It_Should_Add_Custom_Column_Labels() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var tracing = context.GetFakeTracingService(); var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), Attributes = { { "firstname", "Frodo" } } }; var task = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 1" }, { "description", "Description 1" }, { "regardingobjectid", contact.ToEntityReference() } } }; var task2 = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 2" }, { "description", "Description 2" }, { "regardingobjectid", contact.ToEntityReference() } } }; SetupContext(context); context.Initialize(new Entity[] { contact, task, task2 }); var formula = "RecordTable(Fetch(\"<fetch no-lock='true'><entity name='task'><attribute name='description' /><attribute name='subject' /><filter><condition attribute='regardingobjectid' operator='eq' value='{0}' /></filter></entity></fetch>\"), \"task\", Array(\"subject:Overridden Subject Label\", \"description\"))"; var expected = @"<table> <tr><th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px"">Overridden Subject Label</th> <th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px"">Description Label</th> <tr /> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px"">Task 1</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px"">Description 1</td> <tr /> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px"">Task 2</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px"">Description 2</td> <tr /> </table>".Replace("\r", "").Replace("\n", ""); var result = new XTLInterpreter(formula, contact, null, service, tracing).Produce(); Assert.That(result.Replace("\r", "").Replace("\n", ""), Is.EqualTo(expected)); }
public void It_Should_Use_Uneven_And_Even_Row_Styles() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var tracing = context.GetFakeTracingService(); var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), Attributes = { { "firstname", "Frodo" } } }; var task = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 1" }, { "description", "Description 1" }, { "regardingobjectid", contact.ToEntityReference() } } }; var task2 = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 2" }, { "description", "Description 2" }, { "regardingobjectid", contact.ToEntityReference() } } }; SetupContext(context); context.Initialize(new Entity[] { contact, task, task2 }); var formula = "RecordTable(Fetch(\"<fetch no-lock='true'><entity name='task'><attribute name='description' /><attribute name='subject' /><filter><condition attribute='regardingobjectid' operator='eq' value='{0}' /></filter></entity></fetch>\"), \"task\", [\"subject\", \"description\"], { tableStyle: \"border:1px solid green;\", headerStyle: \"border:1px solid orange;\", evenDataStyle: \"border:1px solid white;\", unevenDataStyle: \"border:1px solid blue;\"})"; var expected = @"<table style=""border:1px solid green;""> <tr><th style=""border:1px solid orange;"">Subject Label</th> <th style=""border:1px solid orange;"">Description Label</th> </tr> <tr> <td style=""border:1px solid white;"">Task 1</td> <td style=""border:1px solid white;"">Description 1</td> </tr> <tr> <td style=""border:1px solid blue;"">Task 2</td> <td style=""border:1px solid blue;"">Description 2</td> </tr> </table>".Replace("\r", "").Replace("\n", ""); var result = new XTLInterpreter(formula, contact, null, service, tracing).Produce(); Assert.That(result.Replace("\r", "").Replace("\n", ""), Is.EqualTo(expected)); }
public void TrialFakeXrmEasyTest() { //Ok, this is going to be our test method body //But before doing anything... // FakeXrmEasy is based on the state-based testing paradigm, // which is made of, roughly, 3 easy steps: //1) We define the initial state of our test. //2) Then, we execute the piece of logic which we want to test, // which will produce a new state, the final state. //3) Finally, we verify that the final state is the expected state (assertions). //Let's implement those now // 1) Define the initial state // ----------------------------------------------------------------------- // Our initial state is going to be stored in what we call a faked context: var context = new XrmFakedContext(); //You can think of a context like an Organisation database which stores entities In Memory. //We can also use TypedEntities but we need to tell the context where to look for them, //this could be done, easily, like this: context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account)); //We have to define our initial state now, //by calling the Initialize method, which expects a list of entities. var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" }; context.Initialize(new List <Entity>() { account }); //With the above example, we initialized our context with a single account record // 2) Execute our logic // ----------------------------------------------------------------------- // // We need to get a faked organization service first, by calling this method: var service = context.GetOrganizationService(); // That line is the most powerful functionality of FakeXrmEasy // That method has returned a reference to an OrganizationService // which you could pass to your plugins, codeactivities, etc, // and, from now on, every create, update, delete, even queries, etc // will be reflected in our In Memory context // In a nutshell, everything is already mocked for you... cool, isn't it? // Now... // To illustrate this... // Let's say we have a super simple piece of logic which updates an account's name // Let's do it! var accountToUpdate = new Account() { Id = account.Id }; accountToUpdate.Name = "A new faked name!"; service.Update(accountToUpdate); // Done! //We have successfully executed the code we want to test.. // Now... // The final step is... // 3) Verify final state is the expected state // ----------------------------------------------------------------------- // //We are going to use Xunit assertions. var updatedAccountName = context.CreateQuery <Account>() .Where(e => e.Id == account.Id) .Select(a => a.Name) .FirstOrDefault(); //And finally, validate the account has the expected name Assert.AreEqual("A new faked name!", updatedAccountName); }
public void It_Should_Sort_Sub_Record_Table() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var tracing = context.GetFakeTracingService(); var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), Attributes = { { "firstname", "Frodo" } } }; var task = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 1" }, { "description", "Description 1" }, { "regardingobjectid", contact.ToEntityReference() }, { "createdon", DateTime.UtcNow } } }; var task2 = new Entity { LogicalName = "task", Id = Guid.NewGuid(), Attributes = { { "subject", "Task 2" }, { "description", "Description 2" }, { "regardingobjectid", contact.ToEntityReference() }, { "createdon", DateTime.UtcNow.AddDays(-1) } } }; SetupContext(context); context.Initialize(new Entity[] { contact, task, task2 }); var formula = "RecordTable(Sort(Fetch(\"<fetch no-lock='true'><entity name='task'><attribute name='subject' /><attribute name='description' /><attribute name='createdon' /></entity></fetch>\"), { property: \"createdon\" }), \"task\", Array(\"subject\", \"description\"))"; var expected = @"<table> <tr><th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">Subject Label</th> <th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">Description Label</th> </tr> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Task 2</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Description 2</td> </tr> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Task 1</td> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">Description 1</td> </tr> </table>".Replace("\r", "").Replace("\n", ""); var result = new XTLInterpreter(formula, contact, null, service, tracing).Produce(); Assert.That(result.Replace("\r", "").Replace("\n", ""), Is.EqualTo(expected)); }
public static void Should_Not_Fail_On_Conditions_In_Link_Entities() { var fakedContext = new XrmFakedContext(); var fakedService = fakedContext.GetFakedOrganizationService(); var testEntity1 = new Entity("entity1") { Attributes = new AttributeCollection { { "entity1attr", "test1" } } }; var testEntity2 = new Entity("entity2") { Attributes = new AttributeCollection { { "entity2attr", "test2" } } }; testEntity1.Id = fakedService.Create(testEntity1); testEntity2.Id = fakedService.Create(testEntity2); var testRelation = new XrmFakedRelationship { IntersectEntity = "TestIntersectEntity", Entity1LogicalName = "entity1", Entity1Attribute = "entity1attr", Entity2LogicalName = "entity2", Entity2Attribute = "entity2attr" }; fakedContext.AddRelationship(testRelation.Entity2LogicalName, testRelation); fakedService.Associate(testEntity1.LogicalName, testEntity1.Id, new Relationship(testRelation.Entity2LogicalName), new EntityReferenceCollection { testEntity2.ToEntityReference() }); var query = new QueryExpression { EntityName = "entity1", Criteria = new FilterExpression { FilterOperator = LogicalOperator.And }, ColumnSet = new ColumnSet(true) }; var link = new LinkEntity { JoinOperator = JoinOperator.Natural, LinkFromEntityName = "entity1", LinkFromAttributeName = "entity1attr", LinkToEntityName = "entity2", LinkToAttributeName = "entity2attr", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "entity2attr", Operator = ConditionOperator.Equal, Values = { "test2" } } } } }; query.LinkEntities.Add(link); var result = fakedService.RetrieveMultiple(query); Assert.NotEmpty(result.Entities); Assert.Equal(1, result.Entities.Count); }
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.GetOrganizationService(); 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 Reproduce_issue_312() { var context = new XrmFakedContext(); var service = context.GetOrganizationService(); var accountId = Guid.NewGuid(); Account account = new Account(); account.Id = accountId; account.Name = "Test Account"; Contact contact = new Contact(); contact.FirstName = "Dave"; contact.LastName = "Contact"; contact.ParentCustomerId = new EntityReference("account", accountId); contact.JobTitle = "Developer"; Contact contact2 = new Contact(); contact2.FirstName = "Simon"; contact2.LastName = "Contact"; contact2.ParentCustomerId = new EntityReference("account", accountId); contact2.JobTitle = "Tester2"; service.Create(account); service.Create(contact); service.Create(contact2); string fetchXml = $@" <fetch distinct='true' no-lock='true' > <entity name='account' > <attribute name='name' /> <filter> <condition attribute='accountid' operator='eq' value='{accountId}' /> </filter> <link-entity name='contact' from='parentcustomerid' to='accountid' alias='dev' > <attribute name='firstname' /> <filter> <condition attribute='jobtitle' operator='eq' value='Developer' /> </filter> </link-entity> <link-entity name='contact' from='parentcustomerid' to='accountid' link-type='outer' alias='tester' > <attribute name='firstname' /> <filter> <condition attribute='jobtitle' operator='eq' value='Tester' /> </filter> </link-entity> </entity> </fetch>"; string fetchXml2 = $@" <fetch distinct='true' no-lock='true' > <entity name='account' > <attribute name='name' /> <filter> <condition attribute='accountid' operator='eq' value='{accountId}' /> </filter> <link-entity name='contact' from='parentcustomerid' to='accountid' link-type='outer' alias='tester' > <attribute name='firstname' /> <filter> <condition attribute='jobtitle' operator='eq' value='Tester' /> </filter> </link-entity> </entity> </fetch>"; EntityCollection result2 = service.RetrieveMultiple(new FetchExpression(fetchXml2)); Assert.Equal(1, result2.Entities.Count); Assert.Equal(2, result2.Entities[0].Attributes.Count); Assert.Equal("Test Account", result2.Entities[0].Attributes["name"].ToString()); EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml)); Assert.Equal(1, result.Entities.Count); Assert.Equal(3, result.Entities[0].Attributes.Count); Assert.Equal("Test Account", result.Entities[0].Attributes["name"].ToString()); Assert.Equal("Dave", ((AliasedValue)result.Entities[0].Attributes["dev.firstname"]).Value); }
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 Should_Apply_Left_Outer_Join_Filters_When_The_Right_hand_side_of_the_expression_was_found() { var context = new XrmFakedContext(); var service = context.GetOrganizationService(); // 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 TestSetup() { context = new XrmFakedContext(); surveyService = new SurveyService(); crmService = new TestCrmService(context); }
public void TestRetriveMultipleWithLinkEntityWithAlternateNullField() { // ARRANGE List <Entity> initialEntities = new List <Entity>(); Entity parentEntity = new Entity("parent"); parentEntity["parentname"] = "parent name"; parentEntity.Id = Guid.NewGuid(); initialEntities.Add(parentEntity); // create the first child which has the "myvalue" field set to "value" Entity childEntity1 = new Entity("child"); childEntity1["parent"] = parentEntity.ToEntityReference(); childEntity1["name"] = "entity1"; childEntity1["myvalue"] = "value"; childEntity1.Id = Guid.NewGuid(); initialEntities.Add(childEntity1); // create the second child which has the "myvalue" field set to null Entity childEntity2 = new Entity("child"); childEntity2["parent"] = parentEntity.ToEntityReference(); childEntity2["name"] = "entity2"; childEntity2["myvalue"] = null; childEntity2.Id = Guid.NewGuid(); initialEntities.Add(childEntity2); XrmFakedContext context = new XrmFakedContext(); IOrganizationService service = context.GetOrganizationService(); context.Initialize(initialEntities); // the query selects the "parent" entity, and joins to the "child" entities QueryExpression query = new QueryExpression("parent"); query.ColumnSet = new ColumnSet("parentname"); LinkEntity link = new LinkEntity("parent", "child", "parentid", "parent", JoinOperator.Inner); link.EntityAlias = "c"; link.Columns = new ColumnSet("name", "myvalue"); query.LinkEntities.Add(link); // ACT DataCollection <Entity> results = service.RetrieveMultiple(query).Entities; // ASSERT // fields for the first entity work as expected... string entity1Name = results[0].GetAttributeValue <AliasedValue>("c.name").Value as string; string entity1Value = results[0].GetAttributeValue <AliasedValue>("c.myvalue").Value as string; Assert.Equal("entity1", entity1Name); Assert.Equal("value", entity1Value); // fields for the second entity do not. // The child "name" field is correct, but the "myvalue" field is returning the value of the previous // entity when it should be returning null string entity2Name = results[1].GetAttributeValue <AliasedValue>("c.name").Value as string; string entity2Value = results[1].GetAttributeValue <AliasedValue>("c.myvalue")?.Value as string; // this works fine: Assert.Equal("entity2", entity2Name); // this fails (entity2Value is "value") Assert.Equal(null, entity2Value); }
public void When_translating_a_fetch_xml_expression_fetchxml_must_be_an_xml() { var ctx = new XrmFakedContext(); Assert.Throws <Exception>(() => XrmFakedContext.TranslateFetchXmlToQueryExpression(ctx, "this is not an xml")); }
public void It_Should_Use_MultiValued_Render_Functions_With_Per_Row_Fields() { var context = new XrmFakedContext(); var service = context.GetFakedOrganizationService(); var tracing = context.GetFakeTracingService(); var userId = Guid.NewGuid(); var userSettings = new Entity { LogicalName = "usersettings", Id = userId, ["timezonecode"] = 1 }; var timeZoneDefinition = new Entity { LogicalName = "timezonedefinition", Id = Guid.NewGuid(), ["standardname"] = "Eastern Standard Time", ["timezonecode"] = 1 }; var contact = new Entity { LogicalName = "contact", Id = Guid.NewGuid(), Attributes = { { "createdon", new DateTime(2020, 02, 27, 8, 0, 0, DateTimeKind.Utc) }, { "ownerid", new EntityReference("systemuser", userId) } } }; var email = new Entity { LogicalName = "email", Id = Guid.NewGuid(), Attributes = { { "regardingobjectid", contact.ToEntityReference() } } }; SetupContext(context); context.Initialize(new Entity[] { contact, email, userSettings, timeZoneDefinition }); var formula = "RecordTable(Fetch(\"<fetch no-lock='true'><entity name='contact'><attribute name='ownerid' /> <attribute name='createdon' /></entity></fetch>\"), \"contact\", [{ name: \"createdon\", label: \"Date\", renderFunction: (record, column) => DateToString(ConvertDateTime(Value(column, { explicitTarget: record }), { userId: Value(\"ownerid\", { explicitTarget: record }) }), { format: \"yyyy-MM-dd hh:mm:ss\" }) }])"; var expected = @"<table> <tr><th style=""border:1px solid black;text-align:left;padding:1px 15px 1px 5px;"">Date</th> </tr> <tr> <td style=""border:1px solid black;padding:1px 15px 1px 5px;"">2020-02-27 03:00:00</td> </tr> </table>".Replace("\r", "").Replace("\n", ""); var result = new XTLInterpreter(formula, email, null, service, tracing).Produce(); Assert.That(result.Replace("\r", "").Replace("\n", ""), Is.EqualTo(expected)); }
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_a_plugin_which_inherits_from_iplugin_it_does_compile() { var fakedContext = new XrmFakedContext(); var fakedPlugin = fakedContext.ExecutePluginWithTarget <MyPlugin>(new Entity()); }
public void Should_also_update_entity_metadata_when_not_using_global_option_set() { var label = "dummy label"; var attributeName = "statuscode"; var ctx = new XrmFakedContext(); XrmFakedContext fakedContext = new XrmFakedContext { ProxyTypesAssembly = (Assembly.GetAssembly(typeof(Contact))) }; var entityMetadata = new EntityMetadata() { LogicalName = "contact" }; StatusAttributeMetadata enumAttribute = new StatusAttributeMetadata() { LogicalName = attributeName }; entityMetadata.SetAttributeCollection(new List <AttributeMetadata>() { enumAttribute }); ctx.InitializeMetadata(entityMetadata); var req = new InsertOptionValueRequest() { EntityLogicalName = Contact.EntityLogicalName, AttributeLogicalName = attributeName, Label = new Label(label, 0) }; var service = ctx.GetOrganizationService(); service.Execute(req); //Check the optionsetmetadata was updated var key = string.Format("{0}#{1}", Contact.EntityLogicalName, attributeName); Assert.True(ctx.OptionSetValuesMetadata.ContainsKey(key)); var option = ctx.OptionSetValuesMetadata[key].Options.FirstOrDefault(); Assert.Equal(label, option.Label.LocalizedLabels[0].Label); // Get a list of Option Set values for the Status Reason fields from its metadata RetrieveAttributeRequest attReq = new RetrieveAttributeRequest(); attReq.EntityLogicalName = "contact"; attReq.LogicalName = "statuscode"; attReq.RetrieveAsIfPublished = true; RetrieveAttributeResponse attResponse = (RetrieveAttributeResponse)service.Execute(attReq); StatusAttributeMetadata statusAttributeMetadata = (StatusAttributeMetadata)attResponse.AttributeMetadata; Assert.NotNull(statusAttributeMetadata.OptionSet); Assert.NotNull(statusAttributeMetadata.OptionSet.Options); Assert.Equal(1, statusAttributeMetadata.OptionSet.Options.Where(o => o.Label.LocalizedLabels[0].Label == label).Count()); }
public static object ToValue(this XElement elem, XrmFakedContext ctx, string sEntityName, string sAttributeName) { return(GetConditionExpressionValueCast(elem.Value, ctx, sEntityName, sAttributeName)); }
public static ConditionExpression ToConditionExpression(this XElement elem, XrmFakedContext ctx) { var conditionExpression = new ConditionExpression(); var attributeName = elem.GetAttribute("attribute").Value; ConditionOperator op = ConditionOperator.Equal; string value = null; if (elem.GetAttribute("value") != null) { value = elem.GetAttribute("value").Value; } switch (elem.GetAttribute("operator").Value) { case "eq": op = ConditionOperator.Equal; break; case "ne": case "neq": op = ConditionOperator.NotEqual; break; case "begins-with": op = ConditionOperator.BeginsWith; break; case "not-begin-with": op = ConditionOperator.DoesNotBeginWith; break; case "ends-with": op = ConditionOperator.EndsWith; break; case "not-end-with": op = ConditionOperator.DoesNotEndWith; break; case "in": op = ConditionOperator.In; break; case "not-in": op = ConditionOperator.NotIn; break; case "null": op = ConditionOperator.Null; break; case "not-null": op = ConditionOperator.NotNull; break; case "like": op = ConditionOperator.Like; if (value != null) { if (value.StartsWith("%") && !value.EndsWith("%")) { op = ConditionOperator.EndsWith; } else if (!value.StartsWith("%") && value.EndsWith("%")) { op = ConditionOperator.BeginsWith; } value = value.Replace("%", ""); } break; case "not-like": op = ConditionOperator.NotLike; if (value != null) { if (value.StartsWith("%") && !value.EndsWith("%")) { op = ConditionOperator.DoesNotEndWith; } else if (!value.StartsWith("%") && value.EndsWith("%")) { op = ConditionOperator.DoesNotBeginWith; } value = value.Replace("%", ""); } break; case "gt": op = ConditionOperator.GreaterThan; break; case "ge": op = ConditionOperator.GreaterEqual; break; case "lt": op = ConditionOperator.LessThan; break; case "le": op = ConditionOperator.LessEqual; break; case "on": op = ConditionOperator.On; break; case "on-or-before": op = ConditionOperator.OnOrBefore; break; case "on-or-after": op = ConditionOperator.OnOrAfter; break; case "today": op = ConditionOperator.Today; break; case "yesterday": op = ConditionOperator.Yesterday; break; case "tomorrow": op = ConditionOperator.Tomorrow; break; case "between": op = ConditionOperator.Between; break; case "not-between": op = ConditionOperator.NotBetween; break; default: throw PullRequestException.FetchXmlOperatorNotImplemented(elem.GetAttribute("operator").Value); } //Process values object[] values = null; var entityName = GetAssociatedEntityNameForConditionExpression(elem); //Find values inside the condition expression, if apply values = elem .Elements() //child nodes of this filter .Where(el => el.Name.LocalName.Equals("value")) .Select(el => el.ToValue(ctx, entityName, attributeName)) .ToArray(); //Otherwise, a single value was used if (value != null) { return(new ConditionExpression(attributeName, op, GetConditionExpressionValueCast(value, ctx, entityName, attributeName))); } return(new ConditionExpression(attributeName, op, values)); }
public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) { var updateRequest = (UpdateRequest) request; var target = (Entity)request.Parameters["Target"]; var service = ctx.GetFakedOrganizationService(); service.Update(target); return new UpdateResponse(); }