Exemplo n.º 1
0
 /// <summary>Constructor.</summary>
 /// <param name="dataContext">The data context to apply the changes to.</param>
 /// <param name="metadata">The metadata describing the types to work with.</param>
 public DSPUpdateProvider(DSPContext dataContext, DSPMetadata metadata)
 {
     this.dataContext            = dataContext;
     this.metadata               = metadata;
     this.pendingChanges         = new List <Action>();
     this.propertyValuesModified = new Dictionary <object, Dictionary <string, object> >();
 }
        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;
        }
Exemplo n.º 3
0
 /// <summary>Constructor.</summary>
 /// <param name="dataContext">The data context to apply the changes to.</param>
 /// <param name="metadata">The metadata describing the types to work with.</param>
 public DSPUpdateProvider(DSPContext dataContext, DSPMetadata metadata)
 {
     this.dataContext = dataContext;
     this.metadata = metadata;
     this.pendingChanges = new List<Action>();
     this.propertyValuesModified = new Dictionary<object, Dictionary<string, object>>();
 }
        private static void PopulateContextWithDefaultData(Type contextType, DSPContext dspContext, DSPDataProviderKind providerKind)
        {
            Assert.IsTrue(providerKind == DSPDataProviderKind.EF || providerKind == DSPDataProviderKind.Reflection, "expecting only EF and reflection provider");
            Dictionary<DSPResource, object> entitiesAlreadyAdded = new Dictionary<DSPResource, object>();

            // push all the data to the context.
            // create a new instance of the context
            var context = Activator.CreateInstance(contextType);

            // Clear the database if the context is EF context
            if (providerKind == DSPDataProviderKind.EF)
            {
                if (((DbContext)context).Database.Exists())
                {
                    ((DbContext)context).Database.Delete();
                }
            }

            foreach (var set in dspContext.EntitySets)
            {
                string setName = set.Key;
                List<object> entities = set.Value;

                foreach (var entity in entities)
                {
                    DSPResource resource = (DSPResource)entity;
                    if (!entitiesAlreadyAdded.ContainsKey(resource))
                    {
                        Type entityType = contextType.Assembly.GetType(resource.ResourceType.FullName);
                        var entityInstance = Activator.CreateInstance(entityType);
                        if (providerKind == DSPDataProviderKind.EF)
                        {
                            ((DbContext)context).Set(entityType).Add(entityInstance);
                        }
                        else
                        {
                            IList list = (IList)context.GetType().GetField("_" + setName, BindingFlags.Public | BindingFlags.Static).GetValue(context);
                            list.Add(entityInstance);
                        }

                        entitiesAlreadyAdded.Add(resource, entityInstance);
                        PopulateProperties(context, entityInstance, resource, entitiesAlreadyAdded);
                    }
                    else if (providerKind == DSPDataProviderKind.Reflection)
                    {
                        // Since in reflection provider, adding to the collection does not add to the top level set, adding it explicitly now.
                        IList list = (IList)context.GetType().GetField("_" + setName, BindingFlags.Public | BindingFlags.Static).GetValue(context);
                        list.Add(entitiesAlreadyAdded[resource]);
                    }
                }
            }

            if (providerKind == DSPDataProviderKind.EF)
            {
                ((DbContext)context).SaveChanges();
            }
        }
 public IDisposable CreateChangeScope(DSPContext defaultData)
 {
     if (this.ProviderKind == DSPDataProviderKind.EF)
     {
         return new TransactionScope();
     }
     else
     {
         return new ChangeScope(this, defaultData);
     }
 }
        /// <summary>
        /// Creates a datasource from the given metadata.
        /// </summary>
        /// <param name="metadata">The metadata against which the datasource is created.</param>
        /// <returns>DSPContext representing the data source.</returns>
        private static DSPContext CreateDataSource(DSPMetadata metadata)
        {
            DSPContext context = new DSPContext();
            ResourceType customerType = metadata.GetResourceType("CustomerEntity");
            DSPResource entity1 = new DSPResource(customerType);
            entity1.SetValue("ID", 1);
            entity1.SetValue("Name", "Vineet");
            
            DSPResource entity2 = new DSPResource(customerType);
            entity2.SetValue("ID", 2);
            entity2.SetValue("Name", "Jimmy");

            context.GetResourceSetEntities("CustomerEntities").Add(entity1);
            context.GetResourceSetEntities("CustomerEntities").Add(entity2);
            return context;
        }
Exemplo n.º 7
0
        private static DSPContext GetDefaultData(DSPMetadata metadata)
        {
            var peopleType = metadata.GetResourceType("PeopleType");
            var employeeType = metadata.GetResourceType("EmployeeType");
            var managerType = metadata.GetResourceType("ManagerType");
            var customerType = metadata.GetResourceType("CustomerType");
            var employeeAddressType = metadata.GetResourceType("EmployeeAddressType");
            var customerAddressType = metadata.GetResourceType("CustomerAddressType");

            #region Default Data for the Model
            var context = new DSPContext();

            DSPResource people1 = new DSPResource(peopleType);
            people1.SetValue("ID", 1);
            people1.SetValue("Name", "Foo");

            DSPResource andyAddress = new DSPResource(employeeAddressType);
            andyAddress.SetValue("ID", 1);
            andyAddress.SetValue("Street", "Andy's address");
            andyAddress.SetValue("City", "Sammamish");
            andyAddress.SetValue("State", "WA");

            DSPResource andy = new DSPResource(managerType);
            andy.SetValue("ID", 2);
            andy.SetValue("Name", "Andy");
            andy.SetValue("FullName", "Andy Conrad");
            andy.SetValue("Address", andyAddress);

            DSPResource pratikAddress = new DSPResource(employeeAddressType);
            pratikAddress.SetValue("ID", 2);
            pratikAddress.SetValue("Street", "pratik's address");
            pratikAddress.SetValue("City", "Bothell");
            pratikAddress.SetValue("State", "WA");

            DSPResource pratik = new DSPResource(employeeType);
            pratik.SetValue("ID", 3);
            pratik.SetValue("Name", "Pratik");
            pratik.SetValue("FullName", "Pratik Patel");
            pratik.SetValue("Manager", andy);
            pratik.SetValue("Address", pratikAddress);

            DSPResource jimmyAddress = new DSPResource(employeeAddressType);
            jimmyAddress.SetValue("ID", 3);
            jimmyAddress.SetValue("Street", "jimmy's address");
            jimmyAddress.SetValue("City", "somewhere in seattle");
            jimmyAddress.SetValue("State", "WA");

            DSPResource jimmy = new DSPResource(employeeType);
            jimmy.SetValue("ID", 4);
            jimmy.SetValue("Name", "Jimmy");
            jimmy.SetValue("FullName", "Jian Li");
            jimmy.SetValue("Manager", andy);
            jimmy.SetValue("Address", jimmyAddress);

            andy.SetValue("DirectReports", new List<DSPResource>() { pratik, jimmy });

            DSPResource shyamAddress = new DSPResource(employeeAddressType);
            shyamAddress.SetValue("ID", 4);
            shyamAddress.SetValue("Street", "shyam's address");
            shyamAddress.SetValue("City", "university district");
            shyamAddress.SetValue("State", "WA");

            DSPResource shyam = new DSPResource(managerType);
            shyam.SetValue("ID", 5);
            shyam.SetValue("Name", "Shyam");
            shyam.SetValue("FullName", "Shyam Pather");
            shyam.SetValue("Address", shyamAddress);

            DSPResource marceloAddress = new DSPResource(employeeAddressType);
            marceloAddress.SetValue("ID", 5);
            marceloAddress.SetValue("Street", "marcelo's address");
            marceloAddress.SetValue("City", "kirkland");
            marceloAddress.SetValue("State", "WA");

            DSPResource marcelo = new DSPResource(employeeType);
            marcelo.SetValue("ID", 6);
            marcelo.SetValue("Name", "Marcelo");
            marcelo.SetValue("FullName", "Marcelo Lopez Ruiz");
            marcelo.SetValue("Manager", shyam);
            marcelo.SetValue("Address", marceloAddress);

            andy.SetValue("Manager", shyam);

            shyam.SetValue("DirectReports", new List<DSPResource>() { andy, marcelo });

            DSPResource customer1Address = new DSPResource(customerAddressType);
            customer1Address.SetValue("ID", 6);
            customer1Address.SetValue("Street", "customer1's address");
            customer1Address.SetValue("City", "somewhere");
            customer1Address.SetValue("State", "WA");

            var customer1 = new DSPResource(customerType);
            customer1.SetValue("ID", 7);
            customer1.SetValue("FullName", "Customer FullName");
            customer1.SetValue("Address", customer1Address);

            var people = context.GetResourceSetEntities("People");
            people.AddRange(new object[] { people1, andy, pratik, jimmy, shyam, marcelo, customer1 });

            var addresses = context.GetResourceSetEntities("Addresses");
            addresses.AddRange(new object[] { andyAddress, pratikAddress, jimmyAddress, shyamAddress, marceloAddress, customer1Address });

            #endregion Default Data for the Model

            return context;
        }
Exemplo n.º 8
0
        private DSPUnitTestServiceDefinition CreateTestService(bool openType = false)
        {
            DSPMetadata metadata = new DSPMetadata("SpatialQueryTests", "AstoriaUnitTests.Tests");
            var entityType = metadata.AddEntityType("SpatialEntity", null, null, false);
            metadata.AddKeyProperty(entityType, "ID", typeof(int));
            entityType.IsOpenType = openType;

            if (!openType)
            {
                metadata.AddPrimitiveProperty(entityType, "Geography", typeof(Geography));
                metadata.AddPrimitiveProperty(entityType, "Point", typeof(GeographyPoint));
                metadata.AddPrimitiveProperty(entityType, "Point2", typeof(GeographyPoint));
                metadata.AddPrimitiveProperty(entityType, "LineString", typeof(GeographyLineString));
                metadata.AddPrimitiveProperty(entityType, "Polygon", typeof(GeographyPolygon));
                metadata.AddPrimitiveProperty(entityType, "GeographyCollection", typeof(GeographyCollection));
                metadata.AddPrimitiveProperty(entityType, "MultiPoint", typeof(GeographyMultiPoint));
                metadata.AddPrimitiveProperty(entityType, "MultiLineString", typeof(GeographyMultiLineString));
                metadata.AddPrimitiveProperty(entityType, "MultiPolygon", typeof(GeographyMultiPolygon));

                metadata.AddPrimitiveProperty(entityType, "Geometry", typeof(Geometry));
                metadata.AddPrimitiveProperty(entityType, "GeometryPoint", typeof(GeometryPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryPoint2", typeof(GeometryPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryLineString", typeof(GeometryLineString));
                metadata.AddPrimitiveProperty(entityType, "GeometryPolygon", typeof(GeometryPolygon));
                metadata.AddPrimitiveProperty(entityType, "GeometryCollection", typeof(GeometryCollection));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiPoint", typeof(GeometryMultiPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiLineString", typeof(GeometryMultiLineString));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiPolygon", typeof(GeometryMultiPolygon));
            }

            metadata.AddCollectionProperty(entityType, "CollectionOfPoints", typeof(GeographyPoint));
            metadata.AddCollectionProperty(entityType, "GeometryCollectionOfPoints", typeof(GeometryPoint));
            metadata.AddPrimitiveProperty(entityType, "GeographyNull", typeof(Geography));
            metadata.AddPrimitiveProperty(entityType, "GeometryNull", typeof(Geometry));

            metadata.AddResourceSet("Spatials", entityType);

            metadata.SetReadOnly();

            DSPContext context = new DSPContext();
            var set = context.GetResourceSetEntities("Spatials");

            for (int i = 0; i < 3; ++i)
            {
                DSPResource spatialEntity = new DSPResource(entityType);
                spatialEntity.SetValue("ID", i);
                spatialEntity.SetValue("Geography", GeographyFactory.Point(32.0 - i, -100.0).Build());
                spatialEntity.SetValue("Point", GeographyFactory.Point(33.1 - i, -110.0).Build());
                spatialEntity.SetValue("Point2", GeographyFactory.Point(32.1 - i, -110.0).Build());
                spatialEntity.SetValue("LineString", GeographyFactory.LineString(33.1 - i, -110.0).LineTo(35.97 - i, -110).Build());
                spatialEntity.SetValue("Polygon", GeographyFactory.Polygon().Ring(33.1 - i, -110.0).LineTo(35.97 - i, -110.15).LineTo(11.45 - i, 87.75).Ring(35.97 - i, -110).LineTo(36.97 - i, -110.15).LineTo(45.23 - i, 23.18).Build());
                spatialEntity.SetValue("GeographyCollection", GeographyFactory.Collection().Point(-19.99 - i, -12.0).Build());
                spatialEntity.SetValue("MultiPoint", GeographyFactory.MultiPoint().Point(10.2 - i, 11.2).Point(11.9 - i, 11.6).Build());
                spatialEntity.SetValue("MultiLineString", GeographyFactory.MultiLineString().LineString(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineString(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).Build());
                spatialEntity.SetValue("MultiPolygon", GeographyFactory.MultiPolygon().Polygon().Ring(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineTo(11.45 - i, 87.75).Ring(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).LineTo(11.45 - i, 87.75).Build());
                spatialEntity.SetValue("CollectionOfPoints", new List<GeographyPoint>()
                    {
                        GeographyFactory.Point(10.2, 99.5),
                        GeographyFactory.Point(11.2, 100.5)
                    });

                spatialEntity.SetValue("Geometry", GeometryFactory.Point(32.0 - i, -10.0).Build());
                spatialEntity.SetValue("GeometryPoint", GeometryFactory.Point(33.1 - i, -11.0).Build());
                spatialEntity.SetValue("GeometryPoint2", GeometryFactory.Point(32.1 - i, -11.0).Build());
                spatialEntity.SetValue("GeometryLineString", GeometryFactory.LineString(33.1 - i, -11.5).LineTo(35.97 - i, -11).Build());
                spatialEntity.SetValue("GeometryPolygon", GeometryFactory.Polygon().Ring(33.1 - i, -13.6).LineTo(35.97 - i, -11.15).LineTo(11.45 - i, 87.75).Ring(35.97 - i, -11).LineTo(36.97 - i, -11.15).LineTo(45.23 - i, 23.18).Build());
                spatialEntity.SetValue("GeometryCollection", GeometryFactory.Collection().Point(-19.99 - i, -12.0).Build());
                spatialEntity.SetValue("GeometryMultiPoint", GeometryFactory.MultiPoint().Point(10.2 - i, 11.2).Point(11.9 - i, 11.6).Build());
                spatialEntity.SetValue("GeometryMultiLineString", GeometryFactory.MultiLineString().LineString(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineString(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).Build());
                spatialEntity.SetValue("GeometryMultiPolygon", GeometryFactory.MultiPolygon().Polygon().Ring(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineTo(11.45 - i, 87.75).Ring(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).LineTo(11.45 - i, 87.75).Build());
                spatialEntity.SetValue("GeometryCollectionOfPoints", new List<GeometryPoint>()
                    {
                        GeometryFactory.Point(10.2, 99.5),
                        GeometryFactory.Point(11.2, 100.5)
                    });

                spatialEntity.SetValue("GeographyNull", null);
                spatialEntity.SetValue("GeometryNull", null);

                set.Add(spatialEntity);
            }

            var service = new DSPUnitTestServiceDefinition(metadata, DSPDataProviderKind.CustomProvider, context);
            service.DataServiceBehavior.AcceptSpatialLiteralsInQuery = true;
            service.Writable = true;

            return service;
        }
Exemplo n.º 9
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");
            }
        }
Exemplo n.º 10
0
 private static void PopulateResourceSet(DSPContext context, DSPResource resource)
 {
     string resourceSetName = GetResourceSetName(resource.ResourceType.Name);
     var resourceSet = context.GetResourceSetEntities(resourceSetName);
     resourceSet.AddRange(new object[] { resource });
 }
Exemplo n.º 11
0
            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.");
                };
            }
Exemplo n.º 12
0
            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);
                    }
                });
            }
Exemplo n.º 13
0
            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"));
                    }
                });
            }
Exemplo n.º 14
0
            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);
                    });
                }
            }
Exemplo n.º 15
0
        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;
            
        }
Exemplo n.º 16
0
        internal static DSPContext PopulateRoadTripData(DSPMetadata roadTripMetadata, GeographyPropertyValues defaultValues, bool useComplexType, Action<string, List<KeyValuePair<string, object>>> modifyPropertyValues = null)
        {
            var context = new DSPContext();

            DSPResource tripLegResource = CreateTripLegResource(roadTripMetadata, DefaultId, defaultValues.TripLegGeography1, defaultValues.TripLegGeography2, useComplexType, modifyPropertyValues);
            PopulateResourceSet(context, tripLegResource);

            DSPResource amusementParkResource = CreateAmusementParkResource(roadTripMetadata, DefaultId, defaultValues.AmusementParkGeography, "Disneyland", useComplexType, modifyPropertyValues);
            PopulateResourceSet(context, amusementParkResource);

            DSPResource restStopResource = CreateRestStopResource(roadTripMetadata, DefaultId, defaultValues.RestStopGeography, useComplexType, modifyPropertyValues);
            PopulateResourceSet(context, restStopResource);

            return context;
        }
Exemplo n.º 17
0
 /// <summary>Clears all changes applied to the service up until now.</summary>
 public void ClearChanges()
 {
     this.currentDataSource = null;
 }
        private static DSPContext GetDefaultData(DSPMetadata metadata)
        {
            var peopleType = metadata.GetResourceType("PeopleType");
            var officeType = metadata.GetResourceType("OfficeType");

            #region Default Data for the Model
            var context = new DSPContext();

            DSPResource people1 = new DSPResource(peopleType);
            people1.SetValue("ID", 1);
            people1.SetValue("Name", "Foo");
            people1.SetValue("Body", Encoding.UTF8.GetBytes("a byte array"));          
            people1.SetValue("Age", 23);

            var office = new DSPResource(officeType);
            office.SetValue("Building", "Building 18");
            office.SetValue("OfficeNumber", 100);
            people1.SetValue("Office", office);

            var people = context.GetResourceSetEntities("People");
            people.Add( people1 );

            #endregion Default Data for the Model

            return context;
        }
Exemplo n.º 19
0
 /// <summary>Called to initialize the service on a given request.</summary>
 /// <param name="request">The request which was not yet used for the service to initialize on.</param>
 protected override void InitializeService(TestWebRequest request)
 {
     base.InitializeService(request);
     request.RegisterForDispose(() => { this.currentDataSource = null; });
 }
        public DSPUnitTestServiceDefinition(DSPMetadata metadata, DSPDataProviderKind kind, DSPContext context)
        {
            this.Metadata = metadata;

            if (kind == DSPDataProviderKind.CustomProvider)
            {
                this.DataServiceType = typeof(DSPDataService);
                this.ProviderKind = DSPDataProviderKind.CustomProvider;
                this.CreateDataSource = (m) => context;
            }
            else
            {
                Type contextType = GenerateAssemblyAndGetContextType(metadata, kind);
                this.ProviderKind = kind;
                this.DataServiceType = typeof(OpenWebDataService<>).MakeGenericType(contextType);

                if (kind == DSPDataProviderKind.EF || kind == DSPDataProviderKind.Reflection)
                {
                    PopulateContextWithDefaultData(contextType, context, kind);
                }
            }
        }
        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();
                }
            }
        }
 public ChangeScope(DSPUnitTestServiceDefinition service, DSPContext defaultData)
 {
     this.unitTestService = service;
     this.defaultData = defaultData;
 }
        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 },
            };
        }
Exemplo n.º 24
0
            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;
            }
Exemplo n.º 25
0
        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;
        }