private static Uri ExecuteAssetDeleteRequest( AssetDeleteOptionsRequestAdapter adapter)
 {
     Uri uri = null;
     var context = new DataServiceContext(new Uri("http://127.0.0.1/" + Guid.NewGuid().ToString()));
     bool sendingRequestCalled = false;
     context.SendingRequest2 += delegate(object o, SendingRequest2EventArgs args)
     {
         sendingRequestCalled = true;
         uri = args.RequestMessage.Url;
     };
     try
     {
         AssetData asset = new AssetData() {Id = Guid.NewGuid().ToString()};
         context.AttachTo("Assets", asset);
         context.DeleteObject(asset);
         adapter.Adapt(context);
         context.SaveChanges();
     }
     catch (DataServiceRequestException ex)
     {
         Debug.WriteLine(ex.Message);
     }
     Assert.IsTrue(sendingRequestCalled);
     return uri;
 }
Beispiel #2
0
        public static Uri RegisterDataService(DataServiceContext ctx)
        {
            if (_behavior == null)
                Behavior = Activator.CreateInstance(OAuthConfiguration.Configuration.ClientSettings.WcfDSBehaviorType) as IOAuthBehavior;

            return Behavior.RegisterDataService(ctx);
        }
        public void Init()
        {
            context = new DataServiceContext(new Uri(rootUrl));

            this.sampleDateTimeOffset = new DateTime(2012, 12, 17, 9, 23, 31, DateTimeKind.Utc);
            this.sampleDate = XmlConvert.ToString(this.sampleDateTimeOffset);
        }
Beispiel #4
0
        /// <summary>
        /// Translates resource bound expression tree to a URI.
        /// </summary>
        /// <param name='context'>Data context used to generate type names for types.</param>
        /// <param name="addTrailingParens">flag to indicate whether generated URI should include () if leaf is ResourceSet</param>
        /// <param name="e">The expression to translate</param>
        /// <param name="uri">uri</param>
        /// <param name="version">version for query</param>    
        internal static void Translate(DataServiceContext context, bool addTrailingParens, Expression e, out Uri uri, out Version version)
        {
            var writer = new UriWriter(context);
            writer.Visit(e);
            string fullUri = writer.uriBuilder.ToString();

            if (writer.alias.Any())
            {
                if (fullUri.IndexOf(UriHelper.QUESTIONMARK) > -1)
                {
                    fullUri += UriHelper.AMPERSAND;
                }
                else
                {
                    fullUri += UriHelper.QUESTIONMARK;
                }

                foreach (var kv in writer.alias)
                {
                    fullUri += kv.Key;
                    fullUri += UriHelper.EQUALSSIGN;
                    fullUri += kv.Value;
                    fullUri += UriHelper.AMPERSAND;
                }

                fullUri = fullUri.Substring(0, fullUri.Length - 1);
            }
            

            uri = UriUtil.CreateUri(fullUri, UriKind.Absolute);
            version = writer.uriVersion;
        }
        /// <summary>
        /// Instantiates a new Serializer class and calls WriteEntry method on it.
        /// </summary>
        /// <param name="dataServiceContext"></param>
        /// <returns></returns>
        private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext)
        {
            Person person = new Person();
            Address address = new Address();
            Car car1 = new Car();
            person.Cars.Add(car1);
            person.HomeAddress = address;

            dataServiceContext.AttachTo("Cars", car1);
            dataServiceContext.AttachTo("Addresses", address);

            var requestInfo = new RequestInfo(dataServiceContext);
            var serializer = new Serializer(requestInfo);
            var headers = new HeaderCollection();
            var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var entityDescriptor = new EntityDescriptor(clientModel);
            entityDescriptor.State = EntityStates.Added;
            entityDescriptor.Entity = person;
            var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
            var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) };
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
            return person;
        }
        public void EndToEndShortIntegrationWriteEntryEventTest()
        {
            List<KeyValuePair<string, object>> eventArgsCalled = new List<KeyValuePair<string, object>>();
            var dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/Service.svc"));
            dataServiceContext.Configurations.RequestPipeline.OnEntityReferenceLink((args) => eventArgsCalled.Add(new KeyValuePair<string, object>("OnEntityReferenceLink", args)));
            dataServiceContext.Configurations.RequestPipeline.OnEntryEnding((args) => eventArgsCalled.Add(new KeyValuePair<string, object>("OnEntryEnded", args)));
            dataServiceContext.Configurations.RequestPipeline.OnEntryStarting((args) => eventArgsCalled.Add(new KeyValuePair<string, object>("OnEntryStarted", args)));
            dataServiceContext.Configurations.RequestPipeline.OnNavigationLinkEnding((args) => eventArgsCalled.Add(new KeyValuePair<string, object>("OnNavigationLinkEnded", args)));
            dataServiceContext.Configurations.RequestPipeline.OnNavigationLinkStarting((args) => eventArgsCalled.Add(new KeyValuePair<string, object>("OnNavigationLinkStarted", args)));

            Person person = SetupSerializerAndCallWriteEntry(dataServiceContext);

            eventArgsCalled.Should().HaveCount(8);
            eventArgsCalled[0].Key.Should().Be("OnEntryStarted");
            eventArgsCalled[0].Value.Should().BeOfType<WritingEntryArgs>();
            eventArgsCalled[0].Value.As<WritingEntryArgs>().Entity.Should().BeSameAs(person);
            eventArgsCalled[1].Key.Should().Be("OnNavigationLinkStarted");
            eventArgsCalled[1].Value.Should().BeOfType<WritingNavigationLinkArgs>();
            eventArgsCalled[2].Key.Should().Be("OnEntityReferenceLink");
            eventArgsCalled[2].Value.Should().BeOfType<WritingEntityReferenceLinkArgs>();
            eventArgsCalled[3].Key.Should().Be("OnNavigationLinkEnded");
            eventArgsCalled[3].Value.Should().BeOfType<WritingNavigationLinkArgs>();
            eventArgsCalled[4].Key.Should().Be("OnNavigationLinkStarted");
            eventArgsCalled[4].Value.Should().BeOfType<WritingNavigationLinkArgs>();
            eventArgsCalled[5].Key.Should().Be("OnEntityReferenceLink");
            eventArgsCalled[5].Value.Should().BeOfType<WritingEntityReferenceLinkArgs>();
            eventArgsCalled[6].Key.Should().Be("OnNavigationLinkEnded");
            eventArgsCalled[6].Value.Should().BeOfType<WritingNavigationLinkArgs>();
            eventArgsCalled[7].Key.Should().Be("OnEntryEnded");
            eventArgsCalled[7].Value.Should().BeOfType<WritingEntryArgs>();
            eventArgsCalled[7].Value.As<WritingEntryArgs>().Entity.Should().BeSameAs(person);
        }
        //[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));
            }
        }
	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);
		}
	}
Beispiel #9
0
 private UriWriter(DataServiceContext context)
 {
     Debug.Assert(context != null, "context != null");
     this.context = context;
     this.uriBuilder = new StringBuilder();
     this.uriVersion = Util.DataServiceVersion1;
 }
        /// <summary>
        /// Unregisters this verifier from the context's event
        /// </summary>
        /// <param name="context">The context to stop verifing events on</param>
        /// <param name="inErrorState">A value indicating that we are recovering from an error</param>
        public void UnregisterEventHandler(DataServiceContext context, bool inErrorState)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");
#if !WINDOWS_PHONE
            this.HttpTracker.UnregisterHandler(context, this.HandleRequestResponsePair, !inErrorState);
#endif
        }
Beispiel #11
0
        /// <summary>
        /// constructor for SaveResult
        /// </summary>
        /// <param name="context">context</param>
        /// <param name="method">method</param>
        /// <param name="options">options</param>
        /// <param name="callback">user callback</param>
        /// <param name="state">user state object</param>
        internal SaveResult(DataServiceContext context, string method, SaveChangesOptions options, AsyncCallback callback, object state)
            : base(context, method, null, options, callback, state)
        {
            Debug.Assert(!Util.IsBatch(this.Options), "Util.IsBatch(this.Options) is not set");

            this.cachedResponses = new List<CachedResponse>();
        }
Beispiel #12
0
 /// <summary>
 /// constructor for BatchSaveResult
 /// </summary>
 /// <param name="context">context</param>
 /// <param name="method">method</param>
 /// <param name="queries">queries</param>
 /// <param name="options">options</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state object</param>
 internal BatchSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state)
     : base(context, method, queries, options, callback, state)
 {
     Debug.Assert(Util.IsBatch(options), "the options must have batch  flag set");
     this.Queries = queries;
     this.streamCopyBuffer = new byte[StreamCopyBufferSize];
 }
Beispiel #13
0
 /// <summary>
 /// Creates a new instance of RequestInfo class which is used to build the request to send to the server
 /// </summary>
 /// <param name="context">wrapping context instance.</param>
 internal RequestInfo(DataServiceContext context)
 {
     Debug.Assert(context != null, "context != null");
     this.Context = context;
     this.WriteHelper = new ODataMessageWritingHelper(this);
     this.typeResolver = new TypeResolver(context.Model, context.ResolveTypeFromName, context.ResolveNameFromTypeInternal, context.Format.ServiceModel);
 }
        static public DataServiceState Save(DataServiceContext context, Dictionary<string,object> collections)
        {
            List<Type> knownTypes = GetKnownTypes(context);

            Dictionary<EntityDescriptor, Guid> entityDescriptorToId;
            ContextState contextState = context.SaveState(out entityDescriptorToId);
            string contextAsString = SerializeContextToString(contextState, knownTypes);

            var collectionsState = new Dictionary<string, CollectionState>();
            if (collections != null)
            {
                foreach (KeyValuePair<string, object> kvp in collections)
                {
                    IDataServiceCollection collection = (IDataServiceCollection) kvp.Value;
                    CollectionState collectionState = collection.SaveState(context, entityDescriptorToId);                    
                    collectionsState.Add(kvp.Key, collectionState);
                }
            }

            DataServiceState state = new DataServiceState()
            {
                CollectionsState = collectionsState,
                ContextAsString = contextAsString,
                ContextTypeName = context.GetType().AssemblyQualifiedName,
                KnownTypeNames = knownTypes.Select(t => t.AssemblyQualifiedName).ToList()
            };

            return state;
        }
 public void ClientSerializeGeographyTest_Update()
 {
     DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
     ctx.AttachTo("Entities", testEntity);
     ctx.UpdateObject(testEntity);
     ClientSerializeGeographyTest_Validate(ctx);
 }
        /// <summary>
        /// Analyzes a lambda expression to check whether it can be satisfied with
        /// $select and client-side materialization.
        /// </summary>
        /// <param name="le">Lambda expression.</param>
        /// <param name="re">Resource expression in scope.</param>
        /// <param name="matchMembers">Whether member accesses are matched as top-level projections.</param>
        /// <param name="context">Context of expression to analyze.</param>
        /// <returns>true if the lambda is a client-side projection; false otherwise.</returns>
        internal static bool Analyze(LambdaExpression le, ResourceExpression re, bool matchMembers, DataServiceContext context)
        {
            Debug.Assert(le != null, "le != null");

            if (le.Body.NodeType == ExpressionType.Constant)
            {
                if (ClientTypeUtil.TypeOrElementTypeIsEntity(le.Body.Type))
                {
                    throw new NotSupportedException(Strings.ALinq_CannotCreateConstantEntity);
                }

                re.Projection = new ProjectionQueryOptionExpression(le.Body.Type, le, new List<string>());
                return true;
            }

            if (le.Body.NodeType == ExpressionType.MemberInit || le.Body.NodeType == ExpressionType.New)
            {
                AnalyzeResourceExpression(le, re, context);
                return true;
            }

            if (matchMembers)
            {
                // Members can be projected standalone or type-casted.
                Expression withoutConverts = SkipConverts(le.Body);
                if (withoutConverts.NodeType == ExpressionType.MemberAccess)
                {
                    AnalyzeResourceExpression(le, re, context);
                    return true;
                }
            }

            return false;
        }
 public void ClientSerializeGeographyTest_BindingAddChangeShouldBeDetected()
 {
     DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
     DataServiceCollection<SpatialEntityType> dsc = new DataServiceCollection<SpatialEntityType>(ctx, null, TrackingMode.AutoChangeTracking, "Entities", null, null);
     dsc.Add(testEntity);
     ClientSerializeGeographyTest_Validate(ctx);
 }
Beispiel #18
0
        private static void Analyze(LambdaExpression e, PathBox pb, DataServiceContext context)
        {
            bool flag = ClientTypeUtil.TypeOrElementTypeIsEntity(e.Body.Type);
            ParameterExpression pe = e.Parameters.Last<ParameterExpression>();
            bool flag2 = ClientTypeUtil.TypeOrElementTypeIsEntity(pe.Type);
            if (flag2)
            {
                pb.PushParamExpression(pe);
            }
            if (!flag)
            {
                NonEntityProjectionAnalyzer.Analyze(e.Body, pb, context);
            }
            else
            {
                switch (e.Body.NodeType)
                {
                    case ExpressionType.Constant:
                        throw new NotSupportedException(System.Data.Services.Client.Strings.ALinq_CannotCreateConstantEntity);

                    case ExpressionType.MemberInit:
                        EntityProjectionAnalyzer.Analyze((MemberInitExpression) e.Body, pb, context);
                        goto Label_0099;

                    case ExpressionType.New:
                        throw new NotSupportedException(System.Data.Services.Client.Strings.ALinq_CannotConstructKnownEntityTypes);
                }
                NonEntityProjectionAnalyzer.Analyze(e.Body, pb, context);
            }
        Label_0099:
            if (flag2)
            {
                pb.PopParamExpression();
            }
        }
 public SqlSampleDataPageViewModel(Dispatcher dispatcher, DataServiceContext odataServiceContext)
 {
     this.dispatcher = dispatcher;
     this.Context = odataServiceContext;
     this.Items = new DataServiceCollection<SqlSampleData>(odataServiceContext);
     this.Items.LoadCompleted += this.OnLoadCompleted;
 }
 public void Initialize()
 {
     this.contextWithKeyAsSegment = new DataServiceContext(new Uri("http://myservice/", UriKind.Absolute), ODataProtocolVersion.V4)
                                    {
                                        UrlConventions = DataServiceUrlConventions.KeyAsSegment,
                                    };
 }
        public void ShortIntegrationTestToValidateEntryShouldBeRead()
        {
            var odataEntry = new ODataEntry() { Id = new Uri("http://services.odata.org/OData/OData.svc/Customers(0)") };
            odataEntry.Properties = new ODataProperty[] { new ODataProperty() { Name = "ID", Value = 0 }, new ODataProperty() { Name = "Description", Value = "Simple Stuff" } };

            var clientEdmModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var context = new DataServiceContext();
            MaterializerEntry.CreateEntry(odataEntry, ODataFormat.Atom, true, clientEdmModel);
            var materializerContext = new TestMaterializerContext() {Model = clientEdmModel, Context = context};
            var adapter = new EntityTrackingAdapter(new TestEntityTracker(), MergeOption.OverwriteChanges, clientEdmModel, context);
            QueryComponents components = new QueryComponents(new Uri("http://foo.com/Service"), new Version(4, 0), typeof(Customer), null, new Dictionary<Expression, Expression>());

            var entriesMaterializer = new ODataEntriesEntityMaterializer(new ODataEntry[] { odataEntry }, materializerContext, adapter, components, typeof(Customer), null, ODataFormat.Atom);
            
            var customersRead = new List<Customer>();

            // This line will call ODataEntityMaterializer.ReadImplementation() which will reconstruct the entity, and will get non-public setter called.
            while (entriesMaterializer.Read())
            {
                customersRead.Add(entriesMaterializer.CurrentValue as Customer);
            }

            customersRead.Should().HaveCount(1);
            customersRead[0].ID.Should().Be(0);
            customersRead[0].Description.Should().Be("Simple Stuff");
        }
Beispiel #22
0
        //
        // GET: /OData/
        public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
        {
            DataServiceContext   nwd = new DataServiceContext(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));

               var Products2 =
              (QueryOperationResponse<Product>)nwd.Execute<Product>(
              new Uri("http://services.odata.org/Northwind/Northwind.svc/Products()?$expand=Category,Supplier&$select=ProductID,ProductName,Category/CategoryName,Supplier/CompanyName,Supplier/Country"));

            var t = from p in Products2
                    select new JointProductModel
                    {
                        ProductID = p.ProductID,
                        ProductName = p.ProductName,
                        CategoryName = p.Category.CategoryName,
                        CompanyName = p.Supplier.CompanyName,
                        Country = p.Supplier.Country
                    };

              // ViewBag.count = t.Count();

            ViewBag.page = page;
            ViewBag.rowsPerPage = rowsPerPage;
            ViewBag.sort = sort;
            ViewBag.sortDir = sortDir;
            var r2 = t.AsQueryable().OrderBy(sort + " " + sortDir).Skip((page - 1) * rowsPerPage).Take(rowsPerPage);
            return View(r2.ToList());
        }
 /// <summary>constructor</summary>
 /// <param name="entity">entity</param>
 /// <param name="propertyName">name of collection or reference property to load</param>
 /// <param name="context">Originating context</param>
 /// <param name="request">Originating WebRequest</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state</param>
 /// <param name="dataServiceRequest">request object.</param>
 /// <param name="plan">Projection plan for materialization; possibly null.</param>
 /// <param name="isContinuation">Whether this request is a continuation request.</param>
 internal LoadPropertyResult(object entity, string propertyName, DataServiceContext context, ODataRequestMessageWrapper request, AsyncCallback callback, object state, DataServiceRequest dataServiceRequest, ProjectionPlan plan, bool isContinuation)
     : base(context, Util.LoadPropertyMethodName, dataServiceRequest, request, new RequestInfo(context, isContinuation), callback, state)
 {
     this.entity = entity;
     this.propertyName = propertyName;
     this.plan = plan;
 }
 public DataServicePackageRepository(Uri uri)
 {
     _context = new DataServiceContext(uri);
     _context.SendingRequest += OnSendingRequest;
     _context.IgnoreMissingProperties = true;
     _context.Credentials = CredentialCache.DefaultCredentials;
 }
 private ExpressionWriter(DataServiceContext context)
 {
     Debug.Assert(context != null, "context != null");
     this.context = context;
     this.builder = new StringBuilder();
     this.expressionStack = new Stack<Expression>();
     this.expressionStack.Push(null);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityTrackingAdapter" /> class.
 /// </summary>
 /// <param name="entityTracker">The entity tracker.</param>
 /// <param name="mergeOption">The merge option.</param>
 /// <param name="model">The model.</param>
 /// <param name="context">The context.</param>
 internal EntityTrackingAdapter(EntityTrackerBase entityTracker, MergeOption mergeOption, ClientEdmModel model, DataServiceContext context)
 {
     this.MaterializationLog = new AtomMaterializerLog(mergeOption, model, entityTracker);
     this.MergeOption = mergeOption;
     this.EntityTracker = entityTracker;
     this.Model = model;
     this.Context = context;
 }
Beispiel #27
0
 private static void AnalyzeResourceExpression(LambdaExpression lambda, ResourceExpression resource, DataServiceContext context)
 {
     PathBox pb = new PathBox();
     Analyze(lambda, pb, context);
     resource.Projection = new ProjectionQueryOptionExpression(lambda.Body.Type, lambda, pb.ProjectionPaths.ToList<string>());
     resource.ExpandPaths = pb.ExpandPaths.Union<string>(resource.ExpandPaths, StringComparer.Ordinal).ToList<string>();
     resource.RaiseUriVersion(pb.UriVersion);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DataServiceClientFormat"/> class.
        /// </summary>
        /// <param name="context">DataServiceContext instance associated with this format.</param>
        internal DataServiceClientFormat(DataServiceContext context)
        {
            Debug.Assert(context != null, "Context cannot be null for DataServiceClientFormat");

            // On V6.0.2, we change the default format to be json for the client
            this.ODataFormat = ODataFormat.Json;
            this.context = context;
        }
 // Methods
 public ReportWatchViewModel()
 {
     this.context = new DataServiceContext(new Uri("http://localhost:55555/ReportWatchService.svc", UriKind.Absolute));
     SymbolQueryBegin();
     IndexQueryBegin("^DJI");
     IndexQueryBegin("^GSPC");
     IndexQueryBegin("^IXIC");
 }
Beispiel #30
0
 internal static void Translate(DataServiceContext context, bool addTrailingParens, Expression e, out Uri uri, out Version version)
 {
     var writer = new UriWriter(context);
     writer.leafResourceSet = addTrailingParens ? (e as ResourceSetExpression) : null;
     writer.Visit(e);
     uri = Util.CreateUri(context.BaseUriWithSlash, Util.CreateUri(writer.uriBuilder.ToString(), UriKind.Relative));
     version = writer.uriVersion;
 }
Beispiel #31
0
        public static EntityDescriptor GetEntityDescriptor(this DataServiceContext context, object entity)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");

            return(context.Entities.Where(e => e.Entity == entity).SingleOrDefault());
        }
Beispiel #32
0
            public void SDPC_QORFullLoad()
            {
                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 qor = q.Execute() as QueryOperationResponse <northwindBinding.Customers>;

                        DataServiceQueryContinuation <northwindBinding.Customers> nextCustLink = null;
                        int custCount  = 0;
                        int orderCount = 0;
                        do
                        {
                            ICollection previousOrderCollection = null;

                            foreach (var c in qor)
                            {
                                try
                                {
                                    if (previousOrderCollection != null)
                                    {
                                        qor.GetContinuation(previousOrderCollection);
                                        Assert.Fail("Out of scope collection did not throw");
                                    }
                                }
                                catch (ArgumentException)
                                {
                                }

                                var nextOrderLink = qor.GetContinuation(c.Orders);
                                while (nextOrderLink != null)
                                {
                                    if (custCount % 2 == 0)
                                    {
                                        var innerQOR = ctx.Execute <northwindBinding.Orders>(nextOrderLink) as QueryOperationResponse <northwindBinding.Orders>;
                                        foreach (var innerOrder in innerQOR)
                                        {
                                            ctx.AttachLink(c, "Orders", innerOrder);
                                            c.Orders.Add(innerOrder);
                                        }
                                        nextOrderLink = innerQOR.GetContinuation();
                                    }
                                    else
                                    {
                                        nextOrderLink = ctx.LoadProperty(c, "Orders", nextOrderLink).GetContinuation();
                                    }
                                }

                                previousOrderCollection = c.Orders;

                                orderCount += c.Orders.Count;
                                custCount++;
                            }

                            nextCustLink = qor.GetContinuation();
                            if (nextCustLink != null)
                            {
                                qor = ctx.Execute <northwindBinding.Customers>(nextCustLink) as QueryOperationResponse <northwindBinding.Customers>;
                            }
                        } while (nextCustLink != null);

                        Assert.AreEqual(totalCustomerCount, custCount);
                        Assert.AreEqual(totalOrdersCount, orderCount);
                        Assert.AreEqual(totalOrdersCount, ctx.Links.Count);
                        Assert.AreEqual(totalCustomerCount + totalOrdersCount, ctx.Entities.Count);
                    }
            }
Beispiel #33
0
 /// <summary>
 /// Serialize the operation parameters and put them in a dictionary.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="parameters">The parameters.</param>
 /// <returns>A dictionary where the key is the parameter name, and the value is the serialized parameter value.</returns>
 internal static Dictionary <string, string> SerializeOperationParameters(this DataServiceContext context, UriOperationParameter[] parameters)
 {
     return(parameters.ToDictionary(parameter => parameter.Name, parameter => Serializer.GetParameterValue(context, parameter)));
 }
Beispiel #34
0
 /// <summary>Creates a materializer for partial result sets.</summary>
 /// <param name="context">Context of expression to analyze.</param>
 /// <param name="results">The current page of results</param>
 /// <param name="continuation">The continuation for the results.</param>
 /// <returns>A new materializer.</returns>
 internal static MaterializeAtom CreateWrapper(DataServiceContext context, IEnumerable results, DataServiceQueryContinuation continuation)
 {
     return(new ResultsWrapper(context, results, continuation));
 }
        public void Init()
        {
            this.serviceEdmModel = new EdmModel();

            // Enum type
            this.genreEnumTypeName = "ServiceNS.Genre";
            this.genreEnumType     = new EdmEnumType("ServiceNS", "Genre");
            this.genreEnumType.AddMember(new EdmEnumMember(this.genreEnumType, "Thriller", new EdmEnumMemberValue(1)));
            this.genreEnumType.AddMember(new EdmEnumMember(this.genreEnumType, "SciFi", new EdmEnumMemberValue(2)));
            this.genreEnumType.AddMember(new EdmEnumMember(this.genreEnumType, "Epic", new EdmEnumMemberValue(3)));
            this.serviceEdmModel.AddElement(this.genreEnumType);

            // Complex type
            this.addressComplexTypeName = "ServiceNS.Address";
            this.addressComplexType     = new EdmComplexType("ServiceNS", "Address", null /* baseType */, false /* isAbstract */, true /* isOpen */);
            this.addressComplexType.AddStructuralProperty("AddressLine", EdmPrimitiveTypeKind.String);
            this.addressComplexType.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            this.serviceEdmModel.AddElement(this.addressComplexType);

            // Nested complex type
            this.nextOfKinComplexTypeName = "ServiceNS.NextOfKin";
            this.nextOfKinComplexType     = new EdmComplexType("ServiceNS", "NextOfKin");
            this.nextOfKinComplexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.nextOfKinComplexType.AddStructuralProperty("HomeAddress", new EdmComplexTypeReference(this.addressComplexType, true));
            this.serviceEdmModel.AddElement(this.nextOfKinComplexType);

            // Director entity type
            this.directorEntitySetName  = "Directors";
            this.directorEntityTypeName = "ServiceNS.Director";
            this.directorEntityType     = new EdmEntityType("ServiceNS", "Director", null /* baseType */, false /* isAbstract */, true /* isOpen */); // Open type
            this.directorEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.directorEntityType.AddKeys(this.directorEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
            this.serviceEdmModel.AddElement(directorEntityType);

            // Editor entity type
            this.editorEntitySetName  = "Editors";
            this.editorEntityTypeName = "ServiceNS.Editor";
            this.editorEntityType     = new EdmEntityType("ServiceNS", "Editor", null /* baseType */, false /* isAbstract */, true /* isOpen */); // Open type
            this.editorEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.editorEntityType.AddKeys(this.editorEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
            this.serviceEdmModel.AddElement(editorEntityType);

            // Producer entity type
            this.producerEntitySetName  = "Producers";
            this.producerEntityTypeName = "ServiceNS.Producer";
            this.producerEntityType     = new EdmEntityType("ServiceNS", "Producer"); // Not an open type
            this.producerEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.producerEntityType.AddKeys(this.producerEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
            this.serviceEdmModel.AddElement(producerEntityType);

            // Actor entity type
            this.actorEntitySetName  = "Actors";
            this.actorEntityTypeName = "ServiceNS.Actor";
            this.actorEntityType     = new EdmEntityType("ServiceNS", "Actor", null /* baseType */, false /* isAbstract */, true /* isOpen */); // Open type
            this.actorEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.actorEntityType.AddKeys(this.actorEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
            this.serviceEdmModel.AddElement(actorEntityType);

            // Award entity type
            this.awardEntitySetName  = "Awards";
            this.awardEntityTypeName = "ServiceNS.Award";
            this.awardEntityType     = new EdmEntityType("ServiceNS", "Award"); // Not an open type
            this.awardEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            this.awardEntityType.AddKeys(this.awardEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false));
            this.serviceEdmModel.AddElement(awardEntityType);

            // Entity container
            EdmEntityContainer container = new EdmEntityContainer("ServiceNS", "Container");

            container.AddEntitySet(this.directorEntitySetName, this.directorEntityType, true);
            container.AddEntitySet(this.editorEntitySetName, this.editorEntityType, true);
            container.AddEntitySet(this.producerEntitySetName, this.producerEntityType, true);
            container.AddEntitySet(this.actorEntitySetName, this.actorEntityType, true);
            container.AddEntitySet(this.awardEntitySetName, this.awardEntityType, true);
            this.serviceEdmModel.AddElement(container);

            this.clientEdmModel = new ClientEdmModel(ODataProtocolVersion.V4);

            this.context = new DataServiceContext(new Uri("http://tempuri.org/"), ODataProtocolVersion.V4, this.clientEdmModel);
            this.context.UndeclaredPropertyBehavior = UndeclaredPropertyBehavior.Support;
            this.context.Format.UseJson(this.serviceEdmModel);

            var serverTypeNames = new[]
            {
                this.genreEnumTypeName,
                this.addressComplexTypeName,
                this.nextOfKinComplexTypeName,
                this.directorEntityTypeName,
                this.editorEntityTypeName,
                this.producerEntityTypeName,
                this.actorEntityTypeName,
                this.awardEntityTypeName
            };

            this.context.ResolveName = type => {
                // Lazy approach to resolving server type names - alternative would be multiple if/else blocks
                return(serverTypeNames.FirstOrDefault(d => d.EndsWith(type.Name, StringComparison.Ordinal)));
            };

            var serverTypeNameToClientTypeMapping = new Dictionary <string, Type>
            {
                { this.genreEnumTypeName, typeof(Genre) },
                { this.addressComplexTypeName, typeof(Address) },
                { this.nextOfKinComplexTypeName, typeof(NextOfKin) },
                { this.directorEntityTypeName, typeof(Director) },
                { this.producerEntityTypeName, typeof(Producer) },
                { this.editorEntityTypeName, typeof(Editor) },
                { this.actorEntityTypeName, typeof(Actor) },
                { this.awardEntityTypeName, typeof(Award) }
            };

            this.context.ResolveType = name => {
                if (!serverTypeNameToClientTypeMapping.ContainsKey(name))
                {
                    return(null);
                }
                // Lazy approach to resolving client types - alternative would be multiple if/else blocks
                return(serverTypeNameToClientTypeMapping[name]);
            };

            this.typeNameToEntitySetMapping = new Dictionary <string, string>
            {
                { typeof(Director).Name, this.directorEntitySetName },
                { typeof(Editor).Name, this.editorEntitySetName },
                { typeof(Producer).Name, this.producerEntitySetName },
                { typeof(Actor).Name, this.actorEntitySetName }
            };
        }
 public static DataServiceContext ReConfigureForNetworkLoadingTests(this DataServiceContext context)
 {
     context.Format.InjectMetadataHttpNetworkRequest = InjectFakeEdmxRequest;
     return(context);
 }
Beispiel #37
0
        public static void AddObject <TEntity>(this DataServiceContext dataServiceContext, TEntity entity)
        {
            var entitySetName = new EnglishPluralizationService().Pluralize(typeof(TEntity).Name);

            dataServiceContext.AddObject(entitySetName, entity);
        }
Beispiel #38
0
        /// <summary>
        /// A Factory class to use in selecting the implementation to use depending on the
        /// </summary>
        /// <param name="args"></param>
        /// <param name="dataServiceContext"></param>
        /// <returns></returns>

        public DataServiceClientRequestMessage CreateRequestMessage(DataServiceClientRequestMessageArgs args, DataServiceContext dataServiceContext)
        {
            if (dataServiceContext.HttpRequestTransportMode == HttpRequestTransportMode.HttpWebRequest)
            {
                return(new HttpWebRequestMessage(args));
            }
            else
            {
                return(new HttpClientRequestMessage(args));
            }
        }
 /// <summary>
 /// Create a new instance of <see cref="ClientCreatedArgs"/>
 /// </summary>
 /// <param name="name">the logical name of the client.</param>
 /// <param name="container">the instance of data service context for client communication.</param>
 public ClientCreatedArgs(string name, DataServiceContext container)
 {
     this.Name        = name;
     this.ODataClient = container;
 }
Beispiel #40
0
 public static Task <DataServiceStreamResponse> GetReadStreamAsync(this DataServiceContext context, object entity, DataServiceRequestArgs args, object state)
 {
     return(Task.Factory.FromAsync <object, DataServiceRequestArgs, DataServiceStreamResponse>(context.BeginGetReadStream, context.EndGetReadStream, entity, args, state));
 }
Beispiel #41
0
        public static LinkDescriptor GetLinkDescriptor(this DataServiceContext context, object source, string sourceProperty, object target)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");

            return(context.Links.Where(l => l.Source == source && l.Target == target && l.SourceProperty == sourceProperty).SingleOrDefault());
        }
Beispiel #42
0
        public void BlobStreamSaveChanges()
        {
            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                using (PlaybackService.InspectRequestPayload.Restore())
                    using (PlaybackService.OverridingPlayback.Restore())
                    {
                        request.ServiceType        = typeof(PlaybackService);
                        request.ForceVerboseErrors = true;
                        request.StartService();
                        byte[] content = new byte[] { 1, 2, 3 };

                        DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri, UriKind.RelativeOrAbsolute));
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        Stream stream = new MemoryStream(content);
                        ClientCSharpRegressionTests.CustomerWithStream customer = new ClientCSharpRegressionTests.CustomerWithStream()
                        {
                            ID = 1, Name = "Foo"
                        };
                        ctx.AddObject("Customers", customer);
                        ctx.SetSaveStream(customer, stream, true, new DataServiceRequestArgs()
                        {
                            ContentType = "application/jpeg"
                        });

                        EntityDescriptor ed = ctx.Entities[0];

                        int    i              = 0;
                        string id             = "http://myidhost/somerandomIDUrl";
                        string selfLink       = request.BaseUri + "/self-link/Customer(1)";
                        string editLink       = request.BaseUri + "/edit-link/Customer(1)";
                        string etag           = "someetagvalue";
                        string serverTypeName = "SomeRandomTypeName";

                        string editMediaLink  = "http://myhost/somerandomeUrl/edit-media-link/v1";
                        string readMediaLink  = "http://myedithost/somerandomUrl/foo/self-media-link/v1";
                        string streamETag     = "somerandomeStreamETag";
                        string mediaType      = "application/jpeg";
                        string locationHeader = "http://mylocationhost/somerandomUrl/location/";

                        PlaybackService.InspectRequestPayload.Value = (message) =>
                        {
                            if (i == 0)
                            {
                                string xml = MediaEntry(
                                    id: id,
                                    selfLink: selfLink,
                                    editLink: editLink,
                                    etag: etag,
                                    properties: "<d:ID>5</d:ID>",
                                    serverTypeName: serverTypeName,
                                    readStreamUrl: readMediaLink,
                                    editStreamUrl: editMediaLink,
                                    mediaETag: streamETag,
                                    mediaType: mediaType);

                                // The response payload has some random location header and no etag header.
                                // Verify that the edit link, etag and type name are used from the payload.
                                string responsePayload =
                                    "HTTP/1.1 201 Created" + Environment.NewLine +
                                    "Content-Type: application/atom+xml" + Environment.NewLine +
                                    "Location: " + locationHeader + Environment.NewLine +
                                    Environment.NewLine +
                                    xml;
                                PlaybackService.OverridingPlayback.Value = responsePayload;
                            }
                            else if (i == 1)
                            {
                                // Make sure that no metadata from the payload is merged yet into the public entity descriptor
                                // In V2, we already set the edit link and id to the location header. So that part cannot be changed now.
                                Assert.AreEqual(ed.Identity, locationHeader, "id must be set to location header");
                                Assert.AreEqual(ed.EditLink.AbsoluteUri, locationHeader, "edit link value must be equal to the location header");
                                Assert.AreEqual(ed.SelfLink, null, "Self link must not be populated");
                                Assert.AreEqual(ed.ETag, null, "etag must be null");
                                Assert.AreEqual(ed.ServerTypeName, null, "server type name must be null");
                                Assert.AreEqual(ed.EditStreamUri, null, "edit media stream must be null");
                                Assert.AreEqual(ed.ReadStreamUri, null, "read media stream must be null");
                                Assert.AreEqual(ed.StreamETag, null, "stream etag must be null");

                                // no response for PUT
                                string responsePayload =
                                    "HTTP/1.1 200 OK" + Environment.NewLine +
                                    "Content-Type: application/atom+xml" + Environment.NewLine +
                                    Environment.NewLine;
                                PlaybackService.OverridingPlayback.Value = responsePayload;
                            }

                            i++;
                        };


                        ctx.SaveChanges();

                        Assert.IsTrue(i == 2, "only 2 requests should be sent to the server)");

                        // Make sure the edit link from the payload is used, not the location header
                        Assert.IsTrue(PlaybackService.LastPlayback.Contains("PATCH " + editLink), "should use edit link from the POST response payload");

                        // make sure the etag is used from the payload
                        Assert.IsTrue(PlaybackService.LastPlayback.Contains("If-Match: W/\"" + etag + "\""), "should use the etag value from the POST response payload");

                        // make sure the type is used from the payload
                        Assert.IsTrue(PlaybackService.LastPlayback.Contains("category term=\"#" + serverTypeName + "\" scheme=\"http://docs.oasis-open.org/odata/ns/scheme\""), "should use the server type name as specified in the POST response payload");

                        Assert.AreEqual(ed.Identity, id, "id must be set to location header");
                        Assert.AreEqual(ed.EditLink.AbsoluteUri, editLink, "edit link value must be equal to the location header");
                        Assert.AreEqual(ed.SelfLink, selfLink, "Self link should be populated");
                        Assert.AreEqual(ed.ETag, null, "etag must be null, since the PATCH response didn't send any etag in the response header");
                        Assert.AreEqual(ed.ServerTypeName, serverTypeName, "server type name must NOT be null");
                        Assert.AreEqual(ed.EditStreamUri, editMediaLink, "edit media stream must NOT be null");
                        Assert.AreEqual(ed.ReadStreamUri, readMediaLink, "read media stream must NOT be null");
                        Assert.AreEqual(ed.StreamETag, streamETag, "stream etag must NOT be null");
                    }
        }
 protected BaseRepositoryReadOnly(DataServiceContext context)
 {
     _context = context;
 }
Beispiel #44
0
 public TransportLayerThatRemembersIfMatchAndAlwaysSendsBack204(DataServiceContext context)
     : base(context)
 {
     // Do nothing
 }
Beispiel #46
0
 public void Init()
 {
     this.testSubject = new DataServiceContext(new Uri("http://base.org/"));
 }
Beispiel #47
0
        private SessionRow GetSession(string id)
        {
            DataServiceContext svc = CreateDataServiceContext();

            return(GetSession(id, svc));
        }
Beispiel #48
0
 /// <summary>
 ///  Creates materializer for results
 /// </summary>
 /// <param name="context">Context of expression to analyze.</param>
 /// <param name="results">the results to wrap</param>
 /// <returns>a new materializer</returns>
 internal static MaterializeAtom CreateWrapper(DataServiceContext context, IEnumerable results)
 {
     return(new ResultsWrapper(context, results, null));
 }
Beispiel #49
0
 /// <summary>
 /// Creates a wrapper for raw results
 /// </summary>
 /// <param name="context">Context of expression to analyze.</param>
 /// <param name="results">the results to wrap</param>
 /// <param name="continuation">The continuation for this query.</param>
 internal ResultsWrapper(DataServiceContext context, IEnumerable results, DataServiceQueryContinuation continuation)
 {
     this.context      = context;
     this.results      = results ?? new object[0];
     this.continuation = continuation;
 }
Beispiel #50
0
 public static Task <QueryOperationResponse> LoadPropertyAsync(this DataServiceContext context, object entity, string propertyName, Uri nextLinkUri, object state)
 {
     return(Task.Factory.FromAsync <object, string, Uri, QueryOperationResponse>(context.BeginLoadProperty, context.EndLoadProperty, entity, propertyName, nextLinkUri, state));
 }
 /// <summary>Constructs a query provider based on the context passed in </summary>
 /// <param name="context">The context for the query provider</param>
 internal DataServiceQueryProvider(DataServiceContext context)
 {
     this.Context = context;
 }
Beispiel #52
0
 /// <summary>
 /// Private constructor for creating UriWriter
 /// </summary>
 /// <param name='context'>Data context used to generate type names for types.</param>
 private UriWriter(DataServiceContext context)
 {
     Debug.Assert(context != null, "context != null");
     this.context    = context;
     this.uriVersion = Util.ODataVersion4;
 }
Beispiel #53
0
 public static Task <DataServiceResponse> SaveChangesAsync(this DataServiceContext context, SaveChangesOptions options, object state)
 {
     return(Task.Factory.FromAsync <SaveChangesOptions, DataServiceResponse>(context.BeginSaveChanges, context.EndSaveChanges, options, state));
 }
 public void Init()
 {
     this.v3Context     = new DataServiceContext(new Uri("http://temp.org/"), ODataProtocolVersion.V4);
     this.v3TestSubject = this.v3Context.Format;
 }
Beispiel #55
0
        public ODataPropertyConverterTests()
        {
            this.serverModel          = new EdmModel();
            this.serverEntityType     = new EdmEntityType("Server.NS", "ServerEntityType");
            this.serverEntityTypeName = "Server.NS.ServerEntityType";
            this.serverModel.AddElement(this.serverEntityType);
            this.serverEntityType.AddKeys(this.serverEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));

            var addressType = new EdmComplexType("Server.NS", "Address");

            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            this.serverEntityType.AddStructuralProperty("Address", new EdmComplexTypeReference(addressType, true));
            this.serverComplexTypeName = "Server.NS.Address";

            var homeAddressType = new EdmComplexType("Server.NS", "HomeAddress", addressType);

            homeAddressType.AddStructuralProperty("FamilyName", EdmPrimitiveTypeKind.String);
            this.serverComplexTypeName = "Server.NS.HomeAddress";

            var colorType = new EdmEnumType("Server.NS", "Color");

            colorType.AddMember(new EdmEnumMember(colorType, "Red", new EdmEnumMemberValue(1)));
            colorType.AddMember(new EdmEnumMember(colorType, "Blue", new EdmEnumMemberValue(2)));
            colorType.AddMember(new EdmEnumMember(colorType, "Green", new EdmEnumMemberValue(3)));
            this.serverEntityType.AddStructuralProperty("Color", new EdmEnumTypeReference(colorType, false));

            this.serverEntityType.AddStructuralProperty("Nicknames", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetInt32(false))));
            this.serverEntityType.AddStructuralProperty("OtherAddresses", new EdmCollectionTypeReference(new EdmCollectionType(new EdmComplexTypeReference(addressType, false))));

            this.clientModel          = new ClientEdmModel(ODataProtocolVersion.V4);
            this.clientTypeAnnotation = this.clientModel.GetClientTypeAnnotation(typeof(TestClientEntityType));

            this.context = new DataServiceContext(new Uri("http://temp/"), ODataProtocolVersion.V4, this.clientModel);
            this.context.Format.UseJson(this.serverModel);

            this.testSubject = new ODataPropertyConverter(new RequestInfo(this.context));

            this.context.Format.UseJson(this.serverModel);
            this.context.ResolveName = t =>
            {
                if (t == typeof(TestClientEntityType))
                {
                    return(this.serverEntityTypeName);
                }

                if (t == typeof(Address))
                {
                    return(this.serverComplexTypeName);
                }

                return(null);
            };
            this.entity = new TestClientEntityType
            {
                Id             = 1,
                Name           = "foo",
                Number         = 1.23f,
                Address        = new Address(),
                OpenAddress    = new Address(),
                Nicknames      = new string[0],
                OtherAddresses = new[] { new Address() },
                Color          = 0
            };
            this.entityWithDerivedComplexProperty = new TestClientEntityType
            {
                Id             = 1,
                Name           = "foo",
                Number         = 1.23f,
                Address        = new HomeAddress(),
                OpenAddress    = new Address(),
                Nicknames      = new string[0],
                OtherAddresses = new[] { new Address() }
            };
            this.entityWithDerivedComplexInCollection = new TestClientEntityType
            {
                Id             = 1,
                Name           = "foo",
                Number         = 1.23f,
                Address        = new HomeAddress(),
                OpenAddress    = new Address(),
                Nicknames      = new string[0],
                OtherAddresses = new[] { new Address(), new HomeAddress() }
            };
        }
Beispiel #56
0
 public void PerTestCleanup()
 {
     this.ctx = null;
 }
Beispiel #57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AssetFileCollection"/> class.
 /// </summary>
 /// <param name="cloudMediaContext">The cloud media context.</param>
 internal AssetFileCollection(CloudMediaContext cloudMediaContext)
 {
     _cloudMediaContext   = cloudMediaContext;
     this._dataContext    = cloudMediaContext.DataContextFactory.CreateDataServiceContext();
     this._assetFileQuery = new Lazy <IQueryable <IAssetFile> >(() => this._dataContext.CreateQuery <AssetFileData>(FileSet));
 }
Beispiel #58
0
 public static Task <IEnumerable <T> > ExecuteAsync <T>(this DataServiceContext context, Uri requestUri, object state)
 {
     return(Task.Factory.FromAsync <Uri, IEnumerable <T> >(context.BeginExecute <T>, context.EndExecute <T>, requestUri, state));
 }
Beispiel #59
0
        public void NamedStreams_NestedQuery_1()
        {
            // projecting out deep links to get stream url in DSSL property - 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);
                //context.EnableAtom = true;
                //context.Format.UseAtom();
                var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                        select new EntityWithNamedStreams1
                {
                    ID      = s.ID,
                    Stream1 = s.Stream1,
                    Ref     = new EntityWithNamedStreams1
                    {
                        ID         = s.Ref.ID,
                        RefStream1 = s.Ref.RefStream1
                    },
                    Collection = (from c in s.Collection
                                  select new EntityWithNamedStreams2()
                    {
                        ID = c.ID,
                        ColStream = c.ColStream
                    }).ToList()
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Ref($select=ID),Ref($select=RefStream1),Collection($select=ID),Collection($select=ColStream)&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                foreach (var o in q)
                {
                    Assert.IsNotNull(o.Stream1, "Stream11 must have some value");
                    Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the stream url for Stream1 must be populated correctly");
                    Assert.AreEqual(o.Ref.RefStream1.EditLink, context.GetReadStreamUri(o.Ref, "RefStream1"), "the stream url for RefStream1 must be populated correctly");
                    foreach (var c in o.Collection)
                    {
                        Assert.AreEqual(c.ColStream.EditLink, context.GetReadStreamUri(c, "ColStream"), "the url for the nested collection entity should match");
                    }
                }

                Assert.AreEqual(context.Entities.Count, 3, "there should be 3 entities tracked by the context");
                Assert.AreEqual(context.Entities[0].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet1(1)", "top level entity must be tracked");
                Assert.AreEqual(context.Entities[1].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet2(3)", "the nested entity must be tracked");
                Assert.AreEqual(context.Entities[2].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')", "top level entity must be tracked");
            }

            {
                // 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);
                //context.EnableAtom = true;
                //context.Format.UseAtom();
                var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                        select new
                {
                    ID         = s.ID,
                    Stream1Url = s.Stream1,
                    Ref        = new
                    {
                        ID         = s.Ref.ID,
                        Stream1Url = s.Ref.RefStream1
                    },
                    Collection = (from c in s.Collection
                                  select new
                    {
                        Name = c.Name,
                        Stream1Url = c.ColStream
                    })
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Ref($select=ID),Ref($select=RefStream1),Collection($select=Name),Collection($select=ColStream)&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                foreach (var o in q)
                {
                    Assert.AreEqual(o.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet1(1)/Stream1", "the stream url for Stream1 must be populated correctly");
                    Assert.AreEqual(o.Ref.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url for RefStream1 must be populated correctly");
                    Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context");
            }
        }
Beispiel #60
0
        public void NamedStreams_NestedQuery_2()
        {
            // projecting out collection of collection properties - 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);
                //context.EnableAtom = true;
                //context.Format.UseAtom();
                DataServiceQuery <EntityWithNamedStreams1> q = (DataServiceQuery <EntityWithNamedStreams1>) from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                                                               select new EntityWithNamedStreams1
                {
                    ID         = s.ID,
                    Stream1    = s.Stream1,
                    Collection = (from c in s.Collection
                                  select new EntityWithNamedStreams2()
                    {
                        ID = c.ID,
                        ColStream = c.ColStream,
                        Collection1 = (from c1 in c.Collection1
                                       select new EntityWithNamedStreams1()
                        {
                            ID = c1.ID,
                            RefStream1 = c1.RefStream1
                        }).ToList()
                    }).ToList()
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=ID),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                var response = (QueryOperationResponse <EntityWithNamedStreams1>)q.Execute();
                DataServiceQueryContinuation <EntityWithNamedStreams2> continuation = null;
                foreach (var o in response)
                {
                    Assert.IsNotNull(o.Stream1.EditLink, "Stream1 should not be null");
                    Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the stream url for Stream1 must be populated correctly");
                    foreach (var c in o.Collection)
                    {
                        Assert.IsNotNull(c.ColStream.EditLink, "ColStream should not be null");
                        Assert.AreEqual(c.ColStream.EditLink, context.GetReadStreamUri(c, "ColStream"), "the url for the nested collection entity should match - Level 0");
                        foreach (var c1 in c.Collection1)
                        {
                            Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
                            Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
                        }
                    }

                    // Make sure you get the continuation token for the collection and try and get the next page
                    continuation = response.GetContinuation(o.Collection);
                }

                Assert.AreEqual(context.Entities.Count, 3, "there should be 3 entities tracked by the context");
                Assert.AreEqual(context.Entities[0].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet1(1)", "top level entity must be tracked");
                Assert.AreEqual(context.Entities[1].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')", "top level entity must be tracked");
                Assert.AreEqual(context.Entities[2].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet2(3)", "the nested entity must be tracked");
                Assert.IsNotNull(continuation, "since SDP is turned on, we should get the continuation token");

                // Get the next page and make sure we get the right entity and the link is populated.
                foreach (var entity in context.Execute(continuation))
                {
                    Assert.IsNotNull(entity.ColStream.EditLink, "ColStream should not be null");
                    Assert.AreEqual(entity.ColStream.EditLink, context.GetReadStreamUri(entity, "ColStream"), "the url for the nested collection entity should match - Level 1");
                    foreach (var c1 in entity.Collection1)
                    {
                        Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
                        Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
                    }
                }

                Assert.AreEqual(context.Entities.Count, 4, "there should be 4 entities tracked by the context");
            }

            {
                // 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);
                //context.EnableAtom = true;
                //context.Format.UseAtom();
                var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                        select new
                {
                    ID         = s.ID,
                    Stream1Url = s.Stream1,
                    Collection = (from c in s.Collection
                                  select new
                    {
                        Name = c.Name,
                        Stream1Url = c.ColStream,
                        Collection1 = (from c1 in c.Collection1
                                       select new
                        {
                            ID = c1.ID,
                            Stream1Url = c1.RefStream1
                        })
                    })
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=Name),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                foreach (var o in q)
                {
                    Assert.AreEqual(o.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet1(1)/Stream1", "the stream url for Stream1 must be populated correctly");
                    Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0");
                    Assert.AreEqual(o.Collection.First().Collection1.Single().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url of the collection stream must be populated correctly - index 0 - index 0");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context");
            }
        }