protected override bool ICanSlurpRK(IResourceKey key) { // From Catlg_removeRefdCatlgs return((!Enum.IsDefined(typeof(CatalogType), key.ResourceType) || key.Instance == base.originalKey.Instance) && (base.includeDDSes || !ResourceGraph.IsDDS(key.ResourceType))); }
private List <IResourceConnection> CTPT_addPair() { Diagnostics.Log("CTPT_addPair"); byte status = (byte)base.resource["CommonBlock.BuildBuyProductStatusFlags"].Value; Dictionary <ulong, SpecificResource> indexToPair; if ((status & BBProdStatusShowInCatalog) != 0) { indexToPair = CTPTBrushIndexToPair0; } else { indexToPair = CTPTBrushIndexToPair1; } //int brushIndex = ("" + base.Resource["BrushTexture"]).GetHashCode(); ulong brushIndex = (ulong)base.resource["CommonBlock.NameGUID"].Value; if (indexToPair.ContainsKey(brushIndex)) { //Add("ctpt_pair", CTPTBrushIndexToPair[brushIndex].RequestedRK); List <IResourceConnection> results = new List <IResourceConnection>(); results.Add(new CTPTConnection(indexToPair[brushIndex])); return(results); } else { Diagnostics.Show(String.Format("CTPT {0} BrushIndex {1} not found", ResourceGraph.PrintRKTag(base.originalKey, "CatalogTerrainPaintBrush"), brushIndex), "No ctpt_pair item"); return(new List <IResourceConnection>()); } }
public ResponseResourceObjectBuilderTests() { _relationshipsForBuild = ResourceGraph.GetRelationships <OneToManyPrincipal>(relationship => new { relationship.Dependents }).ToList(); }
public void Applies_cascading_settings_for_relationship_links(LinkTypes linksInRelationshipAttribute, LinkTypes linksInResourceContext, LinkTypes linksInOptions, LinkTypes expected) { // Arrange var exampleResourceContext = new ResourceContext { PublicName = nameof(ExampleResource), ResourceType = typeof(ExampleResource), RelationshipLinks = linksInResourceContext }; var options = new JsonApiOptions { RelationshipLinks = linksInOptions }; var request = new JsonApiRequest(); var paginationContext = new PaginationContext(); var resourceGraph = new ResourceGraph(exampleResourceContext.AsArray()); var httpContextAccessor = new FakeHttpContextAccessor(); var linkGenerator = new FakeLinkGenerator(); var controllerResourceMapping = new FakeControllerResourceMapping(); var linkBuilder = new LinkBuilder(options, request, paginationContext, resourceGraph, httpContextAccessor, linkGenerator, controllerResourceMapping); var relationship = new HasOneAttribute { Links = linksInRelationshipAttribute }; // Act RelationshipLinks relationshipLinks = linkBuilder.GetRelationshipLinks(relationship, new ExampleResource()); // Assert if (expected == LinkTypes.None) { relationshipLinks.Should().BeNull(); } else { if (expected.HasFlag(LinkTypes.Self)) { relationshipLinks.Self.Should().NotBeNull(); } else { relationshipLinks.Self.Should().BeNull(); } if (expected.HasFlag(LinkTypes.Related)) { relationshipLinks.Related.Should().NotBeNull(); } else { relationshipLinks.Related.Should().BeNull(); } } }
// Any interdependency between catalog resource is handled like CFIR (for complex ones) or CTPT (for simple ones) private void Catlg_removeRefdCatlgs(List <IResourceConnection> connections) { Diagnostics.Log("Catlg_removeRefdCatlgs"); IList <TGIBlock> ltgi = (IList <TGIBlock>)base.Resource["TGIBlocks"].Value; AResourceKey rk; int i, j, index, count = ltgi.Count; for (i = 0; i < count; i++) { rk = ltgi[i]; if (Enum.IsDefined(typeof(CatalogType), rk.ResourceType) && rk.Instance != base.originalKey.Instance) { index = -1; for (j = 0; j < connections.Count && index < 0; j++) { if (connections[j].OriginalChildKey.Equals(rk)) { index = j; } } if (index >= 0) { string key = ResourceGraph.PrintRKRef(connections[index].OriginalChildKey, connections[index].AbsolutePath); Diagnostics.Log("Catlg_removeRefdCatlgs: Removed " + key); connections.RemoveAt(index); } } } }
public void SerializeSingle_NoIdWithTargetedSetAttributes_CanBuild() { // Arrange var resourceNoId = new TestResource { Id = 0, StringField = "value", NullableIntField = 123 }; _serializer.AttributesToSerialize = ResourceGraph.GetAttributes <TestResource>(tr => tr.StringField); // Act string serialized = _serializer.Serialize(resourceNoId); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""testResource"", ""attributes"":{ ""stringField"":""value"" } } }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
public void SerializeSingle_ResourceWithoutTargetedAttributes_CanBuild() { // Arrange var resource = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; _serializer.AttributesToSerialize = ResourceGraph.GetAttributes <TestResource>(_ => new { }); // Act string serialized = _serializer.Serialize(resource); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""testResource"", ""id"":""1"" } }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
public void ResourceWithRelationshipsToResourceObject_WithIncludedRelationshipsAttributes_CanBuild() { // Arrange var resource = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, PopulatedToManies = new HashSet <OneToManyDependent> { new OneToManyDependent { Id = 20 } } }; var relationships = ResourceGraph.GetRelationships <MultipleRelationshipsPrincipalPart>(tr => new { tr.PopulatedToManies, tr.PopulatedToOne, tr.EmptyToOne, tr.EmptyToManies }); // Act var resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Equal(4, resourceObject.Relationships.Count); Assert.Null(resourceObject.Relationships["emptyToOne"].Data); Assert.Empty((IList)resourceObject.Relationships["emptyToManies"].Data); var populatedToOneData = (ResourceIdentifierObject)resourceObject.Relationships["populatedToOne"].Data; Assert.NotNull(populatedToOneData); Assert.Equal("10", populatedToOneData.Id); Assert.Equal("oneToOneDependents", populatedToOneData.Type); var populatedToManiesData = (List <ResourceIdentifierObject>)resourceObject.Relationships["populatedToManies"].Data; Assert.Single(populatedToManiesData); Assert.Equal("20", populatedToManiesData.First().Id); Assert.Equal("oneToManyDependents", populatedToManiesData.First().Type); }
public void BeforeUpdate_Deleting_Relationship() { // Arrange var todoDiscovery = SetDiscoverableHooks <TodoItem>(_targetHooks, EnableDbValues); var personDiscovery = SetDiscoverableHooks <Person>(_targetHooks, EnableDbValues); var(_, ufMock, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, repoDbContextOptions: _options); ufMock.Setup(c => c.Relationships).Returns(ResourceGraph.GetRelationships((TodoItem t) => t.OneToOnePerson).ToHashSet); // Act var todoList = new List <TodoItem> { new TodoItem { Id = _todoList[0].Id } }; hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); // Assert todoResourceMock.Verify(rd => rd.BeforeUpdate(It.Is <IDiffableResourceHashSet <TodoItem> >(diff => TodoCheckDiff(diff, Description)), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify(rd => rd.BeforeImplicitUpdateRelationship( It.Is <IRelationshipsDictionary <Person> >(rh => PersonCheck(LastName + LastName, rh)), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); }
/// <inheritdoc /> public IResourceGraph Build() { _resources.ForEach(SetResourceLinksOptions); var resourceGraph = new ResourceGraph(_resources, _validationResults); return(resourceGraph); }
public void BeforeUpdate_Deleting_Relationship() { // Arrange IHooksDiscovery <TodoItem> todoDiscovery = SetDiscoverableHooks <TodoItem>(_targetHooks, EnableDbValues); IHooksDiscovery <Person> personDiscovery = SetDiscoverableHooks <Person>(_targetHooks, EnableDbValues); (_, Mock <ITargetedFields> ufMock, IResourceHookExecutor hookExecutor, Mock <IResourceHookContainer <TodoItem> > todoResourceMock, Mock <IResourceHookContainer <Person> > ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, _options); ufMock.Setup(targetedFields => targetedFields.Relationships) .Returns(ResourceGraph.GetRelationships((TodoItem todoItem) => todoItem.OneToOnePerson).ToHashSet); // Act var todoList = new List <TodoItem> { new TodoItem { Id = _todoList[0].Id } }; hookExecutor.BeforeUpdate(todoList, ResourcePipeline.Patch); // Assert todoResourceMock.Verify( rd => rd.BeforeUpdate(It.Is <IDiffableResourceHashSet <TodoItem> >(diff => TodoCheckDiff(diff, Description)), ResourcePipeline.Patch), Times.Once()); ownerResourceMock.Verify( rd => rd.BeforeImplicitUpdateRelationship(It.Is <IRelationshipsDictionary <Person> >(rh => PersonCheck(Name + Name, rh)), ResourcePipeline.Patch), Times.Once()); VerifyNoOtherCalls(todoResourceMock, ownerResourceMock); }
public void DeserializeAttributes_VariousDataTypes_CanDeserialize(string member, object value, bool expectError = false) { // Arrange var content = new Document { Data = new ResourceObject { Type = "testResource", Id = "1", Attributes = new Dictionary <string, object> { [member] = value } } }; string body = JsonConvert.SerializeObject(content); // Act Func <TestResource> action = () => (TestResource)_deserializer.Deserialize(body); // Assert if (expectError) { Assert.ThrowsAny <FormatException>(action); } else { TestResource resource = action(); PropertyInfo pi = ResourceGraph.GetResourceContext("testResource").Attributes.Single(attr => attr.PublicName == member).Property; object deserializedValue = pi.GetValue(resource); if (member == "intField") { Assert.Equal(1, deserializedValue); } else if (member == "nullableIntField" && value == null) { Assert.Null(deserializedValue); } else if (member == "nullableIntField" && (string)value == "1") { Assert.Equal(1, deserializedValue); } else if (member == "guidField") { Assert.Equal(deserializedValue, Guid.Parse("1a68be43-cc84-4924-a421-7f4d614b7781")); } else if (member == "dateTimeField") { Assert.Equal(deserializedValue, DateTime.Parse("9/11/2019 11:41:40 AM")); } else { Assert.Equal(value, deserializedValue); } } }
protected IFieldsToSerialize GetSerializableFields() { var mock = new Mock <IFieldsToSerialize>(); mock.Setup(m => m.GetAttributes(It.IsAny <Type>())).Returns <Type>(t => ResourceGraph.GetResourceContext(t).Attributes); mock.Setup(m => m.GetRelationships(It.IsAny <Type>())).Returns <Type>(t => ResourceGraph.GetResourceContext(t).Relationships); return(mock.Object); }
/// <inheritdoc /> public IResourceGraph Build() { // this must be done at build so that call order doesn't matter _entities.ForEach(e => e.Links = GetLinkFlags(e.EntityType)); var graph = new ResourceGraph(_entities, _usesDbContext, _validationResults); return(graph); }
public LegacyFilterParseTests() { Options.EnableLegacyFilterNotation = true; CurrentRequest.PrimaryResource = ResourceGraph.GetResourceContext <Article>(); var resourceFactory = new ResourceFactory(new ServiceContainer()); _reader = new FilterQueryStringParameterReader(CurrentRequest, ResourceGraph, resourceFactory, Options); }
public void SerializeSingle_ResourceWithTargetedRelationships_CanBuild() { // Arrange var resourceWithRelationships = new MultipleRelationshipsPrincipalPart { PopulatedToOne = new OneToOneDependent { Id = 10 }, PopulatedToManies = new HashSet <OneToManyDependent> { new OneToManyDependent { Id = 20 } } }; _serializer.RelationshipsToSerialize = ResourceGraph.GetRelationships <MultipleRelationshipsPrincipalPart>(tr => new { tr.EmptyToOne, tr.EmptyToManies, tr.PopulatedToOne, tr.PopulatedToManies }); // Act string serialized = _serializer.Serialize(resourceWithRelationships); // Assert const string expectedFormatted = @"{ ""data"":{ ""type"":""multiPrincipals"", ""attributes"":{ ""attributeMember"":null }, ""relationships"":{ ""emptyToOne"":{ ""data"":null }, ""emptyToManies"":{ ""data"":[ ] }, ""populatedToOne"":{ ""data"":{ ""type"":""oneToOneDependents"", ""id"":""10"" } }, ""populatedToManies"":{ ""data"":[ { ""type"":""oneToManyDependents"", ""id"":""20"" } ] } } } }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
public override FilterExpression OnApplyFilter(FilterExpression existingFilter) { // Use case: automatically exclude deleted resources for all requests. ResourceContext resourceContext = ResourceGraph.GetResourceContext <CallableResource>(); AttrAttribute isDeletedAttribute = resourceContext.Attributes.Single(attribute => attribute.Property.Name == nameof(CallableResource.IsDeleted)); var isNotDeleted = new ComparisonExpression(ComparisonOperator.Equals, new ResourceFieldChainExpression(isDeletedAttribute), new LiteralConstantExpression(bool.FalseString)); return(existingFilter == null ? (FilterExpression)isNotDeleted : new LogicalExpression(LogicalOperator.And, ArrayFactory.Create(isNotDeleted, existingFilter))); }
public void ResourceWithRelationshipsToResourceObject_DeviatingForeignKeyAndNoNavigationWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { // Arrange var resource = new OneToOneDependent { Principal = null, PrincipalId = 123 }; var relationships = ResourceGraph.GetRelationships <OneToOneDependent>(tr => tr.Principal); // Act var resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Null(resourceObject.Relationships["principal"].Data); }
private List <RelationshipAttribute> GetIncludedRelationshipsChain(string chain) { var parsedChain = new List <RelationshipAttribute>(); var resourceContext = ResourceGraph.GetResourceContext <Article>(); var splitPath = chain.Split('.'); foreach (var requestedRelationship in splitPath) { var relationship = resourceContext.Relationships.Single(r => r.PublicName == requestedRelationship); parsedChain.Add(relationship); resourceContext = ResourceGraph.GetResourceContext(relationship.RightType); } return(parsedChain); }
public void SerializeMany_ResourcesWithTargetedAttributes_CanBuild() { // Arrange var resources = new List <TestResource> { new TestResource { Id = 1, StringField = "value1", NullableIntField = 123 }, new TestResource { Id = 2, StringField = "value2", NullableIntField = 123 } }; _serializer.AttributesToSerialize = ResourceGraph.GetAttributes <TestResource>(tr => tr.StringField); // Act string serialized = _serializer.Serialize(resources); // Assert const string expectedFormatted = @"{ ""data"":[ { ""type"":""testResource"", ""id"":""1"", ""attributes"":{ ""stringField"":""value1"" } }, { ""type"":""testResource"", ""id"":""2"", ""attributes"":{ ""stringField"":""value2"" } } ] }"; string expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
private ResourceFieldChainExpression GetRelationshipsInPath(string includePath) { ResourceContext resourceContext = ResourceGraph.GetResourceContext <TodoItem>(); var relationships = new List <RelationshipAttribute>(); foreach (string relationshipName in includePath.Split('.')) { RelationshipAttribute relationship = resourceContext.Relationships.Single(nextRelationship => nextRelationship.PublicName == relationshipName); relationships.Add(relationship); resourceContext = ResourceGraph.GetResourceContext(relationship.RightType); } return(new ResourceFieldChainExpression(relationships)); }
public void SerializeMany_EmptyList_CanBuild() { // Arrange _serializer.AttributesToSerialize = ResourceGraph.GetAttributes <TestResource>(tr => tr.StringField); // Act string serialized = _serializer.Serialize(new List <TestResource>()); // Assert const string expectedFormatted = @"{ ""data"":[] }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
public void SerializeSingle_Null_CanBuild() { // Arrange _serializer.AttributesToSerialize = ResourceGraph.GetAttributes <TestResource>(tr => tr.StringField); // Act string serialized = _serializer.Serialize((IIdentifiable)null); // Assert const string expectedFormatted = @"{ ""data"":null }"; var expected = Regex.Replace(expectedFormatted, @"\s+", ""); Assert.Equal(expected, serialized); }
public void Setup() { _resourceMock = new ResourceMock { References = new ReferenceCollectionMock <IResource>() }; _modelFactory = new UnitOfWorkFactory <ResourcesContext>(new InMemoryDbContextManager(Guid.NewGuid().ToString())); _typeControllerMock = new Mock <IResourceTypeController>(); _linkerMock = new Mock <IResourceLinker>(); _linkerMock.Setup(l => l.SaveReferences(It.IsAny <IUnitOfWork>(), It.IsAny <Resource>(), It.IsAny <ResourceEntity>())) .Returns(new Resource[0]); _initializerMock = new Mock <IResourceInitializer>(); _initializerMock.Setup(i => i.Execute(It.IsAny <IResourceGraph>())).Returns(new[] { _resourceMock }); _linkerMock.Setup(l => l.SaveRoots(It.IsAny <IUnitOfWork>(), It.IsAny <IReadOnlyList <Resource> >())) .Returns(new[] { _resourceMock }); _linkerMock.Setup(l => l.SaveReferences(It.IsAny <IUnitOfWork>(), It.IsAny <Resource>(), It.IsAny <ResourceEntity>())) .Returns(new Resource[0]); _graph = new ResourceGraph { TypeController = _typeControllerMock.Object }; _resourceManager = new ResourceManager { UowFactory = _modelFactory, ResourceLinker = _linkerMock.Object, TypeController = _typeControllerMock.Object, Graph = _graph, Logger = new DummyLogger() }; _typeControllerMock.Setup(tc => tc.Create(typeof(ResourceMock).ResourceType())).Returns(_resourceMock); _typeControllerMock.Setup(tc => tc.Create(typeof(PublicResourceMock).ResourceType())).Returns(new PublicResourceMock() { References = new ReferenceCollectionMock <IResource>() }); using (var uow = _modelFactory.Create()) { var resourceRepo = uow.GetRepository <IResourceEntityRepository>(); resourceRepo.Create(DatabaseResourceName, typeof(ResourceMock).ResourceType()); uow.SaveChanges(); } }
public void ResourceToResourceObject_ResourceWithIncludedAttrs_CanBuild(string stringFieldValue, int?intFieldValue) { // Arrange var resource = new TestResource { StringField = stringFieldValue, NullableIntField = intFieldValue }; var attrs = ResourceGraph.GetAttributes <TestResource>(tr => new { tr.StringField, tr.NullableIntField }); // Act var resourceObject = _builder.Build(resource, attrs); // Assert Assert.NotNull(resourceObject.Attributes); Assert.Equal(2, resourceObject.Attributes.Keys.Count); Assert.Equal(stringFieldValue, resourceObject.Attributes["stringField"]); Assert.Equal(intFieldValue, resourceObject.Attributes["nullableIntField"]); }
private IReadOnlyCollection <RelationshipAttribute> GetIncludedRelationshipsChain(string chain) { var parsedChain = new List <RelationshipAttribute>(); ResourceContext resourceContext = ResourceGraph.GetResourceContext <Article>(); string[] splitPath = chain.Split('.'); foreach (string requestedRelationship in splitPath) { RelationshipAttribute relationship = resourceContext.Relationships.Single(nextRelationship => nextRelationship.PublicName == requestedRelationship); parsedChain.Add(relationship); resourceContext = ResourceGraph.GetResourceContext(relationship.RightType); } return(parsedChain); }
public void ResourceWithRequiredRelationshipsToResourceObject_DeviatingForeignKeyWhileRelationshipIncluded_IgnoresForeignKeyDuringBuild() { // Arrange var resource = new OneToOneRequiredDependent { Principal = new OneToOnePrincipal { Id = 10 }, PrincipalId = 123 }; var relationships = ResourceGraph.GetRelationships <OneToOneRequiredDependent>(tr => tr.Principal); // Act var resourceObject = _builder.Build(resource, relationships: relationships); // Assert Assert.Single(resourceObject.Relationships); Assert.NotNull(resourceObject.Relationships["principal"].Data); var ro = (ResourceIdentifierObject)resourceObject.Relationships["principal"].Data; Assert.Equal("10", ro.Id); }
public void Applies_cascading_settings_for_resource_links(LinkTypes linksInResourceContext, LinkTypes linksInOptions, LinkTypes expected) { // Arrange var exampleResourceContext = new ResourceContext { PublicName = nameof(ExampleResource), ResourceType = typeof(ExampleResource), ResourceLinks = linksInResourceContext }; var resourceGraph = new ResourceGraph(new[] { exampleResourceContext }); var request = new JsonApiRequest(); var paginationContext = new PaginationContext(); var queryStringAccessor = new EmptyRequestQueryStringAccessor(); var options = new JsonApiOptions { ResourceLinks = linksInOptions }; var linkBuilder = new LinkBuilder(options, request, paginationContext, resourceGraph, queryStringAccessor); // Act var resourceLinks = linkBuilder.GetResourceLinks(nameof(ExampleResource), "id"); // Assert if (expected == LinkTypes.Self) { resourceLinks.Self.Should().NotBeNull(); } else { resourceLinks.Should().BeNull(); } }
protected ResourceServiceTestEnvironmentBase(string resourceName) { _resourceName = resourceName; var resourceGraphBuilder = new ResourceGraphBuilder(); resourceGraphBuilder.AddResource <TResource, string>(_resourceName); SetupResourceGraph(resourceGraphBuilder); ResourceGraph = resourceGraphBuilder.Build(); JsonApiContext = Substitute.For <IJsonApiContext>(); JsonApiContext.ResourceGraph.Returns(ResourceGraph); JsonApiContext.RequestEntity.Returns(ResourceGraph.GetContextEntity(_resourceName)); JsonApiContext.Options.Returns(new JsonApiOptions { IncludeTotalRecordCount = true }); Entities = new MemoryRepository <TEntity>(GetUniqueKeySelectors(), GetInitialData()); var config = new MapperConfiguration(cfg => { cfg.ValidateInlineMaps = false; cfg.AddProfile(new XFMapperProfile(SiteId)); SetupMapper(cfg); }); Mapper = config.CreateMapper(); UserAccessor = Substitute.For <IUserAccessor>(); UserAccessor.IsAuthenticated.Returns(false); SiteOptions = Substitute.For <IOptions <SiteOptions> >(); SiteOptions.Value.Returns(new SiteOptions { Id = SiteId, Name = "xForge", Origin = new Uri("http://" + SiteAuthority), SiteDir = SiteDir, SharedDir = SharedDir }); }
public override List <SpecificResource> FindKindredResources(IResourceKey parentKey) { if (this.thumType == 0) { return(null); } if (this.isCWAL) { return(ResourceGraph.SlurpKindredResources(parentKey, this)); } List <SpecificResource> results = new List <SpecificResource>(); SpecificResource sr = THUM.getItem(this.isPNG, this.thumInstance != 0 ? this.thumInstance : parentKey.Instance, this.thumType); if (sr != null && sr.Resource != null) { results.Add(sr); } return(results); }