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);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="IngestManifestAssetCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The <seealso cref="CloudMediaContext"/> instance.</param>
 /// <param name="parentIngestManifest">parent manifest if collection associated with manifest </param>
 internal IngestManifestAssetCollection(CloudMediaContext cloudMediaContext, IIngestManifest parentIngestManifest)
 {
     _cloudMediaContext    = cloudMediaContext;
     _dataContext          = _cloudMediaContext.DataContextFactory.CreateDataServiceContext();
     _parentIngestManifest = parentIngestManifest;
     _query = new Lazy <IQueryable <IIngestManifestAsset> >(() => _dataContext.CreateQuery <IngestManifestAssetData>(EntitySet));
 }
        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);
                }
            }
        }
Example #4
0
	public void WhenOrdering_ThenSucceeds()
	{
		var config = HttpHostConfiguration.Create();
		config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", config))
		{
			var client = new HttpClient("http://localhost:20000");
			client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

			var context = new DataServiceContext(new Uri("http://localhost:20000"));
			// We always specify how many to take, to be explicit.
			var query = context.CreateQuery<Product>("products")
				.Where(x => x.Owner.Name == "kzu")
				.OrderBy(x => x.Id)
				.ThenBy(x => x.Owner.Id)
				.Skip(1)
				.Take(1);

			//var uri = ((DataServiceQuery)query).RequestUri;
			var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
			Console.WriteLine(uri);
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

			var products = new JsonSerializer().Deserialize<List<Product>>(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

			Assert.Equal(1, products.Count);
		}
	}
        //[TestMethod, Variation("One should not be able to get named streams via load property api")]
        public void NamedStreams_LoadPropertyTest()
        {
            // populate the context
            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
            EntityWithNamedStreams1 entity = context.CreateQuery<EntityWithNamedStreams1>("MySet1").Take(1).Single();

            try
            {
                context.LoadProperty(entity, "Stream1");
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }

            try
            {
                context.BeginLoadProperty(
                    entity,
                    "Stream1",
                    (result) => { context.EndLoadProperty(result); },
                    null);
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }
        }
Example #6
0
        public void AddQueryOptionForFormatShouldThrow()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://myservice/", UriKind.Absolute));

            ctx.CreateQuery <Customer>("Customers").AddQueryOption("$format", "atom").ToString().Should()
            .Be("Error translating Linq expression to URI: The '$format' query option is not supported. Use the DataServiceContext.Format property to set the desired format.");
        }
        /// <summary>
        /// Asynchronously saves this <see cref="IJobTemplate"/> when created from a copy of an existing <see cref="IJobTemplate"/>.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task.</returns>
        public Task SaveAsync()
        {
            if (!string.IsNullOrWhiteSpace(this.Id))
            {
                // The job template was already saved, and there is no current support to update it.
                throw new InvalidOperationException(StringTable.InvalidOperationSaveForSavedJobTemplate);
            }

            DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext();

            this.InnerSave(dataContext);

            return(dataContext
                   .SaveChangesAsync(SaveChangesOptions.Batch, this)
                   .ContinueWith(
                       t =>
            {
                t.ThrowIfFaulted();

                JobTemplateData data = (JobTemplateData)t.AsyncState;

                dataContext.CreateQuery <JobTemplateData>(JobTemplateBaseCollection.JobTemplateSet).Where(jt => jt.Id == data.Id).First();
                dataContext.LoadProperty(data, TaskTemplatesPropertyName);
            }));
        }
Example #8
0
        public virtual async Task CreateAndDeleteLinkToDerivedNavigationPropertyOnBaseEntitySet()
        {
            // clear respository
            await this.ClearRepositoryAsync("InheritanceTests_Vehicles");

            Random r = new Random(RandomSeedGenerator.GetRandomSeed());

            // post new entity to repository
            CreatorSettings creatorSettings = new CreatorSettings()
            {
                NullValueProbability = 0,
            };
            var car                = InstanceCreator.CreateInstanceOf <Car>(r, creatorSettings);
            var vehicle            = InstanceCreator.CreateInstanceOf <MiniSportBike>(r, creatorSettings);
            DataServiceContext ctx = WriterClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4);

            ctx.AddObject("InheritanceTests_Vehicles", car);
            ctx.AddObject("InheritanceTests_Vehicles", vehicle);
            await ctx.SaveChangesAsync();

            ctx.SetLink(car, "SingleNavigationProperty", vehicle);
            await ctx.SaveChangesAsync();

            ctx = ReaderClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4);
            var cars   = (await ctx.CreateQuery <Vehicle>("InheritanceTests_Vehicles").ExecuteAsync()).ToList().OfType <Car>();
            var actual = cars.First();
            await ctx.LoadPropertyAsync(actual, "SingleNavigationProperty");

            AssertExtension.PrimitiveEqual(vehicle, actual.SingleNavigationProperty);

            await this.ClearRepositoryAsync("InheritanceTests_Vehicles");
        }
        public async Task Test_NavigationBidingUrlIsAsExpected()
        {
            var ctx = new DataServiceContext(new Uri("http://localhost"));

            ctx.Format.LoadServiceModel = () => CsdlReader.Parse(XmlReader.Create(new StringReader(EDMX)));
            ctx.Format.UseJson();

            ctx.Configurations.ResponsePipeline.OnMessageReaderSettingsCreated((settingsArgs) =>
            {
                settingsArgs.Settings.Validations = ValidationKinds.None;
            });

            ctx.Configurations.RequestPipeline.OnMessageCreating = args => new CustomizedRequestMessage(
                args,
                RESPONSE,
                new Dictionary <string, string>()
            {
                { "Content-Type", "application/json;charset=utf-8" },
            });

            var query = ctx.CreateQuery <Level3>("Level3");

            var values = await query.ExecuteAsync();

            values = values.ToList();

            var first = values.FirstOrDefault();

            Assert.NotNull(first?.Id);
            Assert.NotNull(ctx.Entities);

            var firstEntityDescriptor = ctx.Entities.FirstOrDefault();

            Assert.Equal(EXPECTED_URL, firstEntityDescriptor?.Identity?.AbsoluteUri);
        }
Example #10
0
        private async Task <IEnumerable <T> > GetEntities <T>(string entitySetName)
        {
            DataServiceContext readClient = ReaderClient(new Uri(this.BaseAddress), ODataProtocolVersion.V4);
            var query = readClient.CreateQuery <T>(entitySetName);

            return(await query.ExecuteAsync());
        }
Example #11
0
    public void WhenOrdering_ThenSucceeds()
    {
        var config = HttpHostConfiguration.Create();

        config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

        using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", config))
        {
            var client = new HttpClient("http://localhost:20000");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

            var context = new DataServiceContext(new Uri("http://localhost:20000"));
            // We always specify how many to take, to be explicit.
            var query = context.CreateQuery <Product>("products")
                        .Where(x => x.Owner.Name == "kzu")
                        .OrderBy(x => x.Id)
                        .ThenBy(x => x.Owner.Id)
                        .Skip(1)
                        .Take(1);

            //var uri = ((DataServiceQuery)query).RequestUri;
            var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
            Console.WriteLine(uri);
            var response = client.Get(uri);

            Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

            var products = new JsonSerializer().Deserialize <List <Product> >(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

            Assert.Equal(1, products.Count);
        }
    }
Example #12
0
        private SessionRow GetSession(string id, DataServiceContext context)
        {
            try
            {
                DataServiceQuery <SessionRow> queryObj = context.CreateQuery <SessionRow>(tableName);
                var query = (from session in queryObj
                             where session.PartitionKey == SecUtility.CombineToKey(applicationName, id)
                             select session).AsTableServiceQuery();
                IEnumerable <SessionRow> sessions = query.Execute();

                // enumerate the result and store it in a list
                var sessionList = new List <SessionRow>(sessions);
                if (sessionList.Count() == 1)
                {
                    return(sessionList.First());
                }

                if (sessionList.Count() > 1)
                {
                    throw new ProviderException("Multiple sessions with the same name!");
                }

                return(null);
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing storage.", e);
            }
        }
        public async Task <SegmentedResult <TItem> > SelectAsync <TItem>(Expression <Func <TItem, bool> > queryExpression, string continuationToken = null, int rowCount = 500) where TItem : class, ITableItem, new()
        {
            QueryExpressionVisitor <TItem> visitor = new QueryExpressionVisitor <TItem>();

            _ = (Expression <Func <TItem, bool> >)visitor.Visit(queryExpression);

            DataServiceContext context = new DataServiceContext(new Uri("https://tempuri.org"));
            var    dataServiceQuery    = context.CreateQuery <TItem>("/items").Where(queryExpression);
            string queryString         = (((DataServiceQuery)dataServiceQuery).RequestUri).Query;
            var    queryCollection     = HttpUtility.ParseQueryString(queryString);

            TableQuery query = new TableQuery()
            {
                FilterString = queryCollection.Get("$filter"),
                TakeCount    = rowCount,
            };

            this.Logger.LogInformation($"Running Azure table query: {query.FilterString}");

            var token       = AzureStorageUtilities.DeserializeTableContinuationToken(continuationToken);
            var azureResult = await this.Table.ExecuteQuerySegmentedAsync(query, token);

            IEnumerable <TItem> itemsList = azureResult.Results.Select(x => this.Assembler.Assemble <TItem>((DynamicTableEntity)x));
            string nextPageToken          = azureResult.ContinuationToken.Serialize();

            return(new SegmentedResult <TItem>(itemsList, nextPageToken, null != nextPageToken));
        }
        public void TestSpecialCharactersInPrimaryKey()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri(this.BaseAddress));
            var  todoes            = ctx.CreateQuery <SpecialCharactersLinkGenerationTestsModel>("SpecialCharactersLinkGenerationWebTests").ToList();
            bool success           = true;

            foreach (var todo in todoes)
            {
                try
                {
                    Uri selfLink;
                    Assert.True(ctx.TryGetUri(todo, out selfLink));
                    Console.WriteLine(selfLink);

                    //ctx.UpdateObject(todo);

                    //var response = ctx.SaveChanges().Single();

                    //Assert.Equal(204, response.StatusCode);

                    ctx.Execute <SpecialCharactersLinkGenerationTestsModel>(selfLink, "GET", true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    success = false;
                }
            }

            Assert.True(success);
        }
Example #15
0
        private static DataServiceQuery <DataServicePackage> CreateQuery()
        {
            var dataServiceContext = new DataServiceContext(new Uri(NuGetOfficialFeedUrl));
            var query = dataServiceContext.CreateQuery <DataServicePackage>("Package");

            return(query);
        }
Example #16
0
        public async Task TestSpecialCharactersInPrimaryKey()
        {
            var client = new DataServiceContext(new Uri(this.BaseAddress));

            client.Format.UseJson(_model);

            var query  = client.CreateQuery <SpecialCharactersLinkGenerationTestsModel>("SpecialCharactersLinkGenerationWebTests");
            var todoes = await query.ExecuteAsync();

            bool success = true;

            foreach (var todo in todoes)
            {
                try
                {
                    Uri selfLink;
                    Assert.True(client.TryGetUri(todo, out selfLink));

                    var result = await client.ExecuteAsync <SpecialCharactersLinkGenerationTestsModel>(selfLink, "GET", true);

                    var fetchedTodo = result.FirstOrDefault();
                    Assert.NotNull(fetchedTodo);
                    Assert.Equal(todo.Name, fetchedTodo.Name);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    success = false;
                }
            }

            Assert.True(success);
        }
Example #17
0
        private RoleRow GetUserInRole(DataServiceContext svc, string rolename, string username)
        {
            SecUtility.CheckParameter(ref username, true, true, true, Constants.MaxTableUsernameLength, "username");
            SecUtility.CheckParameter(ref rolename, true, true, true, MaxTableRoleNameLength, "rolename");

            try
            {
                DataServiceQuery <RoleRow> queryObj = svc.CreateQuery <RoleRow>(_tableName);

                var query = (from user in queryObj
                             where user.PartitionKey == SecUtility.CombineToKey(_applicationName, username) &&
                             user.RowKey == SecUtility.Escape(rolename)
                             select user).AsTableServiceQuery();
                try
                {
                    IEnumerable <RoleRow> userRows = query.Execute();
                    return(userRows.FirstOrDefault());
                }
                catch (InvalidOperationException e)
                {
                    if (e.InnerException is DataServiceClientException && (e.InnerException as DataServiceClientException).StatusCode == (int)HttpStatusCode.NotFound)
                    {
                        return(null);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }
Example #18
0
        public void UpdateEntityTest_ETag()
        {
            IQDSP.Customer c = this.CreateCustomer();
            context.MergeOption = MergeOption.OverwriteChanges;
            context.AddObject("Customers", c);
            context.SaveChanges();

            var outdatedContext = new DataServiceContext(context.BaseUri);

            IQDSP.Customer outdatedSupplier = outdatedContext.CreateQuery <IQDSP.Customer>("Customers").Where(_c => _c.CustomerID == c.CustomerID).FirstOrDefault();

            c.CompanyName = "something else";
            context.UpdateObject(c);
            context.SaveChanges();

            context.UpdateObject(c);
            context.SaveChanges();

            c = context.CreateQuery <IQDSP.Customer>("Customers").Where(_c => _c.CustomerID == c.CustomerID).FirstOrDefault();
            Assert.AreEqual("something else", c.CompanyName);

            outdatedContext.UpdateObject(outdatedSupplier);
            try
            {
                outdatedContext.SaveChanges();
                Assert.Fail("Concurrency failed to throw");
            }
            catch (DataServiceRequestException ex)
            {
                Assert.IsTrue(ex.InnerException.Message.Contains("Concurrency: precondition failed for property 'CompanyName'"));
            }
        }
Example #19
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");
            }
        }
Example #20
0
        public void NamedStreams_DeepEntityProjection_CannotAccessEntitiesAcrossLevels()
        {
            // projecting out deep links to get stream url in DSSL property with multiple parameters in scope - both narrow type and anonymous type
            {
                // Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                        where s.ID == 1
                        from c in s.Collection
                        select new EntityWithNamedStreams2()
                {
                    ID      = c.ID,
                    Stream1 = s.Stream1
                };

                try
                {
                    q.ToList();
                }
                catch (NotSupportedException ex)
                {
                    Assert.AreEqual(ex.Message, DataServicesClientResourceUtil.GetString("ALinq_CanOnlyProjectTheLeaf"), "error message should match as expected");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context in error case");
            }
        }
        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)
                {
                    UrlKeyDelimiter = DataServiceUrlKeyDelimiter.Slash
                };

                if (customize != null)
                {
                    customize(ctx);
                }

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

                var navigationsLinks = descriptor.LinkInfos.Where(l => l.NavigationLink != null).ToList();
                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", navigationsLinks[0].AssociationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/BestFriend", navigationsLinks[0].NavigationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/Orders/$ref", navigationsLinks[1].AssociationLink.OriginalString);
                Assert.AreEqual(baseUri + "/Customers/0/Orders", navigationsLinks[1].NavigationLink.OriginalString);
            }
        }
Example #22
0
        //[TestMethod, Variation("One should not be able to get named streams via load property api")]
        public void NamedStreams_LoadPropertyTest()
        {
            // populate the context
            DataServiceContext      context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
            EntityWithNamedStreams1 entity  = context.CreateQuery <EntityWithNamedStreams1>("MySet1").Take(1).Single();

            try
            {
                context.LoadProperty(entity, "Stream1");
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }

            try
            {
                context.BeginLoadProperty(
                    entity,
                    "Stream1",
                    (result) => { context.EndLoadProperty(result); },
                    null);
            }
            catch (DataServiceClientException ex)
            {
                Assert.IsTrue(ex.Message.Contains(DataServicesResourceUtil.GetString("DataService_VersionTooLow", "1.0", "3", "0")), String.Format("The error message was not as expected: {0}", ex.Message));
            }
        }
Example #23
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);
                    }
                }
            }
        }
        private SessionRow GetSession(string id, DataServiceContext context)
        {
            Debug.Assert(context != null);
            Debug.Assert(id != null && id.Length <= Configuration.MaxStringPropertySizeInChars);

            try
            {
                DataServiceQuery <SessionRow> queryObj = context.CreateQuery <SessionRow>(_tableName);
                var query = (from session in queryObj
                             where session.PartitionKey == SecUtility.CombineToKey(_applicationName, id)
                             select session).AsTableServiceQuery();
                IEnumerable <SessionRow> sessions = query.Execute();

                // enumerate the result and store it in a list
                List <SessionRow> sessionList = new List <SessionRow>(sessions);
                if (sessionList != null && sessionList.Count() == 1)
                {
                    return(sessionList.First());
                }
                else if (sessionList != null && sessionList.Count() > 1)
                {
                    throw new ProviderException("Multiple sessions with the same name!");
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing storage.", e);
            }
        }
Example #25
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");
            }
        }
Example #26
0
        /// <summary>
        /// Constructor
        /// </summary>
        public EntityQuery() : base()
        {
            var context = new DataServiceContext(new Uri(__placeholderServiceName), DataServiceProtocolVersion.V3);

            DataServiceQuery = (DataServiceQuery <T>)context.CreateQuery <T>(__placeholderResourceName).Where(x => true);
            QueryableType    = typeof(T);
        }
Example #27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Ожидание сервера.");

            Thread.Sleep(300);

            var context = new DataServiceContext(new Uri(ServiceAddress))
            {
            };


            context.BuildingRequest   += (s, e) => Console.WriteLine(e.RequestUri);
            context.ReceivingResponse += (s, e) => Console.WriteLine($"Response status: {e.ResponseMessage.StatusCode}");



            //context.AttachTo("");

            var data = context.CreateQuery <Student>("Students").Expand(s => s.School);

            var query = data.Expand("School");

            var uri = ((DataServiceQuery)query).RequestUri.ToString();

            var items = data.ToArray();

            foreach (var item in items)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
Example #28
0
            public void SDPC_DSCFullLoad()
            {
                using (Utils.ConfigurationCacheCleaner())
                    using (Utils.RestoreStaticValueOnDispose(typeof(SimpleDataServiceHelper), "PageSizeCustomizer"))
                    {
                        SimpleDataServiceHelper.PageSizeCustomizer = PageSizeCustomizerFast;
                        SimpleWorkspace workspace = this.NorthwindWorkspacePaged;
                        Uri             baseUri   = new Uri(workspace.ServiceEndPoint + workspace.ServiceContainer.Name + ".svc", UriKind.Absolute);

                        DataServiceContext ctx = new DataServiceContext(baseUri);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        var q = ctx.CreateQuery <northwindBinding.Customers>("Customers").Expand("Orders");

                        int totalCustomerCount = q.Count();
                        int totalOrdersCount   = ctx.CreateQuery <northwindBinding.Orders>("Orders").Count();
                        var custs = new DataServiceCollection <northwindBinding.Customers>(q, TrackingMode.None);

                        for (int i = 0; i < 2; i++)
                        {
                            if (i == 1)
                            {
                                // second iteration
                                ctx            = new DataServiceContext(baseUri);
                                ctx.EnableAtom = true;
                                ctx.Format.UseAtom();
                                q     = ctx.CreateQuery <northwindBinding.Customers>("Customers").Expand("Orders");
                                custs = new DataServiceCollection <northwindBinding.Customers>(q);
                            }

                            while (custs.Continuation != null)
                            {
                                custs.Load(ctx.Execute <northwindBinding.Customers>(custs.Continuation));
                            }

                            int linksCount  = 0;
                            int ordersCount = 0;
                            foreach (var c in custs)
                            {
                                while (c.Orders.Continuation != null)
                                {
                                    if (linksCount++ % 2 == 0)
                                    {
                                        ctx.LoadProperty(c, "Orders", c.Orders.Continuation);
                                    }
                                    else
                                    {
                                        c.Orders.Load(ctx.Execute <northwindBinding.Orders>(c.Orders.Continuation));
                                    }
                                }
                                ordersCount += c.Orders.Count;
                            }

                            Assert.IsTrue(linksCount > 0, "links Count must be greater than 0");
                            Assert.AreEqual(totalCustomerCount, custs.Count);
                            Assert.AreEqual(totalOrdersCount, ordersCount);
                        }
                    }
            }
        protected override IQueryable <Session> BuildQuery(DataServiceContext context)
        {
            var query = from s in context.CreateQuery <Session>("Sessions").Expand("Speakers")
                        orderby s.StartHour, s.Track ascending
            select s;

            return(query);
        }
        /// <summary>
        /// Creates a data service query for data of a specified generic type.
        /// create a query based on (BaseUri + relativeUri)
        /// </summary>
        /// <typeparam name="TIinterface">The exposed interface type of elements returned by the query.</typeparam>
        /// <typeparam name="TData">The type used by the query internaly.</typeparam>
        /// <param name="entitySetName">A string that resolves to a URI.</param>
        /// <returns>A new System.Data.Services.Client.DataServiceQuery<TElement> instance that represents a data service query.</returns>
        public IQueryable <TIinterface> CreateQuery <TIinterface, TData>(string entitySetName)
        {
            _clientRequestIdAdapter.ChangeCurrentRequestId();
            IQueryable <TIinterface> inner = (IQueryable <TIinterface>)_dataContext.CreateQuery <TData>(entitySetName);
            var result = new MediaQueryable <TIinterface, TData>(inner, _queryRetryPolicy);

            return(result);
        }
Example #31
0
 public IQueryable <DataServicePackage> GetPackages()
 {
     if (_query == null)
     {
         _query = _context.CreateQuery <DataServicePackage>(Constants.PackageServiceEntitySetName);
     }
     return(_query);
 }
Example #32
0
        public void SupportPostCollectionPropertyByEntityPayload()
        {
            CreatorSettings settings = new CreatorSettings()
            {
                NullValueProbability = 0.0
            };

            // clear respository
            this.ClearRepository("CollectionProperty_Entity");

            //this.Client.GetStringAsync(this.BaseAddress + "/$metadata").Wait();

            Random r = new Random(RandomSeedGenerator.GetRandomSeed());

            // post new entity to repository
            var expected           = InstanceCreator.CreateInstanceOf <CollectionProperty_Entity>(r, settings);
            DataServiceContext ctx = WriterClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3);

            ctx.AddObject("CollectionProperty_Entity", expected);
            ctx.SaveChanges();

            int id = expected.ID;

            ctx = ReaderClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3);
            var actual = ctx.CreateQuery <CollectionProperty_Entity>("CollectionProperty_Entity").Where(t => t.ID == id).First();

            AssertExtension.DeepEqual(expected, actual);

            expected = actual;
            ctx      = WriterClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3);
            ctx.AttachTo("CollectionProperty_Entity", expected);
            expected.StringList            = InstanceCreator.CreateInstanceOf <List <string> >(r, settings);
            expected.ComplexTypeCollection = InstanceCreator.CreateInstanceOf <Collection <CollectionProperty_ComplexType> >(r, settings);
            ctx.UpdateObject(expected);
            ctx.SaveChanges();

            ctx    = ReaderClient(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3);
            actual = ctx.CreateQuery <CollectionProperty_Entity>("CollectionProperty_Entity").Where(t => t.ID == id).First();

            AssertExtension.DeepEqual(expected, actual);

            // clear respository
            this.ClearRepository("CollectionProperty_Entity");
        }
Example #33
0
        public void FilterCollectionWithAnyAll()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"), ODataProtocolVersion.V4);

            var values = ctx.CreateQuery<EntityWithCollections>("Values");
            var testCases = new[]
            {
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any()
                        select e,
                    url = "Values?$filter=CollectionOfInt/any()"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any() && e.ID == 0
                        select e,
                    url = "Values?$filter=CollectionOfInt/any() and ID eq 0"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any(mv => mv == 2 )
                        select e,
                    url = "Values?$filter=CollectionOfInt/any(mv:mv eq 2)"
                },
                new{
                    q = from e in values
                        where e.CollectionOfInt.Any(mv => mv > e.ID ) && e.ID <100
                        select e,
                    url = "Values?$filter=CollectionOfInt/any(mv:mv gt $it/ID) and ID lt 100"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.Any(mv => e.CollectionOfString.All(s => s.StartsWith(mv.Name)) || e.ID <100) && e.ID > 50
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/any(mv:$it/CollectionOfString/all(s:startswith(s,mv/Name)) or $it/ID lt 100) and ID gt 50"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.All(mv => mv.Name.StartsWith("a") || e.ID <100) && e.ID > 50
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/all(mv:startswith(mv/Name,'a') or $it/ID lt 100) and ID gt 50"
                },
                new{
                    q = from e in values
                        where e.CollectionOfComplexType.All(mv => mv.Name.Contains("a") || mv.Numbers.All(n=>n % 2 == 0)) && e.ID/5 == 3
                        select e,
                    url = "Values?$filter=CollectionOfComplexType/all(mv:contains(mv/Name,'a') or mv/Numbers/all(n:n mod 2 eq 0)) and ID div 5 eq 3"
                },
            };

            TestUtil.RunCombinations(testCases, (testCase) =>
            {
                Assert.AreEqual(ctx.BaseUri.AbsoluteUri + testCase.url,testCase.q.ToString(), "url == q.ToString()");
            });
        }
 public void NamedStreams_SimpleProjectionWithStreams()
 {
     // Doing projection of stream properties using AddQueryOption should work
     DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
     context.EnableAtom = true;
     context.Format.UseAtom();
     var query1 = context.CreateQuery<EntityWithNamedStreams1>("MySet1").AddQueryOption("$select", "ID, Stream1");
     List<EntityWithNamedStreams1> entities = query1.Execute().ToList();
     Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 1, "There must be named streams associated with the entity");
 }
 public void NamedStreams_SimpleProjectionWithoutStreams()
 {
     // Doing projection of non-stream properties should work and there should be no stream descriptors populated in the context
     DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
     context.EnableAtom = true;
     context.Format.UseAtom();
     var query1 = context.CreateQuery<EntityWithNamedStreams1>("MySet1").AddQueryOption("$select", "ID");
     List<EntityWithNamedStreams1> entities = query1.Execute().ToList();
     Assert.AreEqual(entities.Count, 1, "There must be only 1 entities populated in the context");
     Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 0, "There must be no named streams associated with the entity yet, since we didn't specify the named streams in the projection query");
 }
        public void ObterTodosProdutos()
        {
            string url = "http://localhost.fiddler:19523/Services/CatalogoDataService.svc";

            var context = new DataServiceContext(new Uri(url));

            var todosProdutos = context.CreateQuery<Produto>("Produtoes").ToList();

            foreach (var produto in todosProdutos)
            {
                Console.WriteLine(produto);
            }

            var produtosAcima100 = context.CreateQuery<Produto>("Produtoes").
                                        Where(p => p.Preco > 100).ToList();

            foreach (var produto in produtosAcima100)
            {
                Console.WriteLine(produto);
            }
        }
Example #37
0
        public void VerifyStreamInfoAfterQuery()
        {
            // Verifying media link information in query scnearios
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamEditLink(MediaEditLink, contentType: MediaContentType, etag: MediaETag) + GetNamedStreamSelfLink(MediaQueryLink, contentType: MediaContentType));

            string nonbatchPayload = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
            string batchPayload = PlaybackService.ConvertToBatchQueryResponsePayload(nonbatchPayload);

            TestUtil.RunCombinations((IEnumerable<QueryMode>)Enum.GetValues(typeof(QueryMode)), (queryMode) =>
            {
                using (PlaybackService.OverridingPlayback.Restore())
                {
                    if (queryMode == QueryMode.BatchAsyncExecute ||
                        queryMode == QueryMode.BatchAsyncExecuteWithCallback ||
                        queryMode == QueryMode.BatchExecute)
                    {
                        PlaybackService.OverridingPlayback.Value = batchPayload;
                    }
                    else
                    {
                        PlaybackService.OverridingPlayback.Value = nonbatchPayload;
                    }

                    DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    context.EnableAtom = true;
                    DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                    Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, queryMode)).Single();

                    Assert.AreEqual(context.Entities.Count, 1, "expecting just one entitydescriptor in the context");
                    Assert.AreEqual(context.Entities[0].StreamDescriptors.Count, 1, "expecting just one stream info in the entitydescriptor");
                    StreamDescriptor streamInfo = context.Entities[0].StreamDescriptors[0];
                    Assert.AreEqual(streamInfo.StreamLink.SelfLink, MediaQueryLink, "Self link should be as expected");
                    Assert.AreEqual(streamInfo.StreamLink.EditLink, MediaEditLink, "Edit link should be as expected");
                    Assert.AreEqual(streamInfo.StreamLink.ContentType, MediaContentType, "Content-Type did not match");
                    Assert.AreEqual(streamInfo.StreamLink.ETag, MediaETag, "ETag should match");
                }
            });
        }
        private void JobEntityRefresh(DataServiceContext dataContext)
        {
            
            InvalidateCollections();

            var refreshed = dataContext.CreateQuery<JobData>(JobBaseCollection.JobSet).Where(c => c.Id == this.Id).FirstOrDefault();
            
            //it is possible that job has been cancelled and deleted while we are refreshing
            if (refreshed != null)
            {
                this.Created = refreshed.Created;
                this.EndTime= refreshed.EndTime;
                this.LastModified = refreshed.LastModified;
                this.Name = refreshed.Name;
                this.Priority = refreshed.Priority;
                this.RunningDuration = refreshed.RunningDuration;
                this.StartTime = refreshed.StartTime;
                this.State = refreshed.State;
                this.TemplateId = refreshed.TemplateId;
                this.JobNotificationSubscriptions = refreshed.JobNotificationSubscriptions;
                this.Tasks = refreshed.Tasks;
            }
        }
        public async Task TestLongTypeAsPrimaryKey()
        {
            var client = new DataServiceContext(new Uri(this.BaseAddress));
            client.Format.UseJson(GetEdmModel());

            var query = client.CreateQuery<LongPrimaryKeyType>("LongPrimaryKeyType");
            var models = await query.ExecuteAsync();

            foreach (var model in models)
            {
                Uri selfLink;
                Assert.True(client.TryGetUri(model, out selfLink));
                Console.WriteLine(selfLink);

                client.UpdateObject(model);

                var response = await client.SaveChangesAsync();

                Assert.Equal(200, response.Single().StatusCode);
            }
        }
Example #40
0
        private void VerifyServerOrderId(int orderId, int? expectedCustomerId, String message = null)
        {
            var _ctx = new DataServiceContext(web.ServiceRoot);
            _ctx.EnableAtom = true;
            _ctx.Format.UseAtom();

            var order = _ctx.CreateQuery<EFFKClient.Order>("CustomObjectContext.Orders").Expand("Customers").Where(o => o.ID == orderId).FirstOrDefault();

            if (message == null)
            {
                message = String.Format("Order {0} expecting Customer {1}", orderId, expectedCustomerId);
            }

            Assert.IsNotNull(order, message);
            if (expectedCustomerId.HasValue)
            {
                Assert.AreEqual(expectedCustomerId, order.CustomerId, message);
                Assert.AreEqual(expectedCustomerId, order.Customers.ID, message);
            }
            else
            {
                Assert.IsNull(order.Customers);
            }
        }
        private MembershipRow GetUserFromTable(DataServiceContext svc, string username)
        {
            SecUtility.CheckParameter(ref username, true, true, true, Constants.MaxTableUsernameLength, "username");

            DataServiceQuery<MembershipRow> queryObj = svc.CreateQuery<MembershipRow>(this.tableName);

            var query = (from user in queryObj
                         where user.PartitionKey == SecUtility.CombineToKey(this.applicationName, username) &&
                               user.ProfileIsCreatedByProfileProvider == false
                         select user).AsTableServiceQuery();

            IEnumerable<MembershipRow> allUsers = query.Execute();
            if (allUsers == null)
            {
                return null;
            }

            IEnumerator<MembershipRow> e = allUsers.GetEnumerator();
            if (e == null)
            {
                return null;
            }

            // e.Reset() throws a not implemented exception
            // according to the spec, the enumerator is at the beginning of the collections after a call to GetEnumerator()
            if (!e.MoveNext())
            {
                return null;
            }

            MembershipRow ret = e.Current;
            if (e.MoveNext())
            {
                throw new ProviderException("Duplicate elements for primary keys application and user name.");
            }

            return ret;
        }
        private RoleRow GetUserInRole(DataServiceContext svc, string rolename, string username)
        {
            SecUtility.CheckParameter(ref username, true, true, true, Constants.MaxTableUsernameLength, "username");
            SecUtility.CheckParameter(ref rolename, true, true, true, MaxTableRoleNameLength, "rolename");

            try
            {
                DataServiceQuery<RoleRow> queryObj = svc.CreateQuery<RoleRow>(_tableName);

                IEnumerable<RoleRow> query = from user in queryObj
                                             where user.PartitionKey == SecUtility.CombineToKey(_applicationName, username) &&
                                                   user.RowKey == SecUtility.Escape(rolename)
                                             select user;
                TableStorageDataServiceQuery<RoleRow> q = new TableStorageDataServiceQuery<RoleRow>(query as DataServiceQuery<RoleRow>, _tableRetry);
                try
                {
                    IEnumerable<RoleRow> userRows = q.ExecuteAllWithRetries();
                    return userRows.First();
                }
                catch (DataServiceQueryException e)
                {
                    HttpStatusCode s;
                    if (TableStorageHelpers.EvaluateException(e, out s) && s == HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (InvalidOperationException e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }
        private SessionRow GetSession(string id, DataServiceContext context)
        {
            Debug.Assert(context != null, "Http context is null");
            Debug.Assert(id != null && id.Length <= ProvidersConfiguration.MaxStringPropertySizeInChars, "Id is null or longer than allowed");

            try
            {
                DataServiceQuery<SessionRow> queryObj = context.CreateQuery<SessionRow>(this.tableName);
                var query = (from session in queryObj
                             where session.PartitionKey == SecUtility.CombineToKey(this.applicationName, id)
                             select session).AsTableServiceQuery();
                IEnumerable<SessionRow> sessions = query.Execute();

                // enumerate the result and store it in a list
                var sessionList = new List<SessionRow>(sessions);
                if (sessionList != null && sessionList.Count() == 1)
                {
                    return sessionList.First();
                }
                else if (sessionList != null && sessionList.Count() > 1)
                {
                    throw new ProviderException("Multiple sessions with the same name!");
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing storage.", e);
            }
        }
 private static DataServiceQuery<DataServicePackage> CreateQuery()
 {
     var dataServiceContext = new DataServiceContext(new Uri(NuGetOfficialFeedUrl));
     var query = dataServiceContext.CreateQuery<DataServicePackage>("Package");
     return query;
 }
Example #45
0
        public void NamedSteams_VerifyGetReadStreamVersion()
        {
            // Verify that GetReadStream for a named stream sends version 3 headers
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                            id: Id,
                            editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                            properties: Properties,
                            links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType));

            TestUtil.RunCombinations(UnitTestsUtil.BooleanValues, (syncRead) =>
            {
                using (PlaybackService.OverridingPlayback.Restore())
                {
                    PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                    DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    context.EnableAtom = true;
                    DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                    Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();

                    if (syncRead)
                    {
                        context.GetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "img/jpeg" });
                    }
                    else
                    {
                        IAsyncResult result = context.BeginGetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "image/jpeg" }, (r) =>
                            {
                                context.EndGetReadStream(r);
                            },
                            null);

                        if (!result.CompletedSynchronously)
                        {
                            Assert.IsTrue(result.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, AstoriaUnitTests.TestConstants.MaxTestTimeout), false), "BeginExecute timeout");
                        }
                    }

                    VerifyRequestWasVersion3(PlaybackService.LastPlayback);
                }
            });
        }
Example #46
0
        public void GetReadStreamUri()
        {
            // passing invalid name should not throw an exception, instead should return null
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties);

            using (PlaybackService.OverridingPlayback.Restore())
            {
                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();

                // ask the uri for a random named stream
                Assert.IsNull(context.GetReadStreamUri(c, "random"), "DataServiceContext.GetReadStreamUri should not throw if the stream with the given name is not present");
            }
        }
Example #47
0
        public void EmptyOrMissingHRefAttributeValue()
        {
            // Missing href attribute or empty href attribute on named stream link elements
            TestUtil.RunCombinations(
                UnitTestsUtil.BooleanValues, // empty or null href attribute value
                UnitTestsUtil.BooleanValues, // edit or self link
                   (editLink, emptyAttributeValue) =>
                   {
                       string url = emptyAttributeValue ? "" : null;
                       string link = editLink ? GetNamedStreamEditLink(url, MediaContentType) : GetNamedStreamSelfLinkWithNull(url, MediaContentType);

                       // Populate the context with a single customer instance
                       string payload = AtomParserTests.AnyEntry(
                           id: Id,
                           properties: Properties,
                           links: link);

                       using (PlaybackService.OverridingPlayback.Restore())
                       {
                           PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                           DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                           context.EnableAtom = true;
                           DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);

                           ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();
                           StreamDescriptor descriptor = context.Entities.First().StreamDescriptors.First();

                           Uri actual = editLink ? descriptor.StreamLink.EditLink : descriptor.StreamLink.SelfLink;

                           if (emptyAttributeValue)
                           {
                               Assert.IsNotNull(actual, "URI should not be null");
                           }
                           else
                           {
                               Assert.IsNull(actual, "URI should be null");
                           }
                       }
                   });
        }
Example #48
0
        public void UpdateNamedStreamOnDeletedEntity()
        {
            // Calling SetSaveStream on deleted entity is not supported
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType));

            using (PlaybackService.OverridingPlayback.Restore())
            {
                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                DataServiceQuery<Customer> q = (DataServiceQuery<Customer>)context.CreateQuery<Customer>("Customers").Where(c1 => c1.ID == 1);
                Customer c = ((IEnumerable<Customer>)DataServiceContextTestUtil.ExecuteQuery(context, q, QueryMode.AsyncExecute)).Single();

                context.DeleteObject(c);

                try
                {
                    context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true /*closeStream*/, "image/jpeg");
                }
                catch (DataServiceClientException ex)
                {
                    Assert.AreEqual(ex.Message, DataServicesClientResourceUtil.GetString("Context_SetSaveStreamOnInvalidEntityState", EntityStates.Deleted), "Error Message not as expected");
                }
            }
        }
Example #49
0
        public void VerifyEntityDescriptorMergeFunctionality()
        {
            // Make sure that based on the MergeOption, the right links are exposed in the entity descriptor
            TestUtil.RunCombinations(
                    new EntityStates[] { EntityStates.Added, EntityStates.Deleted, EntityStates.Modified, EntityStates.Unchanged },
                    new MergeOption[] { MergeOption.AppendOnly, MergeOption.OverwriteChanges, MergeOption.PreserveChanges },
                    new int[] { -1, 0, 1 }, // -1 indicates less links, 0 means exact same number of links, 1 means some extra links
                    UnitTestsUtil.BooleanValues,
                    UnitTestsUtil.BooleanValues,
                    (entityState, mergeOption, extraLinks, useBatchMode, returnETag) =>
                    {
                        using (PlaybackService.OverridingPlayback.Restore())
                        {
                            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                            context.EnableAtom = true;
                            context.MergeOption = mergeOption;

                            // Populate the context with a single customer instance with 2 named streams
                            string originalServiceRoot = "http://randomservice/Foo.svc";
                            string newServiceRoot = "http://randomservice1/Foo1.svc";

                            string payload = AtomParserTests.AnyEntry(
                                id: Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: Properties,
                                links: GetNamedStreamSelfLink(originalServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                       GetNamedStreamEditLink(originalServiceRoot + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag) +
                                       GetNamedStreamSelfLink(originalServiceRoot + "/Customers(1)/SelfLink/Photo", contentType: MediaContentType, name: "Photo") +
                                       GetNamedStreamEditLink(originalServiceRoot + "/Customers(1)/EditLink/Photo", contentType: MediaContentType, name: "Photo"));

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                            Customer c = DataServiceContextTestUtil.CreateEntity<Customer>(context, "Customers", entityState);
                            PlaybackService.OverridingPlayback.Value = null;

                            string linksPayload = null;
                            string newETag = returnETag ? MediaETag + 1 : null;

                            if (extraLinks == -1)
                            {
                                linksPayload = GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: newETag);
                            }
                            else if (extraLinks == 0)
                            {
                                linksPayload = GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: newETag) +
                                               GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/Photo", contentType: MediaContentType, name: "Photo") +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Photo", contentType: MediaContentType, name: "Photo", etag: newETag);
                            }
                            else
                            {
                                linksPayload = GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: newETag) +
                                               GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/Photo", contentType: MediaContentType, name: "Photo") +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Photo", contentType: MediaContentType, etag: newETag, name: "Photo") +
                                               GetNamedStreamSelfLink(newServiceRoot + "/Customers(1)/SelfLink/HighResolutionPhoto", contentType: MediaContentType, name: "HighResolutionPhoto") +
                                               GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/HighResolutionPhoto", contentType: MediaContentType, name: "HighResolutionPhoto", etag: newETag);
                            }

                            payload = AtomParserTests.AnyEntry(
                                id: Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: Properties,
                                links: linksPayload);

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);

                            if (useBatchMode)
                            {
                                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToBatchQueryResponsePayload(PlaybackService.OverridingPlayback.Value);
                                QueryOperationResponse<Customer> resp = (QueryOperationResponse<Customer>)context.ExecuteBatch(context.CreateQuery<Customer>("/Customers(123)")).Single();
                                c = resp.First();
                            }
                            else
                            {
                                c = context.CreateQuery<Customer>("/Customers(123)").Execute().First();
                            }

                            EntityDescriptor entityDescriptor = context.Entities.Where(ed => Object.ReferenceEquals(c, ed.Entity)).Single();
                            StreamDescriptor thumbnail = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Thumbnail").SingleOrDefault();
                            StreamDescriptor photo = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Photo").SingleOrDefault();
                            StreamDescriptor highResPhoto = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "HighResolutionPhoto").SingleOrDefault();

                            string newSelfLink = newServiceRoot + "/Customers(1)/SelfLink/{0}";
                            string newEditLink = newServiceRoot + "/Customers(1)/EditLink/{0}";
                            string existingSelfLink = originalServiceRoot + "/Customers(1)/SelfLink/{0}";
                            string existingEditLink = originalServiceRoot + "/Customers(1)/EditLink/{0}";

                            if (entityState == EntityStates.Added)
                            {
                                Assert.AreEqual(2, context.Entities.Count, "since its in added state, we will get a new entity descriptor");
                                Assert.AreEqual(2 + extraLinks, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");

                                VerifyNamedStreamInfo(thumbnail, newSelfLink, newEditLink, newETag, contentType: MediaContentType);
                                if (extraLinks == -1)
                                {
                                    Assert.AreEqual(photo, null, "photo must be null when extra links = -1 and state = added");
                                    Assert.AreEqual(highResPhoto, null, "highResPhoto must be null when extra links = -1 and state = added");
                                }
                                else if (extraLinks == 0)
                                {
                                    VerifyNamedStreamInfo(photo, newSelfLink, newEditLink, newETag, contentType: MediaContentType);
                                    Assert.AreEqual(highResPhoto, null, "highResPhoto must be null when extra links = 0 and state = added");
                                }
                                else if (extraLinks == 1)
                                {
                                    VerifyNamedStreamInfo(photo, newSelfLink, newEditLink, newETag, contentType: MediaContentType);
                                    VerifyNamedStreamInfo(highResPhoto, newSelfLink, newEditLink, newETag, contentType: MediaContentType);
                                }
                            }
                            else if (mergeOption == MergeOption.OverwriteChanges ||
                                     (mergeOption == MergeOption.PreserveChanges && (entityState == EntityStates.Deleted || entityState == EntityStates.Unchanged)))
                            {
                                Assert.AreEqual(1, context.Entities.Count, "since its not in added state, we will only have one entity descriptor");
                                int numOfNamedStreams = 2;
                                if (extraLinks == 1)
                                {
                                    numOfNamedStreams = 3;
                                }
                                Assert.AreEqual(numOfNamedStreams, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");

                                VerifyNamedStreamInfo(thumbnail, newSelfLink, newEditLink, newETag ?? MediaETag, MediaContentType);
                                if (extraLinks == -1)
                                {
                                    VerifyNamedStreamInfo(photo, existingSelfLink, existingEditLink, null, MediaContentType);
                                    Assert.AreEqual(highResPhoto, null, "highResPhoto must be null when extra links = -1 and state = added");
                                }
                                else if (extraLinks == 0)
                                {
                                    VerifyNamedStreamInfo(photo, newSelfLink, newEditLink, newETag, MediaContentType);
                                    Assert.AreEqual(highResPhoto, null, "highResPhoto must be null when extra links = 0 and state = added");
                                }
                                else if (extraLinks == 1)
                                {
                                    VerifyNamedStreamInfo(photo, newSelfLink, newEditLink, newETag, MediaContentType);
                                    VerifyNamedStreamInfo(highResPhoto, newSelfLink, newEditLink, newETag, MediaContentType);
                                }
                            }
                            else
                            {
                                // no change should be made
                                Assert.AreEqual(1, context.Entities.Count, "since its not in added state, we will only have one entity descriptor");
                                Assert.AreEqual(2, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");
                                VerifyNamedStreamInfo(thumbnail, existingSelfLink, existingEditLink, MediaETag, MediaContentType);
                                VerifyNamedStreamInfo(photo, existingSelfLink, existingEditLink, null, MediaContentType);
                                Assert.AreEqual(highResPhoto, null, "highResPhoto must be null in AppendOnly");
                            }
                        }
                    });
        }
Example #50
0
        public void NamedStreams_ProjectionMissingStream()
        {
            // making sure some of the invalid linq queries fail
            using (PlaybackService.OverridingPlayback.Restore())
            {
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                // Populate the context with a single customer instance with 2 named streams
                string originalServiceRoot = "http://randomservice/Foo.svc";

                string payload = AtomParserTests.AnyEntry(
                    id: NamedStreamTests.Id,
                    editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                    properties: NamedStreamTests.Properties,
                    links: NamedStreamTests.GetNamedStreamEditLink(originalServiceRoot + "/Customers(1)/EditLink/Thumbnail"));

                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                var q = context.CreateQuery<StreamType2>("Customers").Select(s => new StreamType2()
                            {
                                ID = s.ID,
                                Name = s.Name,
                                Thumbnail = s.Thumbnail,
                                Photo = s.Photo // selecting named stream, but not present in payload
                            });

                Exception ex = TestUtil.RunCatching(() => { q.FirstOrDefault(); });
                Assert.IsNotNull(ex);
                Assert.AreEqual(DataServicesClientResourceUtil.GetString("AtomMaterializer_PropertyMissing", "Photo"), ex.Message);
            }
        }
        private List<MembershipRow> GetUsersInactive(DataServiceContext context, string usernameToMatch, bool startswith, ProfileAuthenticationOption auth, DateTime userInactiveSinceDateUtc)
        {
            DataServiceQuery<MembershipRow> queryObj = context.CreateQuery<MembershipRow>(_tableName);

            CloudTableQuery<MembershipRow> query = null;

            // play a trick to deal with the restrictions of currently supported linq queries
            bool first, second;
            if (auth == ProfileAuthenticationOption.All)
            {
                first = true;
                second = false;
            }
            else if (auth == ProfileAuthenticationOption.Anonymous)
            {
                first = true;
                second = true;
            }
            else
            {
                first = false;
                second = false;
            }


            if (startswith && usernameToMatch == string.Empty)
            {
                query = (from user in queryObj
                         where user.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) > 0 &&
                               user.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                               user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                               user.ProfileBlobName != string.Empty &&
                               (user.IsAnonymous == first || user.IsAnonymous == second)
                         select user).AsTableServiceQuery();
            }
            else if (startswith)
            {
                query = (from user in queryObj
                         where user.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) > 0 &&
                               user.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                               user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                               user.ProfileBlobName != string.Empty &&
                               user.UserName.CompareTo(usernameToMatch) >= 0 &&
                               (user.IsAnonymous == first || user.IsAnonymous == second)
                         select user).AsTableServiceQuery();
            }
            else
            {
                query = (from user in queryObj
                         where user.PartitionKey.CompareTo(SecUtility.CombineToKey(_applicationName, usernameToMatch)) == 0 &&
                               user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                               user.ProfileBlobName != string.Empty &&
                               (user.IsAnonymous == first || user.IsAnonymous == second)
                         select user).AsTableServiceQuery();
            }

            /*
            if (auth == ProfileAuthenticationOption.All) {
                query = from user in queryObj
                        where user.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) > 0 &&
                              user.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                              user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                              user.ProfileBlobName != string.Empty
                        select user;
            }
            else if (auth == ProfileAuthenticationOption.Anonymous)
            {
                query = from user in queryObj
                        where user.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) > 0 &&
                              user.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                              user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                              user.ProfileBlobName != string.Empty &&
                              user.IsAnonymous == true
                        select user;
            }
            else
            {
                Debug.Assert(auth == ProfileAuthenticationOption.Authenticated);
                query = from user in queryObj
                        where user.PartitionKey.CompareTo(SecUtility.EscapedFirst(_applicationName)) > 0 &&
                              user.PartitionKey.CompareTo(SecUtility.NextComparisonString(SecUtility.EscapedFirst(_applicationName))) < 0 &&
                              user.LastActivityDateUtc < userInactiveSinceDateUtc &&
                              user.ProfileBlobName != string.Empty &&
                              user.IsAnonymous == false
                        select user;
            } 
            */

            IEnumerable<MembershipRow> users = query.Execute();

            if (users == null)
            {
                return new List<MembershipRow>(); ;
            }
            return new List<MembershipRow>(users);
        }
 private static DataServiceQuery<DataServicePackage> CreateQuery()
 {
     var dataServiceContext = new DataServiceContext(new Uri("https://nuget.org/api/v2"));
     var query = dataServiceContext.CreateQuery<DataServicePackage>("Package");
     return query;
 }
Example #53
0
        public void NamedStreams_BindingTest()
        {
            // Making sure changing the DataServiceStreamLink properties raises the binding events
            using (PlaybackService.OverridingPlayback.Restore())
            using (PlaybackService.InspectRequestPayload.Restore())
            {
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.MergeOption = MergeOption.OverwriteChanges;

                // Populate the context with an entity
                string payload = AtomParserTests.AnyEntry(
                                id: Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: Properties,
                                links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));
                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                var collection = new DataServiceCollection<NamedStreamWithBinding>(context.CreateQuery<NamedStreamWithBinding>("Customers").Where(c1 => c1.ID == 1), TrackingMode.AutoChangeTracking);

                Assert.AreEqual(1, context.Entities.Count, "context should have one entity as tracking");
                NamedStreamWithBinding entity = collection[0];

                // modifying the property directly: nothing should happen...
                // need to use set save stream
                entity.Thumbnail = entity.Thumbnail;
                Assert.AreEqual(EntityStates.Unchanged, context.Entities[0].State, "the entity should be in unchanged state");

                int propertyChangedCallCount = 0;
                entity.PropertyChanged += (o, args) =>
                    {
                        propertyChangedCallCount++;
                    };

                entity.Thumbnail.PropertyChanged += (o, args) =>
                {
                    propertyChangedCallCount++;
                };

                payload = AtomParserTests.AnyEntry(
                                id: Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: Properties,
                                links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(10)/SelfLink/Thumbnail", contentType: MediaContentType) +
                                GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(10)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));
                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                context.CreateQuery<NamedStreamWithBinding>("Customers").Where(c1 => c1.ID == 1).Single();
                Assert.AreEqual(1, context.Entities.Count, "context should have one entity as tracking");
                Assert.AreEqual(request.ServiceRoot + "/Customers(10)/SelfLink/Thumbnail", entity.Thumbnail.SelfLink.AbsoluteUri);
                Assert.AreEqual(7, propertyChangedCallCount);
            }
        }
Example #54
0
        public void NamedStreams_DataServiceStreamLinkNotAllowedInFilterAndOrderBy()
        {
            // Making sure that DataServiceStreamLink is not allowed only in $filter and $orderby query options
            // Populate the context with a single customer instance
            string payload = AtomParserTests.AnyEntry(
                id: Id,
                properties: Properties,
                links: GetNamedStreamEditLink(MediaEditLink, contentType: MediaContentType, etag: MediaETag) + GetNamedStreamSelfLink(MediaQueryLink, contentType: MediaContentType));

            string nonbatchPayload = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
            string batchPayload = PlaybackService.ConvertToBatchQueryResponsePayload(nonbatchPayload);
            DataServiceContext context = new DataServiceContext(request.ServiceRoot);

            TestUtil.RunCombinations(
                (IEnumerable<QueryMode>)Enum.GetValues(typeof(QueryMode)),
                new DataServiceQuery<StreamType>[] {
                    (DataServiceQuery<StreamType>)context.CreateQuery<StreamType>("Customers").Where(c1 => c1.StreamLink.SelfLink.AbsoluteUri.Equals("Foo")),
                    (DataServiceQuery<StreamType>)context.CreateQuery<StreamType>("Customers").OrderBy(c1 => c1.StreamLink) },
                (queryMode, query) =>
                {
                    using (PlaybackService.OverridingPlayback.Restore())
                    {
                        if (queryMode == QueryMode.BatchAsyncExecute ||
                            queryMode == QueryMode.BatchAsyncExecuteWithCallback ||
                            queryMode == QueryMode.BatchExecute)
                        {
                            PlaybackService.OverridingPlayback.Value = batchPayload;
                        }
                        else
                        {
                            PlaybackService.OverridingPlayback.Value = nonbatchPayload;
                        }

                        try
                        {
                            StreamType c = ((IEnumerable<StreamType>)DataServiceContextTestUtil.ExecuteQuery(context, query, queryMode)).Single();
                        }
                        catch (NotSupportedException e)
                        {
                            Assert.AreEqual(e.Message, DataServicesClientResourceUtil.GetString("ALinq_LinkPropertyNotSupportedInExpression", "StreamLink"));
                        }
                    }
                });
        }
        private SessionRow GetSession(string id, DataServiceContext context)
        {
            Debug.Assert(context != null);
            Debug.Assert(id != null && id.Length <= TableStorageConstants.MaxStringPropertySizeInChars);

            try
            {
                DataServiceQuery<SessionRow> queryObj = context.CreateQuery<SessionRow>(_tableName);
                IEnumerable<SessionRow> query = from session in queryObj
                                                where session.PartitionKey == SecUtility.CombineToKey(_applicationName, id)
                                                select session;
                TableStorageDataServiceQuery<SessionRow> q = new TableStorageDataServiceQuery<SessionRow>(query as DataServiceQuery<SessionRow>, _tableRetry);
                IEnumerable<SessionRow> sessions = q.ExecuteWithRetries();

                // enumerate the result and store it in a list
                List<SessionRow> sessionList = new List<SessionRow>(sessions);
                if (sessionList != null && sessionList.Count() == 1)
                {
                    return sessionList.First();
                } else if (sessionList != null && sessionList.Count() > 1) {
                    throw new ProviderException("Multiple sessions with the same name!");
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error accessing storage.", e);
            }
        }
        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.");
                });
            }
        }
        private RoleRow GetUserInRole(DataServiceContext svc, string rolename, string username)
        {
            SecUtility.CheckParameter(ref username, true, true, true, Constants.MaxTableUsernameLength, "username");
            SecUtility.CheckParameter(ref rolename, true, true, true, MaxTableRoleNameLength, "rolename");

            try
            {
                DataServiceQuery<RoleRow> queryObj = svc.CreateQuery<RoleRow>(_tableName);

                var query = (from user in queryObj
                             where user.PartitionKey == SecUtility.CombineToKey(_applicationName, username) &&
                                   user.RowKey == SecUtility.Escape(rolename)
                             select user).AsTableServiceQuery();
                try
                {
                    IEnumerable<RoleRow> userRows = query.Execute();
                    return userRows.FirstOrDefault();
                }
                catch (InvalidOperationException e)
                {
                    if (e.InnerException is DataServiceClientException && (e.InnerException as DataServiceClientException).StatusCode == (int) HttpStatusCode.NotFound)
                    {
                        return null;
                    }
                    throw;
                }
            }
            catch (Exception e)
            {
                throw new ProviderException("Error while accessing the data store.", e);
            }
        }
        public void ResponseHeadersAndStreamTest()
        {
            // Execute a query using a variety of methods (including sync, async, batch) and verify the response headers and payloads
            using (PlaybackService.OverridingPlayback.Restore())
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
            {
                request.ServiceType = typeof(PlaybackService);
                request.StartService();

                string nonbatchPayload =
@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>
<entry xml:base=""http://sparradevvm1:34866/TheTest/"" xmlns:d=""http://docs.oasis-open.org/odata/ns/data"" xmlns:m=""http://docs.oasis-open.org/odata/ns/metadata"" m:etag=""W/&quot;3d9e3978-e6a7-4742-a44e-ef5a43d18d5f&quot;"" xmlns=""http://www.w3.org/2005/Atom"">
  <id>http://sparradevvm1:34866/TheTest/Customers(1)</id>
  <title type=""text""></title>
  <updated>2010-10-12T18:07:17Z</updated>
  <author>
    <name />
  </author>
  <link rel=""edit"" title=""Customer"" href=""Customers(1)"" />
  <link rel=""http://docs.oasis-open.org/odata/ns/related/BestFriend"" type=""application/atom+xml;type=entry"" title=""BestFriend"" href=""Customers(1)/BestFriend"" />
  <link rel=""http://docs.oasis-open.org/odata/ns/related/Orders"" type=""application/atom+xml;type=feed"" title=""Orders"" href=""Customers(1)/Orders"" />
  <category term=""#AstoriaUnitTests.Stubs.CustomerWithBirthday"" scheme=""http://docs.oasis-open.org/odata/ns/scheme"" />
  <content type=""application/xml"">
    <m:properties>
      <d:GuidValue m:type=""Edm.Guid"">3d9e3978-e6a7-4742-a44e-ef5a43d18d5f</d:GuidValue>
      <d:ID m:type=""Edm.Int32"">1</d:ID>
      <d:Name>Customer 1</d:Name>
      <d:NameAsHtml>&lt;html&gt;&lt;body&gt;Customer 1&lt;/body&gt;&lt;/html&gt;</d:NameAsHtml>
      <d:Birthday m:type=""Edm.DateTimeOffset"">1980-10-12T00:00:00-07:00</d:Birthday>
      <d:Address m:type=""AstoriaUnitTests.Stubs.Address"">
        <d:StreetAddress>Line1</d:StreetAddress>
        <d:City>Redmond</d:City>
        <d:State>WA</d:State>
        <d:PostalCode>98052</d:PostalCode>
      </d:Address>
    </m:properties>
  </content>
</entry>
";
                string nonbatchHttpResponse = PlaybackService.ConvertToPlaybackServicePayload(null, nonbatchPayload);
                string batchPayload;
                string batchHttpResponse = PlaybackService.ConvertToBatchResponsePayload(new string[] { nonbatchHttpResponse }, true, out batchPayload);

                Dictionary<string, string> nonbatchHeaders = new Dictionary<string, string>();
                nonbatchHeaders.Add("Content-Type", "application/atom+xml");
                nonbatchHeaders.Add("__HttpStatusCode", "OK");
                nonbatchHeaders.Add("Content-Length", nonbatchPayload.Length.ToString());
                nonbatchHeaders.Add("Server", "Microsoft-HTTPAPI/2.0");
                nonbatchHeaders.Add("Date", null);

                Dictionary<string, string> batchHeaders = new Dictionary<string, string>();
                batchHeaders.Add("Content-Type", "multipart/mixed; boundary=batchresponse_e9b231d9-72ab-46ea-9613-c7e8f5ece46b");
                batchHeaders.Add("__HttpStatusCode", "Accepted");
                batchHeaders.Add("Content-Length", batchPayload.Length.ToString());
                batchHeaders.Add("Server", "Microsoft-HTTPAPI/2.0");
                batchHeaders.Add("Date", null);

                TestUtil.RunCombinations(((IEnumerable<QueryMode>)Enum.GetValues(typeof(QueryMode))), (queryMode) =>
                    {
                        Dictionary<string, string> expectedResponseHeaders;
                        string expectedResponsePayload;
                        bool isBatchQuery = queryMode == QueryMode.BatchAsyncExecute || queryMode == QueryMode.BatchAsyncExecuteWithCallback || queryMode == QueryMode.BatchExecute;
                        if (isBatchQuery)
                        {
                            PlaybackService.OverridingPlayback.Value = batchHttpResponse;
                            expectedResponseHeaders = batchHeaders;
                            expectedResponsePayload = batchPayload;
                        }
                        else
                        {
                            PlaybackService.OverridingPlayback.Value = nonbatchHttpResponse;
                            expectedResponseHeaders = nonbatchHeaders;
                            expectedResponsePayload = nonbatchPayload;
                        }

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

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

                        // 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];
                        VerifyHeaders(expectedResponseHeaders, actualResponseHeaders);

                        // 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();
                        Assert.AreEqual(expectedResponsePayload, actualResponsePayload, "Response payload was not the value that was expected");

                        // 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.");
                    });
            }
        }
Example #59
0
        public void NamedStreams_Projections_MergeInfoOptions()
        {
            // Make sure that based on the MergeOption, the value of the DataServiceStreamLink is updated
            TestUtil.RunCombinations(
                    new EntityStates[] { EntityStates.Added, EntityStates.Deleted, EntityStates.Modified, EntityStates.Unchanged },
                    new MergeOption[] { MergeOption.AppendOnly, MergeOption.OverwriteChanges, MergeOption.PreserveChanges },
                    new int[] { -1, 0, 1 }, // -1 indicates less links, 0 means exact same number of links, 1 means some extra links
                    UnitTestsUtil.BooleanValues,
                    (entityState, mergeOption, extraLinks, useBatchMode) =>
                    {
                        using (PlaybackService.OverridingPlayback.Restore())
                        {
                            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                            context.EnableAtom = true;
                            context.Format.UseAtom();
                            context.MergeOption = mergeOption;

                            // Populate the context with a single customer instance with 2 named streams
                            string originalServiceRoot = "http://randomservice/Foo.svc";
                            string newServiceRoot = "http://randomservice1/Foo1.svc";

                            string payload = AtomParserTests.AnyEntry(
                                id: NamedStreamTests.Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: NamedStreamTests.Properties,
                                links: NamedStreamTests.GetNamedStreamEditLink(originalServiceRoot + "/Customers(1)/EditLink/Thumbnail"));

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                            DataServiceQuery<StreamType2> query = (DataServiceQuery<StreamType2>)context.CreateQuery<StreamType2>("Customers");

                            StreamType2 c = DataServiceContextTestUtil.CreateEntity<StreamType2>(context, "Customers", entityState, query);
                            PlaybackService.OverridingPlayback.Value = null;

                            string linksPayload = null;

                            if (extraLinks == -1)
                            {
                                // send no links
                            }
                            else if (extraLinks == 0)
                            {
                                linksPayload = NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail");
                            }
                            else
                            {
                                linksPayload = NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Thumbnail") +
                                               NamedStreamTests.GetNamedStreamEditLink(newServiceRoot + "/Customers(1)/EditLink/Photo", name: "Photo");
                            }

                            payload = AtomParserTests.AnyEntry(
                                id: NamedStreamTests.Id,
                                editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                properties: NamedStreamTests.Properties,
                                links: linksPayload);

                            PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);

                            if (useBatchMode)
                            {
                                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToBatchQueryResponsePayload(PlaybackService.OverridingPlayback.Value);
                                QueryOperationResponse<StreamType2> resp = (QueryOperationResponse<StreamType2>)context.ExecuteBatch((DataServiceRequest)query).Single();
                                c = resp.First();
                            }
                            else
                            {
                                switch (extraLinks)
                                {
                                    case -1:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name
                                        }).Single();
                                        break;
                                    case 0:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name,
                                            Thumbnail = s.Thumbnail
                                        }).Single();
                                        break;
                                    default:
                                        c = query.Select(s => new StreamType2()
                                        {
                                            ID = s.ID,
                                            Name = s.Name,
                                            Thumbnail = s.Thumbnail,
                                            Photo = s.Photo
                                        }).Single();
                                        break;
                                }
                            }

                            EntityDescriptor entityDescriptor = context.Entities.Where(ed => Object.ReferenceEquals(c, ed.Entity)).Single();
                            StreamDescriptor thumbnail = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Thumbnail").SingleOrDefault();
                            //Assert.IsTrue(thumbnail == null || object.ReferenceEquals(thumbnail.EntityDescriptor, entityDescriptor), "StreamDescriptor.EntityDescriptor should point to the same instance of entity descriptor");
                            StreamDescriptor photo = entityDescriptor.StreamDescriptors.Where(ns => ns.StreamLink.Name == "Photo").SingleOrDefault();
                            //Assert.IsTrue(photo == null || object.ReferenceEquals(photo.EntityDescriptor, entityDescriptor), "StreamDescriptor.EntityDescriptor should point to the same instance of entity descriptor for photo");

                            string newEditLink = newServiceRoot + "/Customers(1)/EditLink/{0}";
                            string existingEditLink = originalServiceRoot + "/Customers(1)/EditLink/{0}";

                            if (entityState == EntityStates.Added)
                            {
                                Assert.AreEqual(2, context.Entities.Count, "since its in added state, we will get a new entity descriptor");
                                Assert.AreEqual(1 + extraLinks, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");

                                if (extraLinks == -1)
                                {
                                    Assert.AreEqual(thumbnail, null, "photo must be null when extra links = -1 and state = added");
                                }
                                else if (extraLinks == 0)
                                {
                                    NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, newEditLink, null, null);
                                }
                                else if (extraLinks == 1)
                                {
                                    NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, newEditLink, null, null);
                                    NamedStreamTests.VerifyNamedStreamInfo(photo, null, newEditLink, null, null);
                                }
                            }
                            else if (mergeOption == MergeOption.OverwriteChanges ||
                                     (mergeOption == MergeOption.PreserveChanges && (entityState == EntityStates.Deleted || entityState == EntityStates.Unchanged)))
                            {
                                Assert.AreEqual(1, context.Entities.Count, "since its not in added state, we will only have one entity descriptor");
                                int numOfNamedStreams = 1;
                                if (extraLinks == 1)
                                {
                                    numOfNamedStreams = 2;
                                }
                                Assert.AreEqual(numOfNamedStreams, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");

                                if (extraLinks == -1)
                                {
                                    NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, existingEditLink, null, null);
                                    Assert.AreEqual(photo, null, "photo must be null when extra links = -1");
                                }
                                else if (extraLinks == 0)
                                {
                                    NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, newEditLink, null, null);
                                    Assert.AreEqual(photo, null, "photo must be null when extra links = 0");
                                }
                                else if (extraLinks == 1)
                                {
                                    NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, newEditLink, null, null);
                                    NamedStreamTests.VerifyNamedStreamInfo(photo, null, newEditLink, null, null);
                                }
                            }
                            else
                            {
                                // no change should be made
                                Assert.AreEqual(1, context.Entities.Count, "since its not in added state, we will only have one entity descriptor");
                                Assert.AreEqual(1, entityDescriptor.StreamDescriptors.Count, "number of named streams was not as expected");
                                NamedStreamTests.VerifyNamedStreamInfo(thumbnail, null, existingEditLink, null, null);
                                Assert.AreEqual(photo, null, "photo must be null when extra links = 0");
                            }
                        }
                    });
        }
        public async Task TestSpecialCharactersInPrimaryKey()
        {
            var client = new DataServiceContext(new Uri(this.BaseAddress));
            client.Format.UseJson(GetEdmModel());

            var query = client.CreateQuery<SpecialCharactersLinkGenerationTestsModel>("SpecialCharactersLinkGenerationWebTests");
            var todoes = await query.ExecuteAsync();

            bool success = true;
            foreach (var todo in todoes)
            {
                try
                {
                    Uri selfLink;
                    Assert.True(client.TryGetUri(todo, out selfLink));
                    Console.WriteLine(selfLink);

                    await client.ExecuteAsync<SpecialCharactersLinkGenerationTestsModel>(selfLink, "GET", true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    success = false;
                }
            }

            Assert.True(success);
        }