コード例 #1
0
        public void Dev10Type_ClientDynamicExpand()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet_Expand);
                web.StartService();
                string baseUri = web.BaseUri;

                DataServiceContext context = new DataServiceContext(new Uri(baseUri));
                var query = context.CreateQuery <Dev10TypeDef.EntityWithDynamicNavigation>("Parents").Expand("Children");
                try
                {
                    var results = query.ToList();
                    Assert.Fail("Exception failed to be thrown.");
                }
                catch (Exception ex)
                {
                    Exception innerEx = ex;
                    while (innerEx.InnerException != null)
                    {
                        innerEx = innerEx.InnerException;
                    }

                    Assert.IsTrue(innerEx.Message.Contains("Internal Server Error. The type 'AstoriaUnitTests.Tests.UnitTestModule+Dev10TypeTests+EntityWithDynamicInterface' is not supported."), ex.InnerException.Message);
                }
            }
        }
コード例 #2
0
        public void SetDollarFormatInAddQueryOption()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(DollarFormatTestService);
                web.StartService();
                DataServiceContext ctx     = new DataServiceContext(web.ServiceRoot, ODataProtocolVersion.V4);
                List <string>      options = new List <string>()
                {
                    "atom",
                    "json",
                    "jsonlight",
                    "xml",
                };

                foreach (string option in options)
                {
                    try
                    {
                        ctx.CreateQuery <Customer>("Customers").AddQueryOption("$format", option).Execute();
                    }
                    catch (NotSupportedException e)
                    {
                        Assert.AreEqual(DataServicesClientResourceUtil.GetString("ALinq_FormatQueryOptionNotSupported"), e.Message);
                    }
                }
            }
        }
コード例 #3
0
        public void AdvertiseLargeNumberOfActionsTests()
        {
            // Test advertising large number of actions.
            var testCases = new[]
            {
                new
                {
                    RequestUri = "/Customers(1)",
                },
            };

            using (TestWebRequest request = service.CreateForInProcessWcf())
            {
                request.StartService();
                t.TestUtil.RunCombinations(testCases, (testCase) =>
                {
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    //ctx.EnableAtom = true;
                    //ctx.Format.UseAtom();
                    ctx.ResolveType = name => typeof(Customer);
                    Uri uri         = new Uri(request.ServiceRoot + testCase.RequestUri);
                    QueryOperationResponse <object> qor = (QueryOperationResponse <object>)ctx.Execute <object>(uri);
                    Assert.IsNotNull(qor);
                    IEnumerator <object> entities = qor.GetEnumerator();
                    entities.MoveNext();
                    Assert.IsNotNull(entities.Current);
                    EntityDescriptor ed = ctx.GetEntityDescriptor(entities.Current);
                    Assert.IsNotNull(ed);
                    Assert.IsNotNull(ed.OperationDescriptors);
                    Assert.AreEqual(ed.OperationDescriptors.Count(), TotalNumberOfActions, "Invalid count of total number of advertised actions.");
                });
            }
        }
コード例 #4
0
        public void FilterNavigationWithAnyAll_TypeCasts()
        {
            using (OpenWebDataServiceHelper.AcceptAnyAllRequests.Restore())
            {
                OpenWebDataServiceHelper.AcceptAnyAllRequests.Value = true;
                using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                {
                    request.DataServiceType = typeof(CustomDataContext);
                    request.StartService();

                    string[] filters = new string[]
                    {
                        "Orders/all(o: o/Customer/AstoriaUnitTests.Stubs.CustomerWithBirthday/Birthday gt 1911-04-22T15:20:45.907Z)",
                        "Orders/all(o: isof(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday') and cast(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday')/Birthday gt 1911-04-22T15:20:45.907Z)",
                        "Orders/all(o: isof(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday') and cast(o/Customer, 'AstoriaUnitTests.Stubs.CustomerWithBirthday')/Orders/any())",
                        "isof(Orders/any(),'Edm.Boolean') and ID eq 1",
                        "isof(Orders/any(o: $it/ID eq 2),'Edm.Boolean') and isof(Orders/all(o: $it/ID eq 2),'Edm.Boolean') and ID eq 1",
                    };

                    foreach (var filter in filters)
                    {
                        request.RequestUriString = "/Customers?$format=atom&$filter=" + filter;
                        Exception e = TestUtil.RunCatching(request.SendRequest);
                        Assert.IsNull(e, "Not expecting exception.");

                        var      xdoc = request.GetResponseStreamAsXDocument();
                        XElement customerWithBirthday = xdoc.Root.Elements(XName.Get("{http://www.w3.org/2005/Atom}entry")).Single();
                        XElement typeName             = customerWithBirthday.Elements(XName.Get("{http://www.w3.org/2005/Atom}category")).Single();
                        Assert.IsTrue(typeName.Attribute("term").Value.EndsWith("CustomerWithBirthday"), "typeName.Attribute(\"term\").Value.EndsWith(\"CustomerWithBirthday\")");
                    }
                }
            }
        }
コード例 #5
0
        public void OpenSpatialProperties()
        {
            // Verify that the client round tripping works with spatial open properties
            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(
                typeof(GeographyPoint),
                TestPoint.DefaultValues,
                false, // useComplexType
                true,  // useOpenType
                null);

            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcessWcf())
            {
                request.StartService();

                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                //context.EnableAtom = true;
                //context.Format.UseAtom();

                // Query the top level set
                List <TripLeg <Geography> > results = context.CreateQuery <TripLeg <Geography> >("TripLegs").ToList();
                Assert.IsTrue(results.Count == 1, "one trip leg should get materialized");
                Assert.IsTrue(context.Entities.Count == 1, "One trip leg instance should get populated in the context");

                // Update the property value
                results[0].GeographyProperty1 = GeographyFactory.Point(22, 45);
                context.UpdateObject(results[0]);
                context.SaveChanges();

                var data = roadTripServiceDefinition.CurrentDataSource.GetResourceSetEntities("TripLegs");
                Assert.AreEqual(1, data.Count, "there should one instance of TripLeg in the set");
                GeographyPoint point = (GeographyPoint)((DSPResource)data[0]).GetOpenPropertyValue("GeographyProperty1");
                Assert.AreEqual(45, point.Longitude, "Make sure longitude value is updated");
                Assert.AreEqual(22, point.Latitude, "Make sure latitude value is updated");
            }
        }
コード例 #6
0
        public void Dev10Type_ClientQueryTupleWithALinq()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet <Dev10TypeDef.EntityWithTupleProperty>);
                web.StartService();
                string baseUri = web.BaseUri;

                DataServiceContext context = new DataServiceContext(new Uri(baseUri));
                var query = from t in context.CreateQuery <Dev10TypeDef.EntityWithTupleProperty>("Entities")
                            where t.ComplexTuple.Item1 == "value 1"
                            select t;
                try
                {
                    string queryUri = query.ToString();
                    Assert.Fail("Client ALINQ with Tuple failed to throw");
                }
                catch (Exception ex)
                {
                    Exception innerEx = ex;
                    while (innerEx.InnerException != null)
                    {
                        innerEx = innerEx.InnerException;
                    }
                    Assert.AreEqual("The type 'System.Tuple`2[System.String,System.String]' is not supported by the client library.", innerEx.Message);
                }
            }
        }
コード例 #7
0
        public void HttpContextServiceHostRequestNameTest()
        {
            CombinatorialEngine engine = CombinatorialEngine.FromDimensions(
                new Dimension("WebServerLocation", new WebServerLocation[] { WebServerLocation.InProcessWcf }),
                new Dimension("LocalHostName", new string[] { "127.0.0.1" }));

            TestUtil.RunCombinatorialEngineFail(engine, delegate(Hashtable values)
            {
                WebServerLocation location = (WebServerLocation)values["WebServerLocation"];
                string hostName            = (string)values["LocalHostName"];
                using (TestWebRequest request = TestWebRequest.CreateForLocation(location))
                {
                    request.DataServiceType  = typeof(CustomDataContext);
                    request.RequestUriString = "/Customers(1)?$format=atom";
                    request.StartService();

                    UriBuilder builder = new UriBuilder(request.FullRequestUriString);
                    builder.Host       = hostName;
                    WebClient client   = new WebClient();
                    string response    = client.DownloadString(builder.Uri);

                    response             = response.Substring(response.IndexOf('<'));
                    XmlDocument document = new XmlDocument(TestUtil.TestNameTable);
                    document.LoadXml(response);
                    string baseUri = UnitTestsUtil.GetBaseUri(document.DocumentElement);
                    TestUtil.AssertContains(baseUri, hostName);
                }
            });
        }
コード例 #8
0
        public void TestInitialize()
        {
            DSPServiceDefinition service = NamedStreamService.SetUpNamedStreamService();

            request = service.CreateForInProcessWcf();
            request.StartService();
        }
コード例 #9
0
        private static void RunEndToEndSmokeTestWithClient(Action <DataServiceContext> customize = null)
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
            {
                request.DataServiceType = typeof(KeyAsSegmentService);

                request.StartService();

                DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4)
                {
                    UrlConventions = DataServiceUrlConventions.KeyAsSegment
                };
                if (customize != null)
                {
                    customize(ctx);
                }

                var customer   = ctx.CreateQuery <Customer>("Customers").Where(c => c.ID == 0).Single();
                var descriptor = ctx.GetEntityDescriptor(customer);

                var baseUri = request.ServiceRoot.AbsoluteUri;
                Assert.AreEqual(baseUri + "/Customers/0", descriptor.Identity.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0", descriptor.EditLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/BestFriend/$ref", descriptor.LinkInfos[0].AssociationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/BestFriend", descriptor.LinkInfos[0].NavigationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/Orders/$ref", descriptor.LinkInfos[1].AssociationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/Orders", descriptor.LinkInfos[1].NavigationLink.OriginalString);
            }
        }
コード例 #10
0
        public void TestCollectionOfSpatialTypes()
        {
            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(typeof(GeographyPoint), TestPoint.DefaultValues, false, false,
                                                                                                  (m) =>
            {
                var resourceType  = m.GetResourceType("TripLeg");
                var primitiveType = Microsoft.OData.Service.Providers.ResourceType.GetPrimitiveResourceType(typeof(GeographyPoint));
                m.AddCollectionProperty(resourceType, "PointsOfInterest", primitiveType);
            },
                                                                                                  (name, values) =>
            {
                if (name == "TripLeg")
                {
                    var list = values.Select(kvp => kvp.Value).ToList();
                    values.Add(new KeyValuePair <string, object>("PointsOfInterest", list));
                }
            });

            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcessWcf())
            {
                request.StartService();

                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                var tripLegs = context.CreateQuery <TripLegWithCollection <GeographyPoint> >("TripLegs").Where(t => t.ID == SpatialTestUtil.DefaultId).ToList();
                var tripLeg  = tripLegs.Single();
                Assert.AreEqual(2, tripLeg.PointsOfInterest.Count(), "didn't materialize all the elements");
            }
        }
コード例 #11
0
        public void NonNullableComplexPropertyTest()
        {
            test.TestUtil.RunCombinations(
                new DSPUnitTestServiceDefinition[] { service },
                new string[] { UnitTestsUtil.AtomFormat },
                ServiceVersion.ValidVersions, // requestDSV
                ServiceVersion.ValidVersions, // requestMDSV
                ServiceVersion.ValidVersions, // maxProtocolVersion
                (localService, format, requestDSV, requestMDSV, maxProtocolVersion) =>
            {
                if (maxProtocolVersion == null)
                {
                    return;
                }

                localService.DataServiceBehavior.MaxProtocolVersion = maxProtocolVersion.ToProtocolVersion();
                using (TestWebRequest request = localService.CreateForInProcess())
                {
                    if (requestDSV != null && maxProtocolVersion.ToProtocolVersion() < requestDSV.ToProtocolVersion())
                    {
                        return;
                    }

                    request.StartService();
                    request.HttpMethod       = "POST";
                    request.RequestUriString = "/People";
                    request.Accept           = format;
                    if (requestDSV != null)
                    {
                        request.RequestVersion = requestDSV.ToString();
                    }
                    if (requestMDSV != null)
                    {
                        request.RequestMaxVersion = requestMDSV.ToString();
                    }

                    request.RequestContentType = format;
                    request.SetRequestStreamAsText(@"<entry xml:base='http://host/' xmlns:d='http://docs.oasis-open.org/odata/ns/data' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns='http://www.w3.org/2005/Atom'>
    <category term='#AstoriaUnitTests.Tests.PeopleType' scheme='http://docs.oasis-open.org/odata/ns/scheme' />
    <content type='application/xml'>
      <m:properties>
        <d:ID m:type='Edm.Int32'>1</d:ID>
        <d:Name>bar</d:Name>
        <d:Body></d:Body>
        <d:Age>6</d:Age>
        <d:Office m:type='#AstoriaUnitTests.Tests.OfficeType' m:null='true'/>
      </m:properties>
    </content>
  </entry>");
                    request.HttpMethod = "POST";
                    var exception      = test.TestUtil.RunCatching(request.SendRequest);
                    Assert.IsNotNull(exception, "Exception is always expected.");
                    Assert.IsNotNull(exception.InnerException, "InnerException is always expected.");

                    // For v1 and v2, provider should throw.
                    Assert.AreEqual("EntityFramework", exception.InnerException.Source, "Source expected: EntityFramework, actual: " + exception.InnerException.Source);
                    Assert.AreEqual(500, request.ResponseStatusCode, "Status code expected: 500" + ", actual: " + request.ResponseStatusCode);
                }
            });
        }
コード例 #12
0
        public void CallbackSuccessQueryKeywordTest()
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
            {
                request.DataServiceType = typeof(CallbackQueryOptionTestService);
                request.StartService();

                request.RequestUriString = "/ReturnNullServiceOperation?$callback=foo";
                request.SendRequest();
                Assert.AreEqual(204, request.ResponseStatusCode);

                request.RequestUriString = "/Customers(1)/ID/$value?$callback=foo";
                request.SendRequest();
                Assert.AreEqual(200, request.ResponseStatusCode);
                Assert.AreEqual("foo(1)", request.GetResponseStreamAsText());
                Assert.AreEqual("text/javascript;charset=utf-8", request.ResponseHeaders["content-type"]);

                request.RequestUriString = "/Customers/$count?$callback=foo";
                request.SendRequest();
                Assert.AreEqual(200, request.ResponseStatusCode);
                var actualText = request.GetResponseStreamAsText();
                Assert.IsTrue(actualText.StartsWith("foo("));
                Assert.IsTrue(actualText.EndsWith(")"));
                Assert.AreEqual("text/javascript;charset=utf-8", request.ResponseHeaders["content-type"]);
            }
        }
コード例 #13
0
        public void QueryWithBothMinimalAndFullMetadataShouldNotCauseDuplicateIdentities()
        {
            // Repro for: EntityDescriptor identity/links key order changes for json DataServiceContext
            using (TestUtil.MetadataCacheCleaner())
                using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                {
                    // using the row-based context because it intentionally puts OrderDetail's key properties in non-alphabetical order in the OM.
                    request.DataServiceType = typeof(CustomRowBasedContext);
                    request.StartService();

                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);

                    JsonLightTestUtil.ConfigureContextForJsonLight(ctx);

                    ConfigureContextForSendingRequest2Verification(ctx);

                    var firstOrderDetail          = ctx.CreateQuery <OrderDetail>("OrderDetails").First();
                    var firstOrderDetailProjected = ctx.CreateQuery <OrderDetail>("OrderDetails").Select(od => new OrderDetail {
                        Quantity = od.Quantity
                    }).First();

                    Assert.IsNotNull(firstOrderDetail);
                    Assert.IsNotNull(firstOrderDetailProjected);
                    Assert.AreEqual(1, ctx.Entities.Count);
                }
        }
コード例 #14
0
ファイル: Dev10EF4FKTests.cs プロジェクト: zdzislaw/odata.net
 public static void ClassInitialize(TestContext context)
 {
     changeScope         = EFFK.CustomObjectContextPOCOProxy.CreateChangeScope();
     web                 = TestWebRequest.CreateForInProcessWcf();
     web.DataServiceType = typeof(EFFK.CustomObjectContextPOCOProxy);
     OpenWebDataServiceHelper.ForceVerboseErrors = true;
     web.StartService();
 }
コード例 #15
0
        [Ignore] // Remove Atom
        // [TestMethod]
        public void ResponseHeadersAndStreamExceptionTest()
        {
            // Execute a query using a variety of methods (including sync, async, batch) and verify the response headers and payloads
            using (PlaybackService.OverridingPlayback.Restore())
                using (PlaybackService.ProcessRequestOverride.Restore())
                    using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                    {
                        request.ServiceType = typeof(PlaybackService);
                        request.StartService();

                        TestUtil.RunCombinations(((IEnumerable <QueryMode>)Enum.GetValues(typeof(QueryMode))), (queryMode) =>
                        {
                            bool isBatchQuery = queryMode == QueryMode.BatchAsyncExecute || queryMode == QueryMode.BatchAsyncExecuteWithCallback || queryMode == QueryMode.BatchExecute;
                            PlaybackService.ProcessRequestOverride.Value = (r) => { throw new InvalidOperationException("ResponseHeadersAndStreamExceptionTest -- Bad Request."); };

                            DataServiceContext context            = new DataServiceContext(new Uri(request.BaseUri));
                            HttpTestHookConsumer testHookConsumer = new HttpTestHookConsumer(context, false);

                            DataServiceQuery <Customer> query = context.CreateQuery <Customer>("Customers");
                            Exception ex = null;
                            try
                            {
                                foreach (var o in DataServiceContextTestUtil.ExecuteQuery(context, query, queryMode))
                                {
                                }
                            }
                            catch (Exception e)
                            {
                                ex = e;
                            }

                            // Verify response headers
                            Assert.AreEqual(1, testHookConsumer.ResponseHeaders.Count, "Wrong number of response headers being tracked by the test hook.");
                            Dictionary <string, string> actualResponseHeaders = testHookConsumer.ResponseHeaders[0];
                            Assert.AreEqual("InternalServerError", actualResponseHeaders["__HttpStatusCode"]);

                            // Verify response stream
                            Assert.AreEqual(1, testHookConsumer.ResponseWrappingStreams.Count, "Unexpected number of response streams tracked by the test hook.");
                            string actualResponsePayload = testHookConsumer.ResponseWrappingStreams[0].GetLoggingStreamAsString();
                            if (queryMode == QueryMode.BatchExecute)
                            {
                                Assert.AreEqual("", actualResponsePayload, "In batch the client calls the hook to get the stream but never reads from it.");
                            }
                            else
                            {
                                TestUtil.AssertContains(actualResponsePayload, "System.InvalidOperationException: ResponseHeadersAndStreamExceptionTest -- Bad Request.");
                            }

                            // Sanity check on the count of request streams, but not verifying them here. That functionality is tested more fully in another test method.
                            int expectedRequestStreamsCount = isBatchQuery ? 1 : 0;
                            Assert.AreEqual(expectedRequestStreamsCount, testHookConsumer.RequestWrappingStreams.Count, "Unexpected number of request streams.");
                        });
                    }
        }
コード例 #16
0
        private static void RunNegativeActionTestWithAtom(TestCase testCase)
        {
            // These tests are specific to Atom and don't apply to JSON Light.
            // Any JSON Light negative cases are covered by ODL reader tests. See ODL tests OperationReaderJsonLightTests and ODataJsonLightDeserializerTests.
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                using (PlaybackService.ProcessRequestOverride.Restore())
                {
                    request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService);
                    request.StartService();

                    PlaybackService.ProcessRequestOverride.Value = (req) =>
                    {
                        // These tests intentionally don't set the base URI of the context, so we need to also remove the xml:base attribute that is automatically
                        // generated by the PayloadGenerator. Otherwise another parsing error will occur before we hit the actual errors we are trying to validate.
                        string payload          = PayloadGenerator.Generate(testCase.ResponsePayloadBuilder, ODataFormat.Atom);
                        string xmlBaseAttribute = @"xml:base=""/""";
                        payload = payload.Remove(payload.IndexOf(xmlBaseAttribute), xmlBaseAttribute.Length);

                        req.SetResponseStreamAsText(payload);
                        req.ResponseHeaders.Add("Content-Type", "application/atom+xml");
                        req.SetResponseStatusCode(200);
                        return(req);
                    };

                    Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
                    DataServiceContext ctx = new DataServiceContext(null, ODataProtocolVersion.V4);
                    ctx.EnableAtom = true;

                    QueryOperationResponse <CustomerEntity> qor = (QueryOperationResponse <CustomerEntity>)ctx.Execute <CustomerEntity>(uri);
                    Assert.IsNotNull(qor);
                    Assert.IsNull(qor.Error);

                    IEnumerator <CustomerEntity> entities = qor.GetEnumerator();

                    Exception exception = AstoriaTest.TestUtil.RunCatching(delegate()
                    {
                        while (entities.MoveNext())
                        {
                            CustomerEntity c    = entities.Current;
                            EntityDescriptor ed = ctx.GetEntityDescriptor(c);
                            IEnumerable <OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
                        }
                    });

                    Assert.IsNotNull(exception);
                    Assert.AreEqual(testCase.ExpectedErrorMessage, exception.Message);
                }
        }
コード例 #17
0
        public void AllowRedefiningConcurrencyTokenOnDerivedType()
        {
            var metadataProvider = new DSPMetadata("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);

            DSPResource baseTypeInstance = new DSPResource(entityType);

            baseTypeInstance.SetValue("ID", 1);
            baseTypeInstance.SetValue("LastUpdatedAuthor", "Phani");

            DSPResource derivedTypeInstance = new DSPResource(derivedType);

            derivedTypeInstance.SetValue("ID", 1);
            derivedTypeInstance.SetValue("LastModifiedAuthor", "Raj");

            DSPContext dataContext = new DSPContext();
            var        entities    = dataContext.GetResourceSetEntities("Customers");

            entities.AddRange(new object[] { baseTypeInstance, derivedTypeInstance });

            var service = new DSPUnitTestServiceDefinition(metadataProvider, DSPDataProviderKind.Reflection, dataContext);

            using (TestWebRequest request = service.CreateForInProcess())
            {
                try
                {
                    request.StartService();
                    request.RequestUriString = "/$metadata";
                    request.SendRequestAndCheckResponse();
                }
                finally
                {
                    request.StopService();
                }
            }
        }
コード例 #18
0
        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++]);
                }
            }
        }
コード例 #19
0
        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.");
                }
            }
        }
コード例 #20
0
        public void AnyAllVersioningTests()
        {
            using (OpenWebDataServiceHelper.AcceptAnyAllRequests.Restore())
            {
                OpenWebDataServiceHelper.ForceVerboseErrors = true;
                TestUtil.RunCombinations(UnitTestsUtil.BooleanValues, (acceptAnyAllRequests) =>
                {
                    OpenWebDataServiceHelper.AcceptAnyAllRequests.Value = acceptAnyAllRequests;
                    using (TestUtil.MetadataCacheCleaner())
                        using (TestWebRequest request = TestWebRequest.CreateForInProcess())
                        {
                            request.DataServiceType = typeof(CustomDataContext);

                            request.StartService();
                            request.RequestUriString = "/Customers?$filter=Orders/any()";
                            TestUtil.RunCombinations(ServiceVersion.ValidVersions, (requestVersion) =>
                            {
                                if (requestVersion != null)
                                {
                                    request.RequestVersion = requestVersion.ToString();
                                }
                                else
                                {
                                    request.RequestVersion = null;
                                }

                                Exception e = TestUtil.RunCatching(request.SendRequest);

                                if (!acceptAnyAllRequests)
                                {
                                    Assert.IsNotNull(e);
                                    Assert.IsInstanceOfType(e.InnerException, typeof(DataServiceException));
                                    Assert.AreEqual(400, ((DataServiceException)(e.InnerException)).StatusCode);
                                    Assert.AreEqual(DataServicesResourceUtil.GetString("RequestQueryParser_DisallowMemberAccessForResourceSetReference", "any", 7), e.InnerException.Message);
                                }
                                else
                                {
                                    Assert.IsNull(e);
                                }
                            });
                        }
                });
            }
        }
コード例 #21
0
        private void QueryDev10TypeService <T>(bool expectException, string exceptionMessage)
            where T : new()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet <T>);
                web.StartService();
                string baseUri = web.BaseUri;

                DataServiceContext context = new DataServiceContext(new Uri(baseUri));

                try
                {
                    var query  = context.CreateQuery <T>("Entities");
                    var result = query.Execute();
                    Assert.IsFalse(expectException);
                    Assert.AreEqual(result.Count(), 3);
                }
                catch (Exception ex)
                {
                    // is exception expected?
                    Assert.IsTrue(expectException, "exception was not expected");
                    if (!String.IsNullOrEmpty(exceptionMessage))
                    {
                        Exception innerEx = ex;
                        while (innerEx.InnerException != null)
                        {
                            innerEx = innerEx.InnerException;
                        }

                        if (exceptionMessage.StartsWith("Contains:"))
                        {
                            exceptionMessage = exceptionMessage.Substring(9);
                            Assert.IsTrue(innerEx.Message.Contains(exceptionMessage), innerEx.Message);
                        }
                        else
                        {
                            Assert.AreEqual(ex.Message, exceptionMessage);
                        }
                    }
                }
            }
        }
コード例 #22
0
ファイル: SpatialTests.cs プロジェクト: marismore/odata.net
        private static void TestSpatialMetadata(DSPDataProviderKind providerKind)
        {
            DSPMetadata metadata = new DSPMetadata("SpatialMetadata", "AstoriaUnitTests.Tests");

            // Entity with all types of geography properties
            KeyValuePair <string, Type>[] geographyProperties = new KeyValuePair <string, Type>[] {
                new KeyValuePair <string, Type>("GeographyProperty", typeof(Geography)),
                new KeyValuePair <string, Type>("PointProperty", typeof(GeographyPoint)),
                new KeyValuePair <string, Type>("LineStringProperty", typeof(GeographyLineString)),
            };
            string entityTypeName = "AllGeographyTypes";

            SpatialTestUtil.AddEntityType(metadata, entityTypeName, geographyProperties, useComplexType: false, useOpenTypes: false);
            metadata.SetReadOnly();

            var service = new DSPUnitTestServiceDefinition(metadata, providerKind, new DSPContext());

            using (TestWebRequest request = service.CreateForInProcess())
            {
                request.StartService();

                request.HttpMethod = "GET";
                XDocument response = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/$metadata");

                XElement   schemaElement = response.Root.Element(UnitTestsUtil.EdmxNamespace + "DataServices").Elements().Single(e => e.Name.LocalName == "Schema");
                XNamespace edmNs         = schemaElement.Name.Namespace;
                XElement   entityElement = schemaElement.Elements(edmNs + "EntityType").Single(e => (string)e.Attribute("Name") == entityTypeName);

                foreach (KeyValuePair <string, Type> property in geographyProperties)
                {
                    XElement propertyElement = entityElement.Elements(edmNs + "Property").Single(e => (string)e.Attribute("Name") == property.Key);

                    // EF provider currently represents all types as Edm.Geography in metadata (property is DbGeography on the entity), otherwise it should reflect the actual type
                    string expectedEdmTypeName = providerKind == DSPDataProviderKind.EF ? "Edm.Geography" : GetExpectedEdmTypeName(property.Value);

                    Assert.AreEqual(expectedEdmTypeName, propertyElement.Attribute("Type").Value, "Wrong property type for property {0},", property.Key);

                    XAttribute attribute = propertyElement.Attributes().Where(a => a.Name == "SRID").Single();
                    Assert.AreEqual("Variable", attribute.Value);
                }
            }
        }
コード例 #23
0
        public void SetDollarFormatInBuildingRequest()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(DollarFormatTestService);
                web.StartService();

                DataServiceContext ctx     = new DataServiceContext(web.ServiceRoot, ODataProtocolVersion.V4);
                List <string>      options = new List <string>()
                {
                    // "atom",  It will be enabled by finishing
                    // "json",  enable the json case by involving proper EDM model in DataServiceContext.
                    "xml",
                };
                string option = string.Empty;
                ctx.BuildingRequest += (sender, arg) => arg.RequestUri = new Uri(arg.RequestUri.AbsoluteUri + "?$format=" + option);

                foreach (string s in options)
                {
                    try
                    {
                        option = s;
                        ctx.Execute <Customer>(new Uri(web.ServiceRoot + "/Customers"));
                        ctx.CreateQuery <Customer>("Customers");
                        //  Assert.IsTrue(option == "json");
                    }
                    catch (DataServiceQueryException e)
                    {
                        if (option == "xml")
                        {
                            TestUtil.AssertContains(e.InnerException.Message, "A supported MIME type could not be found that matches the acceptable MIME types for the request.");
                            Assert.AreEqual(415, e.Response.StatusCode);
                        }
                        else
                        {
                            // Assert.AreEqual("atom", option);
                            // Assert.AreEqual(DataServicesClientResourceUtil.GetString("DataServiceClientFormat_ValidServiceModelRequiredForAtom"), e.InnerException.Message);
                        }
                    }
                }
            }
        }
コード例 #24
0
        private static void TestFilterError(string filter, string expectedMessage)
        {
            using (OpenWebDataServiceHelper.AcceptAnyAllRequests.Restore())
            {
                OpenWebDataServiceHelper.ForceVerboseErrors         = true;
                OpenWebDataServiceHelper.AcceptAnyAllRequests.Value = true;
                using (TestWebRequest request = TestWebRequest.CreateForInProcess())
                {
                    request.DataServiceType = typeof(CustomDataContext);
                    request.StartService();

                    request.RequestUriString = "/Customers?$filter=" + filter;
                    Exception e = TestUtil.RunCatching(request.SendRequest);
                    Assert.IsNotNull(e, "Expecting exception.");
                    Assert.IsNotNull(e.InnerException, "Expecting exception.");

                    Assert.AreEqual(expectedMessage, e.InnerException.Message, "testCase.message == e.InnerException.Message");
                }
            }
        }
コード例 #25
0
ファイル: SpatialTests.cs プロジェクト: marismore/odata.net
        public void SerializeGeodeticPropertiesInResource()
        {
            var testCases = new[]
            {
                new
                {
                    GeographyType = typeof(GeographyPoint),
                    DefaultValues = TestPoint.DefaultValues
                },
                new
                {
                    GeographyType = typeof(GeographyLineString),
                    DefaultValues = TestLineString.DefaultValues
                },
            };

            var responseFromats = new string[] { UnitTestsUtil.AtomFormat };

            TestUtil.RunCombinations(testCases, responseFromats, (testCase, responseFormat) =>
            {
                GeographyPropertyValues defaultValues = testCase.DefaultValues;

                DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(testCase.GeographyType, defaultValues);
                using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
                {
                    request.StartService();
                    request.Accept = responseFormat;

                    ResourceVerification verification = GetResourceVerification(responseFormat, SpatialTestUtil.DefaultId, defaultValues, request);

                    // Geography property followed by another geography property
                    verification.GetAndVerifyTripLeg();

                    // Geography property followed by another non-geography property
                    verification.GetAndVerifyAmusementPark();

                    // Geography property at the end of the entry
                    verification.GetAndVerifyRestStop();
                }
            });
        }
コード例 #26
0
        private void PostToDev10TypeService <T>(bool exceptionExpected, string exceptionMessage)
            where T : new()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(Dev10TypeDef.Dev10TypeEntitySet <T>);
                web.StartService();
                string baseUri = web.BaseUri;

                DataServiceContext context = new DataServiceContext(new Uri(baseUri));
                try
                {
                    context.AddObject("Entities", new T());
                    context.SaveChanges();
                    Assert.IsFalse(exceptionExpected);
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(exceptionExpected);

                    if (exceptionMessage != string.Empty)
                    {
                        Exception innerEx = ex;
                        while (innerEx.InnerException != null)
                        {
                            innerEx = innerEx.InnerException;
                        }

                        if (exceptionMessage.StartsWith("Contains:"))
                        {
                            exceptionMessage = exceptionMessage.Substring(9);
                            Assert.IsTrue(innerEx.Message.Contains(exceptionMessage));
                        }
                        else
                        {
                            Assert.AreEqual(ex.Message, exceptionMessage);
                        }
                    }
                }
            }
        }
コード例 #27
0
        private static void TestSupportedLinqQueries(Func <DataServiceContext, LinqTestCase[]> getTests)
        {
            PlaybackServiceDefinition playbackService = new PlaybackServiceDefinition();

            using (TestWebRequest request = playbackService.CreateForInProcessWcf())
            {
                request.StartService();

                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                //context.EnableAtom = true;
                context.MergeOption = MergeOption.NoTracking;

                var tests = getTests(context);

                for (int i = 0; i < tests.Length; i++)
                {
                    playbackService.OverridingPlayback = tests[i].ServerPayload;
                    VerifyURI(context, tests[i].Query, tests[i].ExpectedUri, tests[i].ExpectedResults, tests[i].ExpectKeyInUri);
                }
            }
        }
コード例 #28
0
        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");
            }
        }
コード例 #29
0
        private static void RunClientIntegrationTestWithMergeOption(Action <DataServiceContext> executeAndVerify, MergeOption mergeOption, Action <DataServiceConfiguration, Type> pageSizeCustomizer)
        {
            using (TestUtil.MetadataCacheCleaner())
                using (OpenWebDataServiceHelper.PageSizeCustomizer.Restore())
                    using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                    {
                        OpenWebDataServiceHelper.PageSizeCustomizer.Value = pageSizeCustomizer;

                        request.DataServiceType    = typeof(CustomDataContext);
                        request.ForceVerboseErrors = true;
                        request.StartService();

                        DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        ctx.MergeOption = mergeOption;

                        JsonLightTestUtil.ConfigureContextForJsonLight(ctx);

                        ConfigureContextForSendingRequest2Verification(ctx);

                        executeAndVerify(ctx);
                    }
        }
コード例 #30
0
        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);
            }
        }
コード例 #31
0
 public void TestInitialize()
 {
      DSPServiceDefinition service = NamedStreamService.SetUpNamedStreamService();
      request = service.CreateForInProcessWcf();
      request.StartService();
 }
コード例 #32
0
ファイル: Dev10EF4FKTests.cs プロジェクト: larsenjo/odata.net
 public static void ClassInitialize(TestContext context)
 {
     changeScope = EFFK.CustomObjectContextPOCOProxy.CreateChangeScope();
     web = TestWebRequest.CreateForInProcessWcf();
     web.DataServiceType = typeof(EFFK.CustomObjectContextPOCOProxy);
     OpenWebDataServiceHelper.ForceVerboseErrors = true;
     web.StartService();
 }