public void TestInitialize() { DSPServiceDefinition service = NamedStreamService.SetUpNamedStreamService(); request = service.CreateForInProcessWcf(); request.StartService(); }
private static void CreateCallCounterService(out CallCountMetadataProvider metadataProvider, out DSPServiceDefinition service) { metadataProvider = new CallCountMetadataProvider("DefaultContainer", "Default"); var entityType = metadataProvider.AddEntityType("EntityType", null, null, false /*isAbstract*/); metadataProvider.AddKeyProperty(entityType, "ID", typeof(int)); metadataProvider.AddPrimitiveProperty(entityType, "LastUpdatedAuthor", typeof(string), true /*eTag*/); var derivedType = metadataProvider.AddEntityType("DerivedType", null, entityType, false /*isAbstract*/); metadataProvider.AddPrimitiveProperty(derivedType, "LastModifiedAuthor", typeof(string), true /*eTag*/); metadataProvider.AddResourceSet("Customers", entityType); var wrapper = new DataServiceMetadataProviderWrapper(metadataProvider); DSPContext dataContext = new DSPContext(); service = new DSPServiceDefinition() { Metadata = metadataProvider, CreateDataSource = (m) => dataContext, ForceVerboseErrors = true, MediaResourceStorage = new DSPMediaResourceStorage(), SupportNamedStream = true, Writable = true, DataServiceBehavior = new OpenWebDataServiceDefinition.OpenWebDataServiceBehavior() { IncludeRelationshipLinksInResponse = true }, }; }
private static void ConfigureReadStreamUri(DSPServiceDefinition service, string resourceSetName, string resourceTypeName, string namedStreamPropertyName) { var entityWithStream = service.DataSource.GetResourceSetEntities(resourceSetName).First(); DSPMediaResource streamResource; var streamResourceProperty = service.Metadata.GetResourceType(resourceTypeName).GetNamedStreams().Single(ns => ns.Name == namedStreamPropertyName); service.MediaResourceStorage.TryGetMediaResource(entityWithStream, streamResourceProperty, out streamResource); streamResource.ReadStreamUri = new Uri("http://otherserver/stream"); }
/// <summary> /// Create a service for a specific spatial property type. /// </summary> /// <remarks> /// DEVNOTE(pqian): /// The service will populate with properties named after the property type, with a sequence number /// indicating which test sample it holds. For example, if the method is called with 3 sample data, /// and the target type is GeographyPoint, then the service will look like /// EntityType: /// ID /// GeographyPoint1 /// GeographyPoint2 /// GeographyPoint3 /// </remarks> /// <typeparam name="T">The target type</typeparam> /// <param name="data">Sample Data</param> /// <param name="overrideType">Use this type instead of typeof(T)</param> /// <param name="openProperty">Use Open Type</param> /// <param name="writable">Writable service</param> /// <returns>The constructed service definition</returns> private DSPServiceDefinition CreateSpatialPropertyService <T>(T[] data, Type overrideType = null, bool openProperty = false, bool writable = false) { Type propertyType = overrideType ?? typeof(T); DSPMetadata metadata = new DSPMetadata("SpatialServerIntegration", "AstoriaUnitTests.Tests"); var entityType = metadata.AddEntityType("EntityType", null, null, false); metadata.AddResourceSet("Entities", entityType); metadata.AddKeyProperty(entityType, "ID", typeof(int)); if (!openProperty) { for (int i = 0; i < data.Length; ++i) { metadata.AddPrimitiveProperty(entityType, propertyType.Name + i, propertyType); } } entityType.IsOpenType = openProperty; var definition = new DSPServiceDefinition() { Metadata = metadata }; if (writable) { definition.CreateDataSource = (m) => new DSPContext(); definition.Writable = true; } else { DSPContext dataSource = new DSPContext(); var entities = dataSource.GetResourceSetEntities("Entities"); var resource = new DSPResource(entityType); resource.SetValue("ID", 0); for (int i = 0; i < data.Length; ++i) { if (!openProperty) { metadata.AddPrimitiveProperty(entityType, propertyType.Name + i, propertyType); } resource.SetValue(propertyType.Name + i, data[i]); } entities.Add(resource); definition.DataSource = dataSource; } return(definition); }
private static void RunPositiveTest(ODataFormat format, TestCase testCase) { MyDSPActionProvider actionProvider = new MyDSPActionProvider(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = Metadata, CreateDataSource = CreateDataSource, ActionProvider = actionProvider }; service.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); //ctx.EnableAtom = true; Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString); MakeFinalChangesToTestCase(testCase, format, actionProvider, request); if (format == ODataFormat.Json) { JsonLightTestUtil.ConfigureContextForJsonLight(ctx, null); } else { //ctx.Format.UseAtom(); } QueryOperationResponse <CustomerEntity> qor = (QueryOperationResponse <CustomerEntity>)ctx.Execute <CustomerEntity>(uri); Assert.IsNotNull(qor); Assert.IsNull(qor.Error); IEnumerator <CustomerEntity> entities = qor.GetEnumerator(); int expectedDescriptorsPerEntity = 0; while (entities.MoveNext()) { CustomerEntity c = entities.Current; EntityDescriptor ed = ctx.GetEntityDescriptor(c); IEnumerable <OperationDescriptor> actualDescriptors = ed.OperationDescriptors; TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]); } } }
public void EdmValidNamesNotAllowedInUri() { DSPMetadata metadata = new DSPMetadata("Test", "TestNS"); var entityType = metadata.AddEntityType("MyType", null, null, false); metadata.AddKeyProperty(entityType, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityType, "Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", typeof(string)); var resourceSet = metadata.AddResourceSet("EntitySet", entityType); metadata.SetReadOnly(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true }; DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return(data); }; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext context = new DataServiceContext(request.ServiceRoot); string value = "value of Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ"; context.AddObject("EntitySet", new MyType() { ID = 1, Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ = value, }); try { context.SaveChanges(); } catch (DataServiceRequestException exception) { Assert.AreEqual(exception.Message, "An error occurred while processing this request."); } } }
public void EdmValidNamesNotAllowedInUri() { DSPMetadata metadata = new DSPMetadata("Test", "TestNS"); var entityType = metadata.AddEntityType("MyType", null, null, false); metadata.AddKeyProperty(entityType, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityType, "Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", typeof(string)); var resourceSet = metadata.AddResourceSet("EntitySet", entityType); metadata.SetReadOnly(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true }; DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return(data); }; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext context = new DataServiceContext(request.ServiceRoot); context.EnableAtom = true; context.Format.UseAtom(); string value = "value of Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ"; context.AddObject("EntitySet", new MyType() { ID = 1, Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ = value, }); context.SaveChanges(); var result = context.Execute <MyType>(new Uri("EntitySet?$orderby=Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", UriKind.Relative)).First(); Assert.AreEqual(value, result.Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ, "The roundtrip value not as expected"); } }
private static DSPServiceDefinition SetupService() { DSPMetadata metadata = new DSPMetadata("ActionsWithLargePayload", "AstoriaUnitTests.ActionTestsWithLargePayload"); var customer = metadata.AddEntityType("Customer", null, null, false); metadata.AddKeyProperty(customer, "ID", typeof(int)); var customers = metadata.AddResourceSet("Customers", customer); ComplexType = metadata.AddComplexType("AddressComplexType", null, null, false); metadata.AddPrimitiveProperty(ComplexType, "ZipCode", typeof(int)); metadata.AddPrimitiveProperty(ComplexType, "City", typeof(string)); DSPContext context = new DSPContext(); metadata.SetReadOnly(); DSPResource customer1 = new DSPResource(customer); customer1.SetValue("ID", 1); context.GetResourceSetEntities("Customers").Add(customer1); MyDSPActionProvider actionProvider = new MyDSPActionProvider(); SetUpActionWithLargeParameterPayload(actionProvider, metadata, customer); SetUpActionWithLargeCollectionParameterPayload(actionProvider, metadata, customer); SetupLargeNumberOfActions(actionProvider, metadata, customer); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => context, ForceVerboseErrors = true, Writable = true, ActionProvider = actionProvider, }; return(service); }
private static void RunClientIntegrationTestWithNamedStreams(Action <DataServiceContext> executeAndVerify, MergeOption mergeOption) { DSPServiceDefinition service = NamedStreamService.SetUpNamedStreamService(); // Configure one of the named streams on each type to have a different ReadStreamUri than the default, so we can verify it's correctly picked up and not built using conventions ConfigureReadStreamUri(service, "MySet1", "EntityWithNamedStreams", "Stream1"); ConfigureReadStreamUri(service, "MySet2", "EntityWithNamedStreams1", "RefStream1"); ConfigureReadStreamUri(service, "MySet3", "EntityWithNamedStreams2", "ColStream"); using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); ctx.MergeOption = mergeOption; JsonLightTestUtil.ConfigureContextForJsonLight(ctx); ConfigureContextForSendingRequest2Verification(ctx); executeAndVerify(ctx); } }
private static void VerifyNegativeQueryErrorMessage(DSPServiceDefinition service, Func<DataServiceContext, IEnumerable<Tuple<IQueryable[], string, Type>>> getTestCases, Action<DataServiceContext> configureContext = null) { using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext context = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4); context.EnableAtom = true; context.Format.UseAtom(); if (configureContext != null) { configureContext(context); } t.TestUtil.RunCombinations(getTestCases(context), testCase => { var queries = testCase.Item1; string expectedError = testCase.Item2; Type expectedExceptionType = testCase.Item3; foreach (var query in queries) { try { foreach (var p in query) { } Assert.Fail("Exception expected but received none."); } catch (Exception e) { Assert.AreEqual(expectedExceptionType, e.GetType()); string errorMsg = e.InnerException == null ? e.Message : e.InnerException.Message; Assert.AreEqual(AstoriaUnitTests.Tests.LinqTests.Normalize(expectedError), AstoriaUnitTests.Tests.LinqTests.Normalize(errorMsg)); } } }); } }
public void EdmValidNamesNotAllowedInUri() { DSPMetadata metadata = new DSPMetadata("Test", "TestNS"); var entityType = metadata.AddEntityType("MyType", null, null, false); metadata.AddKeyProperty(entityType, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityType, "Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", typeof(string)); var resourceSet = metadata.AddResourceSet("EntitySet", entityType); metadata.SetReadOnly(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true }; DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return data; }; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext context = new DataServiceContext(request.ServiceRoot); context.EnableAtom = true; context.Format.UseAtom(); string value = "value of Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ"; context.AddObject("EntitySet", new MyType() { ID = 1, Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ = value, }); context.SaveChanges(); var result = context.Execute<MyType>(new Uri("EntitySet?$orderby=Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", UriKind.Relative)).First(); Assert.AreEqual(value, result.Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ, "The roundtrip value not as expected"); } }
private static void SendRequestAndVerifyUriAndContext(DSPServiceDefinition service, Func<IEnumerable<Tuple<Func<DataServiceContext, IQueryable>[], Func<DataServiceContext, string>, Action<DataServiceContext, IQueryable, List<object>>>>> queryUrisAndValidations) { using (InProcessWebRequest request = (InProcessWebRequest)service.CreateForInProcess()) { request.StartService(); ODataProtocolVersion[] versions = new ODataProtocolVersion[] { ODataProtocolVersion.V4 }; t.TestUtil.RunCombinations(queryUrisAndValidations(), versions, (testCase, version) => { var getQueries = testCase.Item1; var getExpectedUri = testCase.Item2; var validate = testCase.Item3; foreach (var getQuery in getQueries) { var host = new t.TestServiceHost2(); var requestMessage = new DataServiceHostRequestMessage(host); var ctx = new DataServiceContextWithCustomTransportLayer(request.ServiceRoot, version, () => requestMessage, () => { request.SendRequest(host); return new DataServiceHostResponseMessage(host); }); ctx.EnableAtom = true; ctx.Format.UseAtom(); if (version < ODataProtocolVersion.V4) { var query = getQuery(ctx); try { foreach (var p in query) { } Assert.Fail("Exception expected but received none."); } catch (NotSupportedException e) { Assert.IsTrue( "The expression 'TypeAs' is not supported when MaxProtocolVersion is less than '4.0'." == e.Message || "The method 'OfType' is not supported when MaxProtocolVersion is less than '4.0'." == e.Message); } } else { #region Setup resolvers and events ctx.ResolveType = (typeName) => { if (typeName == typeof(Employee).FullName) { return typeof(Employee); } if (typeName == typeof(PeopleManager).FullName) { return typeof(PeopleManager); } return null; }; ctx.SendingRequest2 += (sender, e) => { Assert.AreEqual("4.0", e.RequestMessage.GetHeader("OData-Version"), "OData-Version mismatch."); Assert.AreEqual("4.0", e.RequestMessage.GetHeader("OData-MaxVersion"), "OData-MaxVersion mismatch."); }; #endregion Setup resolvers and events // Validate Uri var query = getQuery(ctx); string clientGeneratedUri = query.ToString(); Assert.AreEqual(getExpectedUri(ctx), clientGeneratedUri); #region Validate entities List<object> materializedObjects = new List<object>(); // Materialize and validate LinkInfos foreach (var e in query) { EntityDescriptor descriptor = ctx.GetEntityDescriptor(e); if (descriptor != null) { foreach (var link in descriptor.LinkInfos) { switch (link.Name) { case "Aquaintances": case "DirectReports": case "Manager": case "Colleagues": case "BestFriend": case "Friends": // If the entity is not of the base type (Person), then expect navigation links to have a type segment. if (descriptor.ServerTypeName != "AstoriaUnitTests.Tests.DerivedProperty.Person") { t.TestUtil.AssertContains(link.NavigationLink.OriginalString, descriptor.ServerTypeName); if (link.AssociationLink != null) { t.TestUtil.AssertContains(link.AssociationLink.OriginalString, descriptor.ServerTypeName); } } break; default: Assert.Fail("Unexpected link: " + link.Name); return; } } } materializedObjects.Add(e); } #endregion Validate entities #region Validate Links // Validate LinkDescriptors foreach (LinkDescriptor link in ctx.Links) { string identity = ctx.GetEntityDescriptor(link.Source).Identity.AbsoluteUri; int startIdx = identity.IndexOf('(') + 1; int endIdx = identity.IndexOf(')'); int sourceId = int.Parse(identity.Substring(startIdx, endIdx - startIdx)); identity = ctx.GetEntityDescriptor(link.Target).Identity.AbsoluteUri; startIdx = identity.IndexOf('(') + 1; endIdx = identity.IndexOf(')'); int targetId = int.Parse(identity.Substring(startIdx, endIdx - startIdx)); switch (link.SourceProperty) { case "DirectReports": switch (sourceId) { case 1: //"Foo": Assert.Fail("DirectReports link not expected for Foo"); break; case 2: //"Andy": //Assert.IsTrue(targetName == "Pratik" || targetName == "Jimmy"); Assert.IsTrue(targetId == 3 || targetId == 4); break; case 3: //"Pratik": Assert.Fail("DirectReports link not expected for Pratik"); break; case 4: //"Jimmy": Assert.Fail("DirectReports link not expected for Jimmy"); break; case 5: //"Shyam": //Assert.IsTrue(targetName == "Andy" || targetName == "Marcelo"); Assert.IsTrue(targetId == 2 || targetId == 6); break; case 6: //"Marcelo": Assert.Fail("DirectReports link not expected for Marcelo"); break; default: Assert.Fail("Unrecognized id: " + sourceId); break; } break; case "Manager": switch (sourceId) { case 1: //"Foo": Assert.Fail("Manager link not expected for Foo"); break; case 2: //"Andy": //Assert.AreEqual("Shyam", targetName); Assert.AreEqual(5, targetId); break; case 3: //"Pratik": //Assert.AreEqual("Andy", targetName); Assert.AreEqual(2, targetId); break; case 4: //"Jimmy": //Assert.AreEqual("Andy", targetName); Assert.AreEqual(2, targetId); break; case 5: //"Shyam": //Assert.AreEqual("Shyam", targetName); Assert.AreEqual(5, targetId); break; case 6: //"Marcelo": //Assert.AreEqual("Shyam", targetName); Assert.AreEqual(5, targetId); break; default: Assert.Fail("Unrecognized id: " + sourceId); break; } break; case "Colleagues": switch (sourceId) { case 1: //"Foo": Assert.Fail("Colleagues link not expected for Foo"); break; case 2: //"Andy": //Assert.AreEqual("Marcelo", targetName); Assert.AreEqual(6, targetId); break; case 3: //"Pratik": //Assert.AreEqual("Jimmy", targetName); Assert.AreEqual(4, targetId); break; case 4: //"Jimmy": //Assert.AreEqual("Pratik", targetName); Assert.AreEqual(3, targetId); break; case 5: //"Shyam": Assert.Fail("Colleagues link not expected for Shyam"); break; case 6: //"Marcelo": //Assert.AreEqual("Andy", targetName); Assert.AreEqual(2, targetId); break; default: Assert.Fail("Unrecognized id: " + sourceId); break; } break; case "BestFriend": switch (sourceId) { case 1: //"Foo": //Assert.AreEqual("Pratik", targetName); Assert.AreEqual(3, targetId); break; case 2: //"Andy": //Assert.AreEqual("Shyam", targetName); Assert.AreEqual(5, targetId); break; case 3: //"Pratik": //Assert.AreEqual("Andy", targetName); Assert.AreEqual(2, targetId); break; case 4: //"Jimmy": //Assert.AreEqual("Foo", targetName); Assert.AreEqual(1, targetId); break; case 5: //"Shyam": //Assert.AreEqual("Marcelo", targetName); Assert.AreEqual(6, targetId); break; case 6: //"Marcelo": //Assert.AreEqual("Jimmy", targetName); Assert.AreEqual(4, targetId); break; default: Assert.Fail("Unrecognized id: " + sourceId); break; } break; case "Friends": break; default: Assert.Fail("Unexpected link descriptor: " + link.SourceProperty); return; } } #endregion Validate Links // Validation specific to the test case. validate(ctx, query, materializedObjects); } } }); } }
public void Collection_ProcessingPipeline() { var metadata = CreateMetadataForXFeatureEntity(); Func<int, DSPResource> CreateNewXFeatureEntityResource = (id) => { DSPResourceWithCollectionProperty newResource = new DSPResourceWithCollectionProperty(metadata.GetResourceType("XFeatureTestsEntity")); newResource.SetRawValue("ID", id); newResource.SetRawValue("Description", "Second"); newResource.SetRawValue("Strings", new List<string>() { "One", "Two" }); newResource.SetRawValue("Structs", new List<DSPResource>()); return newResource; }; var actualCallCount = new ProcessingPipelineCallCount(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => { DSPContext context = new DSPContext(); context.GetResourceSetEntities("Entities").Add(CreateNewXFeatureEntityResource(0)); return context; }, Writable = true, }; service.ProcessingPipeline.ProcessingRequest = (sender, args) => { actualCallCount.ProcessingRequestCallCount++; }; service.ProcessingPipeline.ProcessedRequest = (sender, args) => { actualCallCount.ProcessedRequestCallCount++; }; service.ProcessingPipeline.ProcessingChangeset = (sender, args) => { actualCallCount.ProcessingChangesetCallCount++; }; service.ProcessingPipeline.ProcessedChangeset = (sender, args) => { actualCallCount.ProcessedChangesetCallCount++; }; var testCases = new ProcessingPipelineTestCase[] { new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "GET"; r.RequestUriString = "/Entities"; r.Accept = format; }, }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "GET"; r.RequestUriString = "/Entities(0)/Strings"; r.Accept = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; }, }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "GET"; r.RequestUriString = "/Entities(0)/Structs"; r.Accept = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; }, }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "POST"; r.RequestUriString = "/Entities"; r.Accept = format; r.RequestContentType = format; r.SetRequestStreamAsText(DSPResourceSerializer.WriteEntity( CreateNewXFeatureEntityResource(1), DSPResourceSerializer.SerializerFormatFromMimeType(format))); }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "PUT"; r.RequestUriString = "/Entities(0)"; r.Accept = format; r.RequestContentType = format; r.SetRequestStreamAsText(DSPResourceSerializer.WriteEntity( CreateNewXFeatureEntityResource(0), DSPResourceSerializer.SerializerFormatFromMimeType(format))); }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "PATCH"; r.RequestUriString = "/Entities(0)"; r.Accept = format; r.RequestContentType = format; r.SetRequestStreamAsText(DSPResourceSerializer.WriteEntity( CreateNewXFeatureEntityResource(0), DSPResourceSerializer.SerializerFormatFromMimeType(format))); }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "DELETE"; r.RequestUriString = "/Entities(0)"; r.Accept = format; }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "PUT"; r.RequestUriString = "/Entities(0)/Strings"; r.Accept = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; r.RequestContentType = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; r.SetRequestStreamAsText(DSPResourceSerializer.WriteProperty( metadata.GetResourceType("XFeatureTestsEntity").Properties.First(p => p.Name == "Strings"), new List<string> { "Foo", "Bar" }, DSPResourceSerializer.SerializerFormatFromMimeType(format))); }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, new ProcessingPipelineTestCase() { SetupRequest = (r, format) => { r.HttpMethod = "PUT"; r.RequestUriString = "/Entities(0)/Structs"; r.Accept = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; r.RequestContentType = format == UnitTestsUtil.AtomFormat ? UnitTestsUtil.MimeApplicationXml : format; r.SetRequestStreamAsText(DSPResourceSerializer.WriteProperty( metadata.GetResourceType("XFeatureTestsEntity").Properties.First(p => p.Name == "Structs"), new List<DSPResource>(), DSPResourceSerializer.SerializerFormatFromMimeType(format))); }, ExpectedCallCount = new ProcessingPipelineCallCount() { ProcessingChangesetCallCount = 1, ProcessedChangesetCallCount = 1 } }, }; using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore()) using (TestWebRequest request = service.CreateForInProcess()) { DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true; TestUtil.RunCombinations(testCases, UnitTestsUtil.BooleanValues, UnitTestsUtil.ResponseFormats, (testCase, batch, format) => { service.ClearChanges(); actualCallCount.Clear(); var expectedCallCount = new ProcessingPipelineCallCount(testCase.ExpectedCallCount); // Each request must fire at least one ProcessingRequest and ProcessedRequest expectedCallCount.ProcessingRequestCallCount++; expectedCallCount.ProcessedRequestCallCount++; if (batch) { InMemoryWebRequest batchPart = new InMemoryWebRequest(); testCase.SetupRequest(batchPart, format); BatchWebRequest batchRequest = new BatchWebRequest(); if (batchPart.HttpMethod == "GET") { batchRequest.Parts.Add(batchPart); } else { var changeset = new BatchWebRequest.Changeset(); changeset.Parts.Add(batchPart); batchRequest.Changesets.Add(changeset); } batchRequest.SendRequest(request); } else { request.RequestContentType = null; request.RequestStream = null; testCase.SetupRequest(request, format); request.SendRequest(); } actualCallCount.AssertEquals(expectedCallCount); }); } }
private static DSPServiceDefinition ModelWithDerivedNavigationProperties() { // Navigation Collection Property: Client - Entity, Server - NonEntity DSPMetadata metadata = new DSPMetadata("ModelWithDerivedNavProperties", "AstoriaUnitTests.Tests.DerivedProperty"); var peopleType = metadata.AddEntityType("Person", null, null, false); metadata.AddKeyProperty(peopleType, "ID", typeof(int)); metadata.AddPrimitiveProperty(peopleType, "Name", typeof(string)); var bestFriendProperty = metadata.AddResourceReferenceProperty(peopleType, "BestFriend", peopleType); var friendsProperty = metadata.AddResourceSetReferenceProperty(peopleType, "Friends", peopleType); var aquaintancesProperty = metadata.AddResourceSetReferenceProperty(peopleType, "Aquaintances", peopleType); var peopleSet = metadata.AddResourceSet("People", peopleType); var officeType = metadata.AddComplexType("Office", null, null, false); metadata.AddPrimitiveProperty(officeType, "Building", typeof(string)); metadata.AddPrimitiveProperty(officeType, "OfficeNumber", typeof(int)); var vacationType = metadata.AddComplexType("Vacation", null, null, false); metadata.AddPrimitiveProperty(vacationType, "Description", typeof(string)); metadata.AddPrimitiveProperty(vacationType, "StartDate", typeof(DateTimeOffset)); metadata.AddPrimitiveProperty(vacationType, "EndDate", typeof(DateTimeOffset)); var employeeType = metadata.AddEntityType("Employee", null, peopleType, false); metadata.AddCollectionProperty(employeeType, "Vacations", vacationType); metadata.AddComplexProperty(employeeType, "Office", officeType); metadata.AddCollectionProperty(employeeType, "Skills", ResourceType.GetPrimitiveResourceType(typeof(string))); metadata.AddNamedStreamProperty(employeeType, "Photo"); var managerType = metadata.AddEntityType("PeopleManager", null, employeeType, false); var drProperty = metadata.AddResourceSetReferenceProperty(managerType, "DirectReports", employeeType); var managerProperty = metadata.AddResourceReferenceProperty(employeeType, "Manager", managerType); var colleaguesProperty = metadata.AddResourceSetReferenceProperty(employeeType, "Colleagues", employeeType); metadata.AddResourceAssociationSet(new ResourceAssociationSet( "Manager_DirectReports", new ResourceAssociationSetEnd(peopleSet, employeeType, managerProperty), new ResourceAssociationSetEnd(peopleSet, managerType, drProperty))); metadata.AddResourceAssociationSet(new ResourceAssociationSet( "BestFriend", new ResourceAssociationSetEnd(peopleSet, peopleType, bestFriendProperty), new ResourceAssociationSetEnd(peopleSet, peopleType, null))); metadata.AddResourceAssociationSet(new ResourceAssociationSet( "Friends", new ResourceAssociationSetEnd(peopleSet, peopleType, friendsProperty), new ResourceAssociationSetEnd(peopleSet, peopleType, null))); metadata.AddResourceAssociationSet(new ResourceAssociationSet( "Colleagues", new ResourceAssociationSetEnd(peopleSet, employeeType, colleaguesProperty), new ResourceAssociationSetEnd(peopleSet, employeeType, null))); metadata.AddResourceAssociationSet(new ResourceAssociationSet( "Aquaintances", new ResourceAssociationSetEnd(peopleSet, peopleType, aquaintancesProperty), new ResourceAssociationSetEnd(peopleSet, peopleType, null))); metadata.SetReadOnly(); DSPContext context = new DSPContext(); DSPResource people1 = new DSPResource(peopleType); people1.SetValue("ID", 1); people1.SetValue("Name", "Foo"); people1.SetValue("Friends", new List<DSPResource>()); DSPResource thanksgivingVacation = new DSPResource(vacationType); thanksgivingVacation.SetValue("Description", "Thanksgiving"); thanksgivingVacation.SetValue("StartDate", new DateTime(2011, 11, 19)); thanksgivingVacation.SetValue("EndDate", new DateTime(2011, 11, 27)); DSPResource christmasVacation = new DSPResource(vacationType); christmasVacation.SetValue("Description", "Christmas"); christmasVacation.SetValue("StartDate", new DateTime(2011, 12, 24)); christmasVacation.SetValue("EndDate", new DateTime(2012, 1, 2)); DSPResource andy = new DSPResource(managerType); andy.SetValue("ID", 2); andy.SetValue("Name", "Andy"); andy.SetValue("Vacations", new List<DSPResource>() { thanksgivingVacation, christmasVacation }); var office = new DSPResource(officeType); office.SetValue("Building", "Building 18"); office.SetValue("OfficeNumber", 100); andy.SetValue("Office", office); andy.SetValue("Skills", new List<string>() { "CSharp", "VB", "SQL" }); andy.SetValue("Friends", new List<DSPResource>() { people1 }); andy.SetValue("Aquaintences", new List<DSPResource>()); DSPResource pratik = new DSPResource(employeeType); pratik.SetValue("ID", 3); pratik.SetValue("Name", "Pratik"); pratik.SetValue("Manager", andy); pratik.SetValue("Vacations", new List<DSPResource>() { christmasVacation }); office = new DSPResource(officeType); office.SetValue("Building", "Building 18"); office.SetValue("OfficeNumber", 101); pratik.SetValue("Office", office); pratik.SetValue("Skills", new List<string>() { "CSharp", "VB", "SQL" }); pratik.SetValue("Friends", new List<DSPResource>() { people1 }); pratik.SetValue("Aquaintences", new List<DSPResource>()); DSPResource jimmy = new DSPResource(employeeType); jimmy.SetValue("ID", 4); jimmy.SetValue("Name", "Jimmy"); jimmy.SetValue("Manager", andy); jimmy.SetValue("Vacations", new List<DSPResource>() { thanksgivingVacation, christmasVacation }); office = new DSPResource(officeType); office.SetValue("Building", "Building 18"); office.SetValue("OfficeNumber", 102); jimmy.SetValue("Office", office); jimmy.SetValue("Skills", new List<string>() { "CSharp", "SQL" }); jimmy.SetValue("Friends", new List<DSPResource>() { people1 }); jimmy.SetValue("Aquaintences", new List<DSPResource>()); andy.SetValue("DirectReports", new List<DSPResource>() { pratik, jimmy }); DSPResource shyam = new DSPResource(managerType); shyam.SetValue("ID", 5); shyam.SetValue("Name", "Shyam"); shyam.SetValue("Manager", shyam); shyam.SetValue("Vacations", new List<DSPResource>() { thanksgivingVacation, christmasVacation }); office = new DSPResource(officeType); office.SetValue("Building", "Building 18"); office.SetValue("OfficeNumber", 103); shyam.SetValue("Office", office); shyam.SetValue("Skills", new List<string>()); shyam.SetValue("Friends", new List<DSPResource>() { people1 }); shyam.SetValue("Aquaintences", new List<DSPResource>()); DSPResource marcelo = new DSPResource(employeeType); marcelo.SetValue("ID", 6); marcelo.SetValue("Name", "Marcelo"); marcelo.SetValue("Manager", shyam); marcelo.SetValue("Vacations", new List<DSPResource>()); office = new DSPResource(officeType); office.SetValue("Building", "Building 18"); office.SetValue("OfficeNumber", 104); marcelo.SetValue("Office", office); marcelo.SetValue("Skills", new List<string>() { "CSharp", "VB", "SQL" }); marcelo.SetValue("Friends", new List<DSPResource>() { people1 }); marcelo.SetValue("Aquaintences", new List<DSPResource>()); andy.SetValue("Manager", shyam); shyam.SetValue("DirectReports", new List<DSPResource>() { andy, marcelo }); pratik.SetValue("BestFriend", andy); andy.SetValue("BestFriend", shyam); shyam.SetValue("BestFriend", marcelo); marcelo.SetValue("BestFriend", jimmy); jimmy.SetValue("BestFriend", people1); people1.SetValue("BestFriend", pratik); andy.SetValue("Colleagues", new List<DSPResource>() { marcelo }); pratik.SetValue("Colleagues", new List<DSPResource>() { jimmy }); jimmy.SetValue("Colleagues", new List<DSPResource>() { pratik }); marcelo.SetValue("Colleagues", new List<DSPResource>() { andy }); shyam.SetValue("Colleagues", new List<DSPResource>()); people1.SetValue("Aquaintances", new List<DSPResource>() { pratik, andy, jimmy, shyam, marcelo }); var people = context.GetResourceSetEntities("People"); people.Add(people1); people.Add(andy); people.Add(pratik); people.Add(jimmy); people.Add(shyam); people.Add(marcelo); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => context, ForceVerboseErrors = true, MediaResourceStorage = new DSPMediaResourceStorage(), SupportNamedStream = true, Writable = true, DataServiceBehavior = new OpenWebDataServiceDefinition.OpenWebDataServiceBehavior() { IncludeRelationshipLinksInResponse = true }, }; return service; }
private static void VerifyMLEs(DSPServiceDefinition service, object clientMle, byte[] clientBlob) { DSPResource serverMle = (DSPResource)service.CurrentDataSource.GetResourceSetEntities("Entities").FirstOrDefault( e => (int)(((DSPResource)e).GetValue("ID")) == (int)clientMle.GetType().GetProperty("ID").GetValue(clientMle, null)); Assert.IsNotNull(serverMle, "MLE not saved correctly on the server"); ValidateResult(clientMle, serverMle, true); DSPMediaResource serverBlob; service.MediaResourceStorage.TryGetMediaResource(serverMle, null, out serverBlob); bool isEmptyStream; using (Stream serverStream = serverBlob.GetReadStream(out isEmptyStream)) { Assert.IsFalse(isEmptyStream, "Unexpected empty stream"); VerifyStream(clientBlob, serverStream); } }
private static DSPServiceDefinition SetupService() { DSPMetadata metadata = new DSPMetadata("ActionsWithLargePayload", "AstoriaUnitTests.ActionTestsWithLargePayload"); var customer = metadata.AddEntityType("Customer", null, null, false); metadata.AddKeyProperty(customer, "ID", typeof(int)); var customers = metadata.AddResourceSet("Customers", customer); ComplexType = metadata.AddComplexType("AddressComplexType", null, null, false); metadata.AddPrimitiveProperty(ComplexType, "ZipCode", typeof(int)); metadata.AddPrimitiveProperty(ComplexType, "City", typeof(string)); DSPContext context = new DSPContext(); metadata.SetReadOnly(); DSPResource customer1 = new DSPResource(customer); customer1.SetValue("ID", 1); context.GetResourceSetEntities("Customers").Add(customer1); MyDSPActionProvider actionProvider = new MyDSPActionProvider(); SetUpActionWithLargeParameterPayload(actionProvider, metadata, customer); SetUpActionWithLargeCollectionParameterPayload(actionProvider, metadata, customer); SetupLargeNumberOfActions(actionProvider, metadata, customer); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => context, ForceVerboseErrors = true, Writable = true, ActionProvider = actionProvider, }; return service; }
public void Collection_BatchIDataServiceHostAndChangeTracking() { DSPMetadata metadata = CreateMetadataForXFeatureEntity(); TestUtil.RunCombinations( new bool[] { false, true }, new bool[] { false, true }, new Type[] { typeof(IDataServiceHost), typeof(IDataServiceHost2) }, (sendAsBatch, replaceOnUpdate, hostInterfaceType) => { DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, HostInterfaceType = hostInterfaceType }; DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return data; }; // This test operates just on 2 entities - so let's take just first two from the set List<object> testEntities = CreateClientTestEntities().Take(2).ToList<object>(); SaveChangesOptions saveOptions = (sendAsBatch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None) | (replaceOnUpdate ? SaveChangesOptions.ReplaceOnUpdate : SaveChangesOptions.None); using (TestWebRequest request = service.CreateForInProcessWcf()) using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore()) { DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true; request.StartService(); // Add entities DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); foreach (XFeatureTestsEntity entity in testEntities) { ctx.AddObject("Entities", entity); } VerifyStateOfEntities(ctx, testEntities, EntityStates.Added); ctx.SaveChanges(saveOptions); VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged); VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities")); // Change one of the entities ((XFeatureTestsEntity)testEntities[0]).Structs.RemoveAt(0); ctx.UpdateObject(testEntities[0]); VerifyStateOfEntities(ctx, new[] { testEntities[0] }, EntityStates.Modified); VerifyStateOfEntities(ctx, new[] { testEntities[1] }, EntityStates.Unchanged); ctx.SaveChanges(saveOptions); VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged); VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities")); // Change collection in both entities List<string> tempCollection = ((XFeatureTestsEntity)testEntities[0]).Strings; ((XFeatureTestsEntity)testEntities[0]).Strings = ((XFeatureTestsEntity)testEntities[1]).Strings; ((XFeatureTestsEntity)testEntities[1]).Strings = tempCollection; ctx.UpdateObject(testEntities[0]); ctx.UpdateObject(testEntities[1]); VerifyStateOfEntities(ctx, testEntities, EntityStates.Modified); ctx.SaveChanges(saveOptions); VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged); VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities")); // Delete entities ctx.DeleteObject(testEntities[0]); ctx.DeleteObject(testEntities[1]); VerifyStateOfEntities(ctx, testEntities, EntityStates.Deleted); ctx.SaveChanges(saveOptions); testEntities.RemoveAt(0); testEntities.RemoveAt(0); VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities")); } }); }
public void Collection_Count() { TestUtil.RunCombinations(new int?[] { null, 1, 2 }, (sdpPageSize) => { DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = CreateMetadataForXFeatureEntity(), CreateDataSource = (m) => new DSPContext(), Writable = true, PageSizeCustomizer = (config, type) => { if (sdpPageSize.HasValue) { config.SetEntitySetPageSize("Entities", sdpPageSize.Value); } } }; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); var ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); PopulateClientContextWithTestEntities(ctx); var testCases = new[] { new { // Just entity set Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities"), TotalCount = 3, QueryCount = 3 }, new { // $filter Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities").Where(e => e.ID < 2), TotalCount = 1, QueryCount = 1 }, new { // $top Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities").Take(1), TotalCount = 3, QueryCount = 1 }, new { // $skip Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities").Skip(1), TotalCount = 3, QueryCount = 2 }, new { // $orderby Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities").OrderBy(e => e.Description), TotalCount = 3, QueryCount = 3 }, new { // $select Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities") .Select(e => new XFeatureTestsEntity() { Strings = e.Strings }), TotalCount = 3, QueryCount = 3 }, new { // $expand Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities").Expand("NextTestEntity"), TotalCount = 3, QueryCount = 3 }, new { // $select and $expand Query = (DataServiceQuery<XFeatureTestsEntity>)ctx.CreateQuery<XFeatureTestsEntity>("Entities") .Select(e => new XFeatureTestsEntity() { NextTestEntity = e.NextTestEntity == null ? null : new XFeatureTestsEntity() { Description = e.NextTestEntity.Description } }), TotalCount = 3, QueryCount = 3 }, }; TestUtil.RunCombinations(testCases, (testCase) => { // $count int actualCount = testCase.Query.Count(); int expectedCount = testCase.QueryCount; Assert.AreEqual(expectedCount, actualCount, "The $count query didn't return correct number."); // query $count var response = (QueryOperationResponse<XFeatureTestsEntity>)testCase.Query.IncludeTotalCount().Execute(); Assert.AreEqual(testCase.TotalCount, response.TotalCount, "The $count query didn't return correct number."); // The actual number of results returned int expectedResultCount = expectedCount; if (sdpPageSize.HasValue && sdpPageSize.Value < expectedResultCount) expectedResultCount = sdpPageSize.Value; Assert.AreEqual(expectedResultCount, response.Count(), "The actual number of results returned doesn't match the expected count."); }); } }); }
internal static DSPServiceDefinition SetUpNamedStreamService() { DSPMetadata metadata = new DSPMetadata("NamedStreamIDSPContainer", "NamedStreamTest"); // entity with streams ResourceType entityWithNamedStreams = metadata.AddEntityType("EntityWithNamedStreams", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityWithNamedStreams, "Name", typeof(string)); ResourceProperty streamInfo1 = new ResourceProperty("Stream1", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams.AddProperty(streamInfo1); ResourceProperty streamInfo2 = new ResourceProperty("Stream2", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams.AddProperty(streamInfo2); // entity1 with streams ResourceType entityWithNamedStreams1 = metadata.AddEntityType("EntityWithNamedStreams1", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams1, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityWithNamedStreams1, "Name", typeof(string)); ResourceProperty refStreamInfo1 = new ResourceProperty("RefStream1", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams1.AddProperty(refStreamInfo1); // entity2 with streams ResourceType entityWithNamedStreams2 = metadata.AddEntityType("EntityWithNamedStreams2", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams2, "ID", typeof(string)); metadata.AddPrimitiveProperty(entityWithNamedStreams2, "Name", typeof(string)); ResourceProperty collectionStreamInfo = new ResourceProperty("ColStream", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams2.AddProperty(collectionStreamInfo); ResourceSet set1 = metadata.AddResourceSet("MySet1", entityWithNamedStreams); ResourceSet set2 = metadata.AddResourceSet("MySet2", entityWithNamedStreams1); ResourceSet set3 = metadata.AddResourceSet("MySet3", entityWithNamedStreams2); // add navigation property to entityWithNamedStreams metadata.AddResourceReferenceProperty(entityWithNamedStreams, "Ref", set2, entityWithNamedStreams1); metadata.AddResourceSetReferenceProperty(entityWithNamedStreams, "Collection", set3, entityWithNamedStreams2); metadata.AddResourceSetReferenceProperty(entityWithNamedStreams2, "Collection1", set2, entityWithNamedStreams1); DSPServiceDefinition service = new DSPServiceDefinition(); service.Metadata = metadata; service.MediaResourceStorage = new DSPMediaResourceStorage(); service.SupportMediaResource = true; service.SupportNamedStream = true; service.ForceVerboseErrors = true; service.PageSizeCustomizer = (config, type) => { config.SetEntitySetPageSize("MySet3", 1); }; // populate data DSPContext context = new DSPContext(); DSPResource entity1 = new DSPResource(entityWithNamedStreams); { context.GetResourceSetEntities("MySet1").Add(entity1); entity1.SetValue("ID", 1); entity1.SetValue("Name", "Foo"); DSPMediaResource namedStream1 = service.MediaResourceStorage.CreateMediaResource(entity1, streamInfo1); namedStream1.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; namedStream1.GetWriteStream().Write(data1, 0, data1.Length); DSPMediaResource namedStream2 = service.MediaResourceStorage.CreateMediaResource(entity1, streamInfo2); namedStream2.ContentType = "image/jpeg"; byte[] data2 = new byte[] { 0, 1, 2, 3, 4 }; namedStream2.GetWriteStream().Write(data2, 0, data2.Length); } DSPResource entity2 = new DSPResource(entityWithNamedStreams1); { context.GetResourceSetEntities("MySet2").Add(entity2); entity2.SetValue("ID", 3); entity2.SetValue("Name", "Bar"); DSPMediaResource refNamedStream1 = service.MediaResourceStorage.CreateMediaResource(entity2, refStreamInfo1); refNamedStream1.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; refNamedStream1.GetWriteStream().Write(data1, 0, data1.Length); // set the navigation property entity1.SetValue("Ref", entity2); } { DSPResource entity3 = new DSPResource(entityWithNamedStreams2); context.GetResourceSetEntities("MySet3").Add(entity3); entity3.SetValue("ID", "ABCDE"); entity3.SetValue("Name", "Bar"); DSPMediaResource stream = service.MediaResourceStorage.CreateMediaResource(entity3, collectionStreamInfo); stream.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; stream.GetWriteStream().Write(data1, 0, data1.Length); entity3.SetValue("Collection1", new List<DSPResource>() { entity2 }); DSPResource entity4 = new DSPResource(entityWithNamedStreams2); context.GetResourceSetEntities("MySet3").Add(entity4); entity4.SetValue("ID", "XYZ"); entity4.SetValue("Name", "Foo"); DSPMediaResource stream1 = service.MediaResourceStorage.CreateMediaResource(entity3, collectionStreamInfo); stream1.ContentType = "image/jpeg"; stream1.GetWriteStream().Write(data1, 0, data1.Length); entity4.SetValue("Collection1", new List<DSPResource>() { entity2 }); entity1.SetValue("Collection", new List<DSPResource>() { entity3, entity4 }); } service.DataSource = context; return service; }
private static void CollectionAndServerDrivenPagingTestRunner(Action<DataServiceContext, DSPContext, int?, bool> test) { DSPMetadata metadata = CreateMetadataForXFeatureEntity(); TestUtil.RunCombinations( new int?[] { null, 1, 2, 7, 100 }, new bool[] { false, true }, (pageSize, enableCustomPaging) => { DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, EnableCustomPaging = enableCustomPaging && pageSize != null /*pageSize == null means "no paging at all" */ }; if (pageSize != null) { if (!enableCustomPaging) { service.PageSizeCustomizer = (config, serviceType) => config.SetEntitySetPageSize("Entities", (int)pageSize); } else { CountManager.MaxCount = (int)pageSize; } } using (TestWebRequest request = service.CreateForInProcessWcf()) { DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return data; }; request.StartService(); DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); PopulateClientContextWithTestEntities(ctx); test(ctx, data, pageSize, enableCustomPaging); } }); }
public void Collection_IExpandProvider() { var metadata = CreateMetadataForXFeatureEntity(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => new DSPContext(), Writable = true, SupportIExpandProvider = true }; string[] responseFormats = new string[] { UnitTestsUtil.AtomFormat }; TestUtil.RunCombinations(responseFormats, (format) => { using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); PopulateClientContextWithTestEntities(ctx); // set navigation ((XFeatureTestsEntity)ctx.Entities.Last().Entity).NextTestEntity = (XFeatureTestsEntity)ctx.Entities.First().Entity; ctx.SetLink(ctx.Entities.Last().Entity, "NextTestEntity", ctx.Entities.First().Entity); ctx.SaveChanges(); request.RequestUriString = "/Entities?$expand=NextTestEntity"; request.Accept = format; request.SendRequest(); XDocument resp = UnitTestsUtil.GetResponseAsAtomXLinq(request); Assert.IsNotNull(resp.Descendants(UnitTestsUtil.MetadataNamespace + "inline").Elements(UnitTestsUtil.AtomNamespace + "entry").FirstOrDefault(), "No expanded entities in the payload."); foreach (XFeatureTestsEntity entity in ctx.Entities.Select(e => e.Entity)) { var entityXElement = (from e in resp.Element(UnitTestsUtil.AtomNamespace + "feed").Elements(UnitTestsUtil.AtomNamespace + "entry") where (int)e.Element(UnitTestsUtil.AtomNamespace + "content") .Element(UnitTestsUtil.MetadataNamespace + "properties") .Element(UnitTestsUtil.DataNamespace + "ID") == entity.ID select e).Single(); ValidateResult(entity, entityXElement); } } }); }
public void Collection_Configuration() { var testCases = new ConfigurationTestCase[] { // AcceptCountRequests new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.AcceptCountRequests = true; }, RequestUri = "/Entities/$count", }, new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.AcceptCountRequests = false; }, RequestUri = "/Entities/$count", ExpectedExceptionMessage = "The ability of the data service to return row count information is disabled. To enable this functionality, set the DataServiceConfiguration.AcceptCountRequests property to true." }, new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.AcceptCountRequests = false; }, RequestUri = "/Entities?$count=true", ExpectedExceptionMessage = "The ability of the data service to return row count information is disabled. To enable this functionality, set the DataServiceConfiguration.AcceptCountRequests property to true." }, // AcceptProjectionRequests new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.AcceptProjectionRequests = true; }, RequestUri = "/Entities?$select=Strings", }, new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.AcceptProjectionRequests = false; }, RequestUri = "/Entities?$select=Strings", ExpectedExceptionMessage = "The ability to use the $select query option to define a projection in a data service query is disabled. To enable this functionality, set the DataServiceConfiguration. AcceptProjectionRequests property to true." }, // IncludeAssociationLinksInResponse new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.IncludeRelationshipLinksInResponse = false; }, RequestUri = "/Entities", VerifyResponse = (r) => { Assert.IsTrue(UnitTestsUtil.GetResponseAsAtomXLinq(r).Descendants(UnitTestsUtil.AtomNamespace + "entry") .Elements(UnitTestsUtil.AtomNamespace + "link").Where(l => l.Attribute("rel").Value.Contains("relatedlinks/NextTestEntity")).Count() == 0, "The payload contains relationship links even though they were turned off."); } }, new ConfigurationTestCase{ SetupService = (s) => { s.DataServiceBehavior.IncludeRelationshipLinksInResponse = true; }, RequestUri = "/Entities", VerifyResponse = (r) => { Assert.IsTrue(UnitTestsUtil.GetResponseAsAtomXLinq(r).Descendants(UnitTestsUtil.AtomNamespace + "entry") .Elements(UnitTestsUtil.AtomNamespace + "link").Where(l => l.Attribute("rel").Value.Contains("relatedlinks/NextTestEntity")).Count() > 0, "The payload doesn't contain relationship links even though they were turned on."); } }, // Max results per collection new ConfigurationTestCase{ SetupService = (s) => { s.MaxResultsPerCollection = 1; }, RequestUri = "/Entities", ExpectedExceptionMessage = "The response exceeds the maximum 1 results per collection." }, new ConfigurationTestCase{ SetupService = (s) => { s.MaxResultsPerCollection = 1; }, RequestUri = "/Entities?$filter=ID eq 1", VerifyResponse = (r) => { Assert.AreEqual(3, UnitTestsUtil.GetResponseAsAtomXLinq(r).Root.Element(UnitTestsUtil.AtomNamespace + "entry") .Element(UnitTestsUtil.AtomNamespace + "content").Element(UnitTestsUtil.MetadataNamespace + "properties") .Element(UnitTestsUtil.DataNamespace + "Strings").Elements(UnitTestsUtil.MetadataNamespace + "element").Count(), "The collection should contain 3 items."); } }, }; TestUtil.RunCombinations(testCases, (testCase) => { var metadata = CreateMetadataForXFeatureEntity(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => new DSPContext(), Writable = true, ForceVerboseErrors = true }; testCase.SetupService(service); using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore()) using (TestWebRequest request = service.CreateForInProcessWcf()) { DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true; request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); PopulateClientContextWithTestEntities(ctx); request.RequestUriString = testCase.RequestUri; request.Accept = "application/atom+xml,application/xml,text/plain"; Exception e = TestUtil.RunCatching(request.SendRequest); if (testCase.ExpectedExceptionMessage == null) { Assert.IsNull(e, "Request should have succeeded."); if (testCase.VerifyResponse != null) { testCase.VerifyResponse(request); } } else { string message = request.GetResponseStreamAsText(); Assert.IsTrue(message.Contains(testCase.ExpectedExceptionMessage), "The exception message is not the one expected."); } } }); }
private DSPServiceDefinition PreferHeader_CreateService(DSPMetadata metadata, object existingItem, object existingCollection, object existingStream, object existingNamedStream) { DSPMediaResourceStorage mrStorage = new DSPMediaResourceStorage(); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, CreateDataSource = (m) => { DSPContext context = new DSPContext(); context.GetResourceSetEntities("Items").Add(existingItem); if (existingCollection != null) { context.GetResourceSetEntities("Collection").Add(existingCollection); } if (existingStream != null) { DSPMediaResource defaultStream = mrStorage.CreateMediaResource(existingStream, null); defaultStream.ContentType = UnitTestsUtil.MimeTextPlain; defaultStream.GetWriteStream().WriteByte((int)'c'); context.GetResourceSetEntities("Streams").Add(existingStream); } if (existingNamedStream != null) { DSPMediaResource namedStream1 = mrStorage.CreateMediaResource(existingNamedStream, m.GetResourceType("NamedStream").GetNamedStreams().First(ns => ns.Name == "NamedStream1")); namedStream1.ContentType = UnitTestsUtil.MimeTextPlain; namedStream1.GetWriteStream().WriteByte((int)'d'); context.GetResourceSetEntities("NamedStreams").Add(existingNamedStream); } return context; }, Writable = true, HostInterfaceType = typeof(IDataServiceHost2), SupportMediaResource = true, SupportNamedStream = true, MediaResourceStorage = mrStorage }; return service; }
private static void RunPositiveTest(ODataFormat format, TestCase testCase) { MyDSPActionProvider actionProvider = new MyDSPActionProvider(); DSPServiceDefinition service = new DSPServiceDefinition() {Metadata = Metadata, CreateDataSource = CreateDataSource, ActionProvider = actionProvider}; service.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4; using (TestWebRequest request = service.CreateForInProcessWcf()) { request.StartService(); DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); ctx.EnableAtom = true; Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString); MakeFinalChangesToTestCase(testCase, format, actionProvider, request); if (format == ODataFormat.Json) { JsonLightTestUtil.ConfigureContextForJsonLight(ctx, null); } else { ctx.Format.UseAtom(); } QueryOperationResponse<CustomerEntity> qor = (QueryOperationResponse<CustomerEntity>)ctx.Execute<CustomerEntity>(uri); Assert.IsNotNull(qor); Assert.IsNull(qor.Error); IEnumerator<CustomerEntity> entities = qor.GetEnumerator(); int expectedDescriptorsPerEntity = 0; while (entities.MoveNext()) { CustomerEntity c = entities.Current; EntityDescriptor ed = ctx.GetEntityDescriptor(c); IEnumerable<OperationDescriptor> actualDescriptors = ed.OperationDescriptors; TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]); } } }
internal static DSPServiceDefinition SetUpNamedStreamService() { DSPMetadata metadata = new DSPMetadata("NamedStreamIDSPContainer", "NamedStreamTest"); // entity with streams ResourceType entityWithNamedStreams = metadata.AddEntityType("EntityWithNamedStreams", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityWithNamedStreams, "Name", typeof(string)); ResourceProperty streamInfo1 = new ResourceProperty("Stream1", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams.AddProperty(streamInfo1); ResourceProperty streamInfo2 = new ResourceProperty("Stream2", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams.AddProperty(streamInfo2); // entity1 with streams ResourceType entityWithNamedStreams1 = metadata.AddEntityType("EntityWithNamedStreams1", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams1, "ID", typeof(int)); metadata.AddPrimitiveProperty(entityWithNamedStreams1, "Name", typeof(string)); ResourceProperty refStreamInfo1 = new ResourceProperty("RefStream1", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams1.AddProperty(refStreamInfo1); // entity2 with streams ResourceType entityWithNamedStreams2 = metadata.AddEntityType("EntityWithNamedStreams2", null, null, false); metadata.AddKeyProperty(entityWithNamedStreams2, "ID", typeof(string)); metadata.AddPrimitiveProperty(entityWithNamedStreams2, "Name", typeof(string)); ResourceProperty collectionStreamInfo = new ResourceProperty("ColStream", ResourcePropertyKind.Stream, ResourceType.GetPrimitiveResourceType(typeof(Stream))); entityWithNamedStreams2.AddProperty(collectionStreamInfo); ResourceSet set1 = metadata.AddResourceSet("MySet1", entityWithNamedStreams); ResourceSet set2 = metadata.AddResourceSet("MySet2", entityWithNamedStreams1); ResourceSet set3 = metadata.AddResourceSet("MySet3", entityWithNamedStreams2); // add navigation property to entityWithNamedStreams metadata.AddResourceReferenceProperty(entityWithNamedStreams, "Ref", set2, entityWithNamedStreams1); metadata.AddResourceSetReferenceProperty(entityWithNamedStreams, "Collection", set3, entityWithNamedStreams2); metadata.AddResourceSetReferenceProperty(entityWithNamedStreams2, "Collection1", set2, entityWithNamedStreams1); DSPServiceDefinition service = new DSPServiceDefinition(); service.Metadata = metadata; service.MediaResourceStorage = new DSPMediaResourceStorage(); service.SupportMediaResource = true; service.SupportNamedStream = true; service.ForceVerboseErrors = true; service.PageSizeCustomizer = (config, type) => { config.SetEntitySetPageSize("MySet3", 1); }; // populate data DSPContext context = new DSPContext(); DSPResource entity1 = new DSPResource(entityWithNamedStreams); { context.GetResourceSetEntities("MySet1").Add(entity1); entity1.SetValue("ID", 1); entity1.SetValue("Name", "Foo"); DSPMediaResource namedStream1 = service.MediaResourceStorage.CreateMediaResource(entity1, streamInfo1); namedStream1.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; namedStream1.GetWriteStream().Write(data1, 0, data1.Length); DSPMediaResource namedStream2 = service.MediaResourceStorage.CreateMediaResource(entity1, streamInfo2); namedStream2.ContentType = "image/jpeg"; byte[] data2 = new byte[] { 0, 1, 2, 3, 4 }; namedStream2.GetWriteStream().Write(data2, 0, data2.Length); } DSPResource entity2 = new DSPResource(entityWithNamedStreams1); { context.GetResourceSetEntities("MySet2").Add(entity2); entity2.SetValue("ID", 3); entity2.SetValue("Name", "Bar"); DSPMediaResource refNamedStream1 = service.MediaResourceStorage.CreateMediaResource(entity2, refStreamInfo1); refNamedStream1.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; refNamedStream1.GetWriteStream().Write(data1, 0, data1.Length); // set the navigation property entity1.SetValue("Ref", entity2); } { DSPResource entity3 = new DSPResource(entityWithNamedStreams2); context.GetResourceSetEntities("MySet3").Add(entity3); entity3.SetValue("ID", "ABCDE"); entity3.SetValue("Name", "Bar"); DSPMediaResource stream = service.MediaResourceStorage.CreateMediaResource(entity3, collectionStreamInfo); stream.ContentType = "image/jpeg"; byte[] data1 = new byte[] { 0, 1, 2, 3, 4 }; stream.GetWriteStream().Write(data1, 0, data1.Length); entity3.SetValue("Collection1", new List <DSPResource>() { entity2 }); DSPResource entity4 = new DSPResource(entityWithNamedStreams2); context.GetResourceSetEntities("MySet3").Add(entity4); entity4.SetValue("ID", "XYZ"); entity4.SetValue("Name", "Foo"); DSPMediaResource stream1 = service.MediaResourceStorage.CreateMediaResource(entity3, collectionStreamInfo); stream1.ContentType = "image/jpeg"; stream1.GetWriteStream().Write(data1, 0, data1.Length); entity4.SetValue("Collection1", new List <DSPResource>() { entity2 }); entity1.SetValue("Collection", new List <DSPResource>() { entity3, entity4 }); } service.DataSource = context; return(service); }
public void Collection_Blobs() { DSPMetadata metadata = CreateMetadataForXFeatureEntity(true); DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, SupportMediaResource = true, MediaResourceStorage = new DSPMediaResourceStorage() }; byte[] clientBlob = new byte[] { 0xcc, 0x10, 0x00, 0xff }; DSPContext data = new DSPContext(); service.CreateDataSource = (m) => { return data; }; using (TestWebRequest request = service.CreateForInProcessWcf()) using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore()) { DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true; request.StartService(); XFeatureTestsMLE clientMle = new XFeatureTestsMLE() { ID = 1, Description = "Entity 1", Strings = new List<string>(new string[] { "string 1", "string 2", string.Empty }), Structs = new List<XFeatureTestsComplexType>(new XFeatureTestsComplexType[] { new XFeatureTestsComplexType() { Text = "text 1" }, new XFeatureTestsComplexType() { Text = "text 2" }}) }; DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4); ctx.EnableAtom = true; ctx.Format.UseAtom(); ctx.AddObject("Entities", clientMle); ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString()); ctx.SaveChanges(); VerifyMLEs(service, clientMle, clientBlob); // Read stream and verify stream contents using (Stream serverStream = ctx.GetReadStream(clientMle).Stream) { VerifyStream(clientBlob, serverStream); } // modify MLE and the corresponding stream clientMle.Structs.Add(new XFeatureTestsComplexType() { Text = "text 3" }); clientMle.Strings.RemoveAt(0); clientBlob[0] ^= 0xff; ctx.UpdateObject(clientMle); ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString()); ctx.SaveChanges(); VerifyMLEs(service, clientMle, clientBlob); // delete MLE ctx.DeleteObject(clientMle); ctx.SaveChanges(); Assert.IsNull((DSPResource)service.CurrentDataSource.GetResourceSetEntities("Entities"). FirstOrDefault(e => (int)(((DSPResource)e).GetValue("ID")) == (int)clientMle.GetType().GetProperty("ID").GetValue(clientMle, null)), "MLE has not been deleted."); Assert.AreEqual(0, service.MediaResourceStorage.Content.Count(), "The stream on the server has not been deleted."); }; }