Esempio n. 1
0
        public IList GetBatchObjects(string entityName, CriteriaOperator filter, Dictionary <string, string> properties)
        {
            DataServiceQuery query            = CreateObjectQuery(entityName, filter, properties);
            var batchRequests                 = new DataServiceRequest[] { query };
            DataServiceResponse batchResponse = ServiceContext.ExecuteBatch(batchRequests);


            IList list = null;

            foreach (QueryOperationResponse response in batchResponse)
            {
                // Handle an error response.
                if (response.StatusCode > 299 || response.StatusCode < 200)
                {
                    Console.WriteLine("An error occurred.");
                    Console.WriteLine(response.Error.Message);
                }
                else
                {
                    foreach (var item in response)
                    {
                        if (list == null)
                        {
                            var listType = typeof(List <>).MakeGenericType(item.GetType());
                            list = Activator.CreateInstance(listType) as IList;
                        }
                        list.Add(item);
                    }
                }
            }

            return(list);
        }
Esempio n. 2
0
        private void MaterializeTest(HttpStatusCode statusCode, ODataPayloadKind payloadKind)
        {
            var uri             = new Uri("http://any");
            var context         = new DataServiceContext().ReConfigureForNetworkLoadingTests();
            var requestInfo     = new RequestInfo(context);
            var responseInfo    = new ResponseInfo(requestInfo, MergeOption.OverwriteChanges);
            var queryComponents = new QueryComponents(uri, new Version(4, 0), typeof(Product), null, null);
            var responseMessage = new HttpWebResponseMessage(
                new HeaderCollection(),
                (int)statusCode,
                () => new MemoryStream());
            var materialize = DataServiceRequest.Materialize(
                responseInfo,
                queryComponents,
                null,
                "application/json",
                responseMessage,
                payloadKind);

            Assert.IsNull(materialize.Context);
            Assert.IsNull(materialize.Current);
            var enumerable = materialize.Cast <object>();

            Assert.AreEqual(0, enumerable.Count());
        }
Esempio n. 3
0
 /// <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 void QueryEntityInstanceBatchAsync()
        {
            this.RunOnAtomAndJsonFormats(
                this.CreateContext,
                (contextWrapper) =>
            {
                contextWrapper.Context.IgnoreMissingProperties = true;

                contextWrapper.Configurations.ResponsePipeline
                .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
                .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
                .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

                DataServiceRequest[] requests = new DataServiceRequest[] {
                    contextWrapper.CreateQuery <Person>("Person(-10)"),
                    contextWrapper.CreateQuery <Customer>("Customer"),
                };

                DataServiceResponse responses = null;
                IAsyncResult r = contextWrapper.BeginExecuteBatch(
                    result =>
                {
                    responses = contextWrapper.EndExecuteBatch(result);
                },
                    null,
                    requests);

                while (!r.IsCompleted)
                {
                    Thread.Sleep(1000);
                }

                bool personVerified   = false;
                bool customerVerified = false;
                foreach (QueryOperationResponse response in responses)
                {
                    foreach (object p in response)
                    {
                        SpecialEmployee se1 = p as SpecialEmployee;
                        Customer c          = p as Customer;
                        if (se1 != null)
                        {
                            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", se1.CarsLicensePlate, "Unexpected CarsLicensePlate");
                            Assert.AreEqual(1, se1.BonusLevel, "Unexpected BonusLevel");
                            personVerified = true;
                        }

                        if (c != null)
                        {
                            Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property");
                            Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property");
                            Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property");
                            customerVerified = true;
                        }
                    }
                }

                Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
            });
        }
Esempio n. 5
0
        private static void QueryEntityInstance(DataServiceContextWrapper <DefaultContainer> contextWrapper)
        {
            // contextWrapper.Context.UndeclaredPropertyBehavior = UndeclaredPropertyBehavior.Support;
            contextWrapper.Configurations.ResponsePipeline
            .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
            .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
            .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

            var specialEmployee =
                contextWrapper.CreateQuery <Person>("Person").Where(p => p.PersonId == -10).Single() as SpecialEmployee;
            EntityDescriptor descriptor = contextWrapper.GetEntityDescriptor(specialEmployee);

            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            specialEmployee = contextWrapper.Execute <SpecialEmployee>(new Uri("Person(-10)", UriKind.Relative)).Single();
            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            DataServiceRequest[] requests = new DataServiceRequest[]
            {
                contextWrapper.CreateQuery <Person>("Person"),
                contextWrapper.CreateQuery <Customer>("Customer"),
            };

            DataServiceResponse responses = contextWrapper.ExecuteBatch(requests);
            bool personVerified           = false;
            bool customerVerified         = false;

            foreach (QueryOperationResponse response in responses)
            {
                foreach (object p in response)
                {
                    var      specialEmployee1 = p as SpecialEmployee;
                    Customer c = p as Customer;
                    if (specialEmployee1 != null)
                    {
                        Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee1.CarsLicensePlate,
                                        "Unexpected CarsLicensePlate");
                        Assert.AreEqual(1, specialEmployee1.BonusLevel, "Unexpected BonusLevel");
                        personVerified = true;
                    }

                    if (c != null)
                    {
                        Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected primitive property");
                        Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected complex property");
                        Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected collection property");
                        customerVerified = true;
                    }
                }
            }

            Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
        }
        bool GenerateSecurityToken()
        {
            if (securityToken != string.Empty)
            {
                return(true);
            }

            securityToken = string.Empty;
            Uri uri = new Uri("GenerateSecurityToken", UriKind.Relative);

            DataServiceRequest <string> loginRequest = new DataServiceRequest <string>(uri);
            var loginResponse = sldDataServiceContext.ExecuteBatch(loginRequest);
            QueryOperationResponse <string> queryOperationResponse = loginResponse.FirstOrDefault() as QueryOperationResponse <string>;

            if (queryOperationResponse == null)
            {
                return(false);
            }

            string token = queryOperationResponse.FirstOrDefault();

            if (token == null)
            {
                return(false);
            }

            securityToken = token;

            return(true);
        }
Esempio n. 7
0
        public void SingletonQueryInBatchTest()
        {
            var serviceRoot   = this.BaseAddress + "/clientTest/";
            var ClientContext = new Client.Container(new Uri(serviceRoot));

            // Reset data source
            ClientContext.Execute(new Uri(serviceRoot + "Umbrella/WebStack.QA.Test.OData.Singleton.ResetDataSource"), "POST");
            ClientContext.Execute(new Uri(serviceRoot + "Partners/WebStack.QA.Test.OData.Singleton.ResetDataSource"),
                                  "POST");

            DataServiceRequest[] requests = new DataServiceRequest[] {
                ClientContext.CreateSingletonQuery <Client.Company>("Umbrella"),
                ClientContext.CreateQuery <Client.Partner>("Partners")
            };

            DataServiceResponse responses = ClientContext.ExecuteBatch(requests);

            foreach (var response in responses)
            {
                var companyResponse = response as QueryOperationResponse <Client.Company>;
                var partnerResponse = response as QueryOperationResponse <Client.Partner>;

                if (companyResponse != null)
                {
                    Assert.Equal("Umbrella", companyResponse.Single().Name);
                }

                if (partnerResponse != null)
                {
                    Assert.Equal(10, partnerResponse.ToArray().Count());
                }
            }
        }
Esempio n. 8
0
            public void QueryFailureUsingExecuteBatch()
            {
                DataServiceRequest <northwindClient.Customers> request  = new DataServiceRequest <northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('QUICK')"));
                DataServiceRequest <northwindClient.Customers> request1 = new DataServiceRequest <northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('NONEXIST')"));
                DataServiceResponse response = ctx.ExecuteBatch(request, request1);

                Utils.IsBatchResponse(response);

                List <QueryOperationResponse> responses = new List <QueryOperationResponse>();

                foreach (QueryOperationResponse queryResponse in response)
                {
                    responses.Add(queryResponse);
                }

                Assert.IsTrue(responses.Count == 2, "expecting 2 responses in batch query");

                // first one to succeed
                Utils.IsSuccessResponse(responses[0], HttpStatusCode.OK);
                Assert.IsTrue(responses[0].Query == request, "expecting the same request object");

                // expecting the second one to fail
                Utils.IsErrorResponse(responses[1], HttpStatusCode.NotFound, true);
                Assert.IsTrue(responses[1].Query == request1, "expecting the same request object1");
            }
Esempio n. 9
0
        public void CanBatchQueriesWithDataServicesClient()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/UnbufferedBatch");

            UnbufferedBatchProxy.Container client = new UnbufferedBatchProxy.Container(serviceUrl);
            client.Format.UseJson();
            Uri customersRequestUri = new Uri(BaseAddress + "/UnbufferedBatch/UnbufferedBatchCustomer");
            DataServiceRequest <UnbufferedBatchProxy.UnbufferedBatchCustomer> customersRequest = new DataServiceRequest <UnbufferedBatchProxy.UnbufferedBatchCustomer>(customersRequestUri);
            Uri singleCustomerRequestUri = new Uri(BaseAddress + "/UnbufferedBatch/UnbufferedBatchCustomer(0)");
            DataServiceRequest <UnbufferedBatchProxy.UnbufferedBatchCustomer> singleCustomerRequest = new DataServiceRequest <UnbufferedBatchProxy.UnbufferedBatchCustomer>(singleCustomerRequestUri);

            DataServiceResponse batchResponse = client.ExecuteBatchAsync(customersRequest, singleCustomerRequest).Result;

            if (batchResponse.IsBatchResponse)
            {
                Assert.Equal(200, batchResponse.BatchStatusCode);
            }

            foreach (QueryOperationResponse response in batchResponse)
            {
                Assert.Equal(200, response.StatusCode);
                if (response.Query.RequestUri == customersRequestUri)
                {
                    Assert.Equal(10, response.Cast <UnbufferedBatchProxy.UnbufferedBatchCustomer>().Count());
                    continue;
                }
                if (response.Query.RequestUri == singleCustomerRequestUri)
                {
                    Assert.Equal(1, response.Cast <UnbufferedBatchProxy.UnbufferedBatchCustomer>().Count());
                    continue;
                }
            }
        }
Esempio n. 10
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];
 }
Esempio n. 11
0
        public async Task CanBatchQueriesWithDataServicesClient()
        {
            Uri serviceUrl = new Uri(BaseAddress + "/DefaultBatch");

            DefaultBatchProxy.Container client = new DefaultBatchProxy.Container(serviceUrl);
            client.Format.UseJson();
            Uri customersRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer");
            DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer> customersRequest = new DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer>(customersRequestUri);
            Uri singleCustomerRequestUri = new Uri(BaseAddress + "/DefaultBatch/DefaultBatchCustomer(0)");
            DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer> singleCustomerRequest = new DataServiceRequest <DefaultBatchProxy.DefaultBatchCustomer>(singleCustomerRequestUri);

            DataServiceResponse batchResponse = await client.ExecuteBatchAsync(customersRequest, singleCustomerRequest);

            if (batchResponse.IsBatchResponse)
            {
                Assert.Equal(200, batchResponse.BatchStatusCode);
            }

            foreach (QueryOperationResponse response in batchResponse)
            {
                Assert.Equal(200, response.StatusCode);
                if (response.Query.RequestUri == customersRequestUri)
                {
                    // Previous test could modify the total count to be anywhere from, 10 to 14.
                    Assert.InRange(response.Cast <DefaultBatchProxy.DefaultBatchCustomer>().Count(), 10, 14);
                    continue;
                }
                if (response.Query.RequestUri == singleCustomerRequestUri)
                {
                    Assert.Single(response.Cast <DefaultBatchProxy.DefaultBatchCustomer>());
                    continue;
                }
            }
        }
        private static object HandleQueryResponse(DataServiceResponse response, DataServiceRequest query, DataServiceContext context)
        {
            if ((int)HttpStatusCode.Accepted == response.BatchStatusCode)
            {
                // Assert.IsFalse(response.HasErrors, "response.HasErrors should be false (" + DescribeErrors(response) + ")");
                QueryOperationResponse queryResponse = (QueryOperationResponse)response.First <OperationResponse>();
                if (queryResponse.Error != null)
                {
                    Assert.IsNotNull(queryResponse.Headers);
                }

                try
                {
                    Assert.AreEqual(200, queryResponse.StatusCode);
                    return(queryResponse);
                }
                catch (AssertFailedException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    Assert.IsTrue(queryResponse.Error != null, "expected HasErrors: {0}", e);
                    throw;
                }
            }
            else
            {
                QueryOperationResponse queryResponse = (QueryOperationResponse)response.First <OperationResponse>();
                Assert.AreEqual(200, queryResponse.StatusCode);
                Assert.IsTrue(queryResponse.Error != null);

                throw new WebException("batch query failed", WebExceptionStatus.ProtocolError);
            }
        }
Esempio n. 13
0
 /// <summary>constructor</summary>
 /// <param name="source">source object of async request</param>
 /// <param name="method">async method name on source object</param>
 /// <param name="serviceRequest">Originating serviceRequest</param>
 /// <param name="request">Originating WebRequest</param>
 /// <param name="requestInfo">The request info of the originating request.</param>
 /// <param name="callback">user callback</param>
 /// <param name="state">user state</param>
 internal QueryResult(object source, string method, DataServiceRequest serviceRequest, ODataRequestMessageWrapper request, RequestInfo requestInfo, AsyncCallback callback, object state)
     : base(source, method, callback, state)
 {
     Debug.Assert(request != null, "null request");
     this.ServiceRequest = serviceRequest;
     this.Request        = request;
     this.RequestInfo    = requestInfo;
     this.Abortable      = request;
 }
Esempio n. 14
0
        private static async Task BatchRequestsQueries(Container dsc, Uri serviceUri)
        {
            Uri usersUri = new Uri(serviceUri.AbsoluteUri + "/users");
            Uri booksUri = new Uri(serviceUri.AbsoluteUri + "/books");

            DataServiceRequest <User> usersQuery = new DataServiceRequest <User>(usersUri);
            DataServiceRequest <Book> booksQuery = new DataServiceRequest <Book>(booksUri);

            DataServiceRequest[] batchRequests = new DataServiceRequest[] { usersQuery, booksQuery };

            DataServiceResponse batchResponse;

            try
            {
                batchResponse = await dsc.ExecuteBatchAsync(batchRequests);

                Console.WriteLine($"Is batch response: {batchResponse.IsBatchResponse}");

                foreach (QueryOperationResponse response in batchResponse)
                {
                    if (response.StatusCode < 200 || response.StatusCode > 299)
                    {
                        Console.WriteLine($"Error Message : {response.Error.Message} Status Code: {response.StatusCode}");
                    }
                    else
                    {
                        if (response.Query.ElementType == typeof(User))
                        {
                            foreach (User user in response)
                            {
                                Console.WriteLine($"User: {user.Name}");
                            }
                        }
                        else if (response.Query.ElementType == typeof(Book))
                        {
                            foreach (Book book in response)
                            {
                                Console.WriteLine($"Book: {book.Title}");
                            }
                        }
                    }
                }
            }
            catch (DataServiceRequestException ex)
            {
                batchResponse = ex.Response;
                foreach (QueryOperationResponse response in batchResponse)
                {
                    if (response.Error != null)
                    {
                        Console.WriteLine("An error occurred.");
                        Console.WriteLine(response);
                    }
                }
            }
        }
            public override object GetResults(IAsyncResult async)
            {
                object[]           state   = (object[])async.AsyncState;
                DataServiceRequest query   = (DataServiceRequest)state[0];
                DataServiceContext context = (DataServiceContext)state[1];

                DataServiceResponse response = context.EndExecuteBatch(async);

                return(HandleQueryResponse(response, query, context));
            }
Esempio n. 16
0
        public IEnumerable <T> ExecuteBatch <T>(DataServiceRequest request)
        {
#if NETFRAMEWORK
            return(_context.ExecuteBatch(request)
                   .Cast <QueryOperationResponse>()
                   .SelectMany(o => o.Cast <T>()));
#else
            throw new Exception("not ported");
#endif
        }
Esempio n. 17
0
        /// <summary>
        /// Synchronously executes the query and returns the value.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="parseQueryResultFunc">A function to process the query result.</param>
        /// <returns>The query result</returns>
        internal TElement GetValue <TElement>(DataServiceContext context, Func <QueryResult, TElement> parseQueryResultFunc)
        {
            Debug.Assert(context != null, "context is null");
            QueryComponents queryComponents = this.QueryComponents(context.Model);
            Version         requestVersion  = queryComponents.Version;

            if (requestVersion == null)
            {
                requestVersion = Util.ODataVersion4;
            }

            Uri requestUri = queryComponents.Uri;
            DataServiceRequest <TElement> serviceRequest = new DataServiceRequest <TElement>(requestUri, queryComponents, null);

            HeaderCollection headers = new HeaderCollection();

            // Validate and set the request DSV header
            headers.SetRequestVersion(requestVersion, context.MaxProtocolVersionAsVersion);
            context.Format.SetRequestAcceptHeaderForCount(headers);

            string httpMethod = XmlConstants.HttpMethodGet;
            ODataRequestMessageWrapper request = context.CreateODataRequestMessage(
                context.CreateRequestArgsAndFireBuildingRequest(httpMethod, requestUri, headers, context.HttpStack, null /*descriptor*/),
                null /*descriptor*/);

            QueryResult queryResult = new QueryResult(this, Util.ExecuteMethodName, serviceRequest, request, new RequestInfo(context), null, null);

            try
            {
                queryResult.ExecuteQuery();

                if (HttpStatusCode.NoContent != queryResult.StatusCode)
                {
                    TElement parsedResult = parseQueryResultFunc(queryResult);

                    return(parsedResult);
                }
                else
                {
                    throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetValue, queryResult.Failure);
                }
            }
            catch (InvalidOperationException ex)
            {
                QueryOperationResponse operationResponse;
                operationResponse = queryResult.GetResponse <TElement>(MaterializeAtom.EmptyResults);
                if (operationResponse != null)
                {
                    operationResponse.Error = ex;
                    throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
                }

                throw;
            }
        }
Esempio n. 18
0
 /// <summary>Ends an asynchronous query request to a data service.</summary>
 /// <returns>Returns an <see cref="System.Collections.Generic.IEnumerable{T}" />  that contains the results of the query operation.</returns>
 /// <param name="asyncResult">The pending asynchronous query request.</param>
 /// <exception cref="Microsoft.OData.Client.DataServiceQueryException">When the data service returns an HTTP 404: Resource Not Found error.</exception>
 public virtual new IEnumerable <TElement> EndExecute(IAsyncResult asyncResult)
 {
     if (this.IsFunction)
     {
         return(this.Context.EndExecute <TElement>(asyncResult));
     }
     else
     {
         return(DataServiceRequest.EndExecute <TElement>(this, this.Context, Util.ExecuteMethodName, asyncResult));
     }
 }
Esempio n. 19
0
        public object Execute(Expression expression)
        {
            DataServiceRequest request = _query.GetRequest(expression);

            if (_query.RequiresBatch(expression))
            {
                return(_context.ExecuteBatch <object>(request).FirstOrDefault());
            }

            return(_query.Execute(expression));
        }
Esempio n. 20
0
        public IEnumerator <T> GetEnumerator()
        {
            DataServiceRequest request = _query.GetRequest(Expression);

            if (_query.RequiresBatch(Expression))
            {
                return(_context.ExecuteBatch <T>(request).GetEnumerator());
            }

            return(_query.CreateQuery <T>(Expression).GetEnumerator());
        }
        public void ClientShouldRequestAllMetadataWithProjectionInBatchExecute()
        {
            RunClientIntegrationTestWithBothTrackingAndNoTracking(ctx =>
            {
                var requests = new DataServiceRequest[]
                {
                    new DataServiceRequest <Order>(new Uri("/Orders(1)?$select=DollarAmount,CurrencyAmount", UriKind.Relative)),
                    new DataServiceRequest <Customer>(new Uri("/Customers(1)?$select=ID,GuidValue", UriKind.Relative)),
                };

                ctx.ExecuteBatch(requests);
            });
        }
        private bool LoginIntoSLD(string URL, string SLDUsername, string SLDPassword)
        {
            lock (this)
            {
                try
                {
                    cookies = new CookieContainer();
                    sldDataServiceContext = new DataServiceContext(new Uri(URL));

                    sldDataServiceContext.SendingRequest         += new EventHandler <SendingRequestEventArgs>(sldDataServiceContext_SendingRequest);
                    sldDataServiceContext.IgnoreMissingProperties = true;

                    string strLogonCmd = string.Empty;

                    string tempUser     = System.Web.HttpUtility.UrlEncode(SLDUsername, System.Text.Encoding.UTF8);
                    string tempPassword = System.Web.HttpUtility.UrlEncode(SLDPassword, System.Text.Encoding.UTF8);
                    strLogonCmd = string.Format("LogonByNamedUser?Account='{0}'&Password='******'", tempUser, tempPassword);
                    Uri uri = new Uri(strLogonCmd, UriKind.Relative);

                    DataServiceRequest <bool> loginRequest = new DataServiceRequest <bool>(uri);
                    var loginResponse = sldDataServiceContext.ExecuteBatch(loginRequest);

                    foreach (var response in loginResponse)
                    {
                        var queryOperationResponse = response as QueryOperationResponse <bool>;
                        if (queryOperationResponse == null || !queryOperationResponse.FirstOrDefault())
                        {
                            return(false);
                        }
                    }
                }
                catch
                {
                    throw;
                }

                try
                {
                    if (!GenerateSecurityToken())
                    {
                        return(false);
                    }
                }
                catch
                {
                    throw;
                }

                return(true);
            }
        }
Esempio n. 23
0
        public void BatchSample001()
        {
            DataServiceRequest  queryItems    = new DataServiceRequest <Item>(new Uri($"{urlSl}Items('A00001')"));
            DataServiceResponse batchResponse = serviceContainer.ExecuteBatch(new DataServiceRequest[] { queryItems });

            foreach (QueryOperationResponse response in batchResponse)
            {
                if (response.StatusCode > 299 || response.StatusCode < 200)
                {
                    throw new Exception($"An error ocurred: {response.Error.Message}");
                }
                Console.WriteLine($"Item: {JsonConvert.SerializeObject(response.OfType<Item>().Single())}");
            }
        }
            public override object GetResults(IAsyncResult async)
            {
                object[]           state   = (object[])async.AsyncState;
                DataServiceRequest query   = (DataServiceRequest)state[0];
                DataServiceContext context = (DataServiceContext)state[1];

                Assert.IsTrue(async.IsCompleted);
                if (query is DataServiceQuery)
                {
                    return(UnitTestCodeGen.InvokeMethod(query.GetType(), "EndExecute", TypesIAsyncResult, null, query, new object[] { async }));
                }
                else
                {
                    return(UnitTestCodeGen.InvokeMethod(typeof(DataServiceContext), "EndExecute", TypesIAsyncResult, new Type[] { query.ElementType }, context, new object[] { async }));
                }
            }
Esempio n. 25
0
        internal BaseSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state)
            : base(context, method, callback, state)
        {
            this.RequestInfo = new RequestInfo(context);
            this.Options = options;
            this.SerializerInstance = new Serializer(this.RequestInfo, options);

            if (null == queries)
            {
                #region changed entries
                this.ChangedEntries = context.EntityTracker.Entities.Cast<Descriptor>()
                                      .Union(context.EntityTracker.Links.Cast<Descriptor>())
                                      .Union(context.EntityTracker.Entities.SelectMany(e => e.StreamDescriptors).Cast<Descriptor>())
                                      .Where(o => o.IsModified && o.ChangeOrder != UInt32.MaxValue)
                                      .OrderBy(o => o.ChangeOrder)
                                      .ToList();

                foreach (Descriptor e in this.ChangedEntries)
                {
                    e.ContentGeneratedForSave = false;
                    e.SaveResultWasProcessed = 0;
                    e.SaveError = null;

                    if (e.DescriptorKind == DescriptorKind.Link)
                    {
                        object target = ((LinkDescriptor)e).Target;
                        if (null != target)
                        {
                            Descriptor f = context.EntityTracker.GetEntityDescriptor(target);
                            if (EntityStates.Unchanged == f.State)
                            {
                                f.ContentGeneratedForSave = false;
                                f.SaveResultWasProcessed = 0;
                                f.SaveError = null;
                            }
                        }
                    }
                }
                #endregion
            }
            else
            {
                this.ChangedEntries = new List<Descriptor>();
            }
        }
Esempio n. 26
0
            public void QueryRowCountBatchRequest()
            {
                DataServiceRequest[] queries = new DataServiceRequest[] {
                    (DataServiceRequest)(from c in ctx.CreateQuery <northwindClient.Customers>("Customers").IncludeTotalCount() select c).Take(1),
                    (DataServiceRequest)(from c in ctx.CreateQuery <northwindClient.Customers>("Customers").IncludeTotalCount().Where(c => c.ContactTitle == "Owner") select c).Take(1),
                    (DataServiceRequest)(from c in ctx.CreateQuery <northwindClient.Orders>("Orders").IncludeTotalCount().Expand("Order_Details") select c).Take(1),
                    (DataServiceRequest)(ctx.CreateQuery <northwindClient.Customers>("Customers").IncludeTotalCount().Where(c => c.CustomerID == "QUICK").SelectMany(c => c.Orders)).Take(1)
                };

                DataServiceResponse response = ctx.ExecuteBatch(queries);

                Utils.IsBatchResponse(response);

                foreach (QueryOperationResponse r in response)
                {
                    long count = r.TotalCount;
                    Assert.IsTrue(count > 0);
                }
            }
Esempio n. 27
0
        public void BatchRequest()
        {
            var context = this.CreateWrappedContext <DefaultContainer>();

            //Setup queries
            DataServiceRequest[] reqs = new DataServiceRequest[] {
                context.CreateQuery <Customer>("BatchRequest1"),
                context.CreateQuery <Person>("BatchRequest2"),
            };

            var response = context.ExecuteBatch(reqs);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.IsBatchResponse);
            foreach (var item in response)
            {
                Assert.IsTrue(item.StatusCode == 200);
            }
        }
Esempio n. 28
0
        [Ignore]  // there is not feed id when using json format.
        public void ErrorResponseTest()
        {
            DataServiceContextWrapper <DefaultContainer> contextWrapper = this.CreateWrappedContext <DefaultContainer>();

            //contextWrapper.Format.UseAtom();
            contextWrapper.Configurations.ResponsePipeline
            .OnFeedStarted(this.SetOnCustomerFeedStartedCalled)
            .OnEntryStarted(this.SetOnCustomerEntryStartedCalled);

            // regular error response
            this.ResetDelegateFlags();
            this.Throws <Exception>(() => contextWrapper.Execute <Customer>(new Uri("Customer(1234)", UriKind.Relative)).Single());
            Assert.IsFalse(OnCustomerEntryStartedCalled, "Unexpected OnEntryEndedCalled");

            // inner response error in a batch
            DataServiceRequest[] requests = new DataServiceRequest[] {
                contextWrapper.CreateQuery <Order>("Order"),
                contextWrapper.CreateQuery <Customer>("Customer(-1234)"),
            };
            this.ResetDelegateFlags();
            this.Throws <Exception>(() =>
            {
                DataServiceResponse responses = contextWrapper.ExecuteBatch(requests);
                foreach (QueryOperationResponse response in responses)
                {
                    foreach (object p in response)
                    {
                    }
                }
            });
            Assert.IsFalse(OnCustomerFeedStartedCalled, "Unexpected OnCustomerFeedStartedCalled");
            Assert.IsFalse(OnCustomerEntryStartedCalled, "Unexpected OnEntryEndedCalled");
            Assert.IsTrue(OnOrderFeedStartedCalled, "Unexpected OnOrderFeedStartedCalled");
            Assert.IsTrue(OnOrderEntryStartedCalled, "Unexpected OnOrderEntryStartedCalled");

            // in-stream error in response
            this.ResetDelegateFlags();
            this.Throws <Exception>(() => contextWrapper.Execute <Customer>(new Uri("InStreamErrorGetCustomer", UriKind.Relative)).ToArray());
            Assert.IsTrue(OnCustomerFeedStartedCalled, "Unexpected OnCustomerFeedStartedCalled");
            Assert.IsTrue(OnCustomerEntryStartedCalled, "Unexpected OnEntryEndedCalled");
        }
Esempio n. 29
0
        public void BatchRequestBaseUriDifferentBetweenBatchAndRequest()
        {
            var context = this.CreateWrappedContext <DefaultContainer>();

            //Setup queries
            DataServiceRequest[] reqs = new DataServiceRequest[] {
                context.CreateQuery <Customer>("BatchRequest3"),
            };

            var response = context.ExecuteBatch(reqs);

            Assert.IsNotNull(response);
            Assert.IsTrue(response.IsBatchResponse);
            foreach (QueryOperationResponse item in response)
            {
                Assert.IsNotNull(item.Error);

                Assert.IsInstanceOfType(item.Error, typeof(DataServiceClientException), "Unexpected inner exception type");
                var ex = item.Error as DataServiceClientException;
                StringResourceUtil.VerifyDataServicesString(ClientExceptionUtil.ExtractServerErrorMessage(item), "DataServiceOperationContext_CannotModifyServiceUriInsideBatch");
            }
        }
Esempio n. 30
0
 internal BaseSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state) : base(context, method, callback, state)
 {
     this.entryIndex = -1;
     this.RequestInfo = new System.Data.Services.Client.RequestInfo(context);
     this.Options = options;
     this.SerializerInstance = new Serializer(this.RequestInfo);
     if (queries == null)
     {
         this.ChangedEntries = (from o in context.EntityTracker.Entities.Cast<Descriptor>().Union<Descriptor>(context.EntityTracker.Links.Cast<Descriptor>()).Union<Descriptor>((from e in context.EntityTracker.Entities select e.StreamDescriptors).Cast<Descriptor>())
             where o.IsModified && (o.ChangeOrder != uint.MaxValue)
             orderby o.ChangeOrder
             select o).ToList<Descriptor>();
         foreach (Descriptor descriptor in this.ChangedEntries)
         {
             descriptor.ContentGeneratedForSave = false;
             descriptor.SaveResultWasProcessed = 0;
             descriptor.SaveError = null;
             if (descriptor.DescriptorKind == DescriptorKind.Link)
             {
                 object target = ((LinkDescriptor) descriptor).Target;
                 if (target != null)
                 {
                     Descriptor entityDescriptor = context.EntityTracker.GetEntityDescriptor(target);
                     if (EntityStates.Unchanged == entityDescriptor.State)
                     {
                         entityDescriptor.ContentGeneratedForSave = false;
                         entityDescriptor.SaveResultWasProcessed = 0;
                         entityDescriptor.SaveError = null;
                     }
                 }
             }
         }
     }
     else
     {
         this.ChangedEntries = new List<Descriptor>();
     }
 }
Esempio n. 31
0
        /// <summary>
        /// execute uri and materialize result
        /// </summary>
        /// <typeparam name="TElement">element type</typeparam>
        /// <param name="context">context</param>
        /// <param name="queryComponents">query components for request to execute</param>
        /// <returns>enumerable of results</returns>
        internal QueryOperationResponse <TElement> Execute <TElement>(DataServiceContext context, QueryComponents queryComponents)
        {
            QueryResult result = null;

            try
            {
                Uri requestUri = queryComponents.Uri;
                DataServiceRequest <TElement> serviceRequest = new DataServiceRequest <TElement>(requestUri, queryComponents, this.Plan);
                result = serviceRequest.CreateExecuteResult(this, context, null, null, Util.ExecuteMethodName);
                result.ExecuteQuery();
                return(result.ProcessResult <TElement>(this.Plan));
            }
            catch (InvalidOperationException ex)
            {
                if (result != null)
                {
                    QueryOperationResponse operationResponse = result.GetResponse <TElement>(MaterializeAtom.EmptyResults);

                    if (operationResponse != null)
                    {
                        if (context.IgnoreResourceNotFoundException)
                        {
                            DataServiceClientException cex = ex as DataServiceClientException;
                            if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
                            {
                                // don't throw
                                return((QueryOperationResponse <TElement>)operationResponse);
                            }
                        }

                        operationResponse.Error = ex;
                        throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
                    }
                }

                throw;
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Creates an instance of <see cref="MaterializeAtom"/> for the given plan.
        /// </summary>
        /// <param name="plan">The projection plan.</param>
        /// <param name="payloadKind">expected payload kind.</param>
        /// <returns>A new materializer instance</returns>
        private MaterializeAtom CreateMaterializer(ProjectionPlan plan, ODataPayloadKind payloadKind)
        {
            QueryComponents queryComponents = this.ServiceRequest.QueryComponents(this.responseInfo.Model);

            // In V2, in projection path, we did not check for assignability between the expected type and the type returned by the type resolver.
            if (plan != null || queryComponents.Projection != null)
            {
                this.RequestInfo.TypeResolver.IsProjectionRequest();
            }

            var responseMessageWrapper = new HttpWebResponseMessage(
                new HeaderCollection(this.responseMessage),
                this.responseMessage.StatusCode,
                this.GetResponseStream);

            return(DataServiceRequest.Materialize(
                       this.responseInfo,
                       queryComponents,
                       plan,
                       this.ContentType,
                       responseMessageWrapper,
                       payloadKind));
        }
Esempio n. 33
0
        public void BatchRequest()
        {
            var context = this.CreateWrappedContext<DefaultContainer>();
            //Setup queries
            DataServiceRequest[] reqs = new DataServiceRequest[] {
                context.CreateQuery<Customer>("BatchRequest1"),
                context.CreateQuery<Person>("BatchRequest2"),
            };

            var response = context.ExecuteBatch(reqs);
            Assert.IsNotNull(response);
            Assert.IsTrue(response.IsBatchResponse);
            foreach (var item in response)
            {
                Assert.IsTrue(item.StatusCode == 200);
            }
        }
Esempio n. 34
0
        public void SingletonQueryInBatchTest()
        {
            var serviceRoot = this.BaseAddress + "/clientTest/";
            var ClientContext = new Client.Container(new Uri(serviceRoot));

            // Reset data source
            ClientContext.Execute(new Uri(serviceRoot + "Umbrella/WebStack.QA.Test.OData.Singleton.ResetDataSource"), "POST");
            ClientContext.Execute(new Uri(serviceRoot + "Partners/WebStack.QA.Test.OData.Singleton.ResetDataSource"),
                                  "POST");

            DataServiceRequest[] requests = new DataServiceRequest[] {
                        ClientContext.CreateSingletonQuery<Client.Company>("Umbrella"),
                        ClientContext.CreateQuery<Client.Partner>("Partners")
            };

            DataServiceResponse responses = ClientContext.ExecuteBatch(requests);

            foreach (var response in responses)
            {
                var companyResponse = response as QueryOperationResponse<Client.Company>;
                var partnerResponse = response as QueryOperationResponse<Client.Partner>;

                if (companyResponse != null)
                {
                    Assert.Equal("Umbrella", companyResponse.Single().Name);
                }

                if (partnerResponse != null)
                {
                    Assert.Equal(10, partnerResponse.ToArray().Count());
                }
            }
        }
Esempio n. 35
0
            public void QueryFailureUsingExecuteBatch()
            {
                DataServiceRequest<northwindClient.Customers> request = new DataServiceRequest<northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('QUICK')"));
                DataServiceRequest<northwindClient.Customers> request1 = new DataServiceRequest<northwindClient.Customers>(new Uri(ctx.BaseUri.OriginalString + "/Customers('NONEXIST')"));
                DataServiceResponse response = ctx.ExecuteBatch(request, request1);
                Utils.IsBatchResponse(response);

                List<QueryOperationResponse> responses = new List<QueryOperationResponse>();
                foreach (QueryOperationResponse queryResponse in response)
                {
                    responses.Add(queryResponse);
                }

                Assert.IsTrue(responses.Count == 2, "expecting 2 responses in batch query");

                // first one to succeed
                Utils.IsSuccessResponse(responses[0], HttpStatusCode.OK);
                Assert.IsTrue(responses[0].Query == request, "expecting the same request object");

                // expecting the second one to fail
                Utils.IsErrorResponse(responses[1], HttpStatusCode.NotFound, true);
                Assert.IsTrue(responses[1].Query == request1, "expecting the same request object1");
            }
Esempio n. 36
0
 internal static BaseSaveResult CreateSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state)
 {
     if ((options & SaveChangesOptions.Batch) != SaveChangesOptions.Batch)
     {
         return new SaveResult(context, method, options, callback, state);
     }
     return new BatchSaveResult(context, method, queries, options, callback, state);
 }
Esempio n. 37
0
        public void BatchRequestBaseUriDifferentBetweenBatchAndRequest()
        {
            var context = this.CreateWrappedContext<DefaultContainer>();

            //Setup queries
            DataServiceRequest[] reqs = new DataServiceRequest[] {
                context.CreateQuery<Customer>("BatchRequest3"),
            };

            var response = context.ExecuteBatch(reqs);
            Assert.IsNotNull(response);
            Assert.IsTrue(response.IsBatchResponse);
            foreach (QueryOperationResponse item in response)
            {
                Assert.IsNotNull(item.Error);

                Assert.IsInstanceOfType(item.Error, typeof(DataServiceClientException), "Unexpected inner exception type");
                var ex = item.Error as DataServiceClientException;
                StringResourceUtil.VerifyDataServicesString(ClientExceptionUtil.ExtractServerErrorMessage(item), "DataServiceOperationContext_CannotModifyServiceUriInsideBatch");
            }
        }
Esempio n. 38
0
            public void QueryRowCountBatchRequest()
            {
                DataServiceRequest[] queries = new DataServiceRequest[] {
                        (DataServiceRequest)(from c in ctx.CreateQuery<northwindClient.Customers>("Customers").IncludeTotalCount() select c).Take(1),
                        (DataServiceRequest)(from c in ctx.CreateQuery<northwindClient.Customers>("Customers").IncludeTotalCount().Where(c=>c.ContactTitle=="Owner") select c).Take(1),
                        (DataServiceRequest)(from c in ctx.CreateQuery<northwindClient.Orders>("Orders").IncludeTotalCount().Expand("Order_Details") select c).Take(1),
                        (DataServiceRequest)(ctx.CreateQuery<northwindClient.Customers>("Customers").IncludeTotalCount().Where(c=>c.CustomerID=="QUICK").SelectMany(c => c.Orders)).Take(1)
                    };

                DataServiceResponse response = ctx.ExecuteBatch(queries);
                Utils.IsBatchResponse(response);

                foreach (QueryOperationResponse r in response)
                {
                    long count = r.TotalCount;
                    Assert.IsTrue(count > 0);
                }
            }
        public static IEnumerable ExecuteQuery(DataServiceContext context, DataServiceRequest query, QueryMode queryMode)
        {
            bool isQuery = (null != (query as DataServiceQuery));

            object result = null;

            switch (queryMode)
            {
            case QueryMode.GetEnumerator:     // IEnumerable.GetEnumerator
            {
                if (isQuery)
                {
                    result = query;
                }
                else
                {
                    goto case QueryMode.ExecuteMethod;
                }
                break;
            }

            case QueryMode.ExecuteMethod:     // DataServiceQuery<T>.Execute
            {
                if (isQuery)
                {
                    result = UnitTestCodeGen.InvokeMethod(query.GetType(), "Execute", null, null, query, null);
                }
                else
                {
                    result = UnitTestCodeGen.InvokeMethod(typeof(DataServiceContext), "Execute", TypesUri, new Type[] { query.ElementType }, context, query.RequestUri);
                }

                break;
            }

            case QueryMode.AsyncExecute:     // DataServiceQuery<T>.BeginExecute and wait
            {
                if (isQuery)
                {
                    IAsyncResult async = (IAsyncResult)UnitTestCodeGen.InvokeMethod(query.GetType(), "BeginExecute", TypesAsyncCallbackObject, null, query, new object[] { null, null });
                    if (!async.CompletedSynchronously)
                    {
                        Assert.IsTrue(async.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, TestConstants.MaxTestTimeout), false), "BeginExecute timeout");
                    }

                    result = UnitTestCodeGen.InvokeMethod(query.GetType(), "EndExecute", TypesIAsyncResult, null, query, new object[] { async });
                }
                else
                {
                    IAsyncResult async = UnitTestCodeGen.InvokeMethod <DataServiceContext, IAsyncResult>("BeginExecute", TypesUriAsyncCallbackObject, new Type[] { query.ElementType }, context, query.RequestUri, null, null);
                    if (!async.CompletedSynchronously)
                    {
                        Assert.IsTrue(async.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, TestConstants.MaxTestTimeout), false), "BeginExecute timeout");
                    }

                    result = UnitTestCodeGen.InvokeMethod(typeof(DataServiceContext), "EndExecute", TypesIAsyncResult, new Type[] { query.ElementType }, context, async);
                }

                break;
            }

            case QueryMode.AsyncExecuteWithCallback:     // DataServiceQuery<T>.BeginExecute with callback
            {
                ExecuteCallback callback = new ExecuteCallback();
                IAsyncResult    async;
                if (isQuery)
                {
                    async = (IAsyncResult)UnitTestCodeGen.InvokeMethod(query.GetType(), "BeginExecute", TypesAsyncCallbackObject, null, query, new object[] { (AsyncCallback)callback.CallbackMethod, new object[] { query, context } });
                }
                else
                {
                    async = UnitTestCodeGen.InvokeMethod <DataServiceContext, IAsyncResult>("BeginExecute", TypesUriAsyncCallbackObject, new Type[] { query.ElementType }, context, new object[] { query.RequestUri, (AsyncCallback)callback.CallbackMethod, new object[] { query, context } });
                }

                Assert.IsTrue(callback.Finished.WaitOne(new TimeSpan(0, 0, TestConstants.MaxTestTimeout), false), "Asyncallback timeout");
                Assert.IsTrue(async.IsCompleted);

                if (null != callback.CallbackFailure)
                {
                    Assert.IsNull(callback.CallbackResult, callback.CallbackFailure.ToString());
                    throw new Exception("failure in callback", callback.CallbackFailure);
                }

                result = callback.CallbackResult;
                Assert.IsNotNull(result);
                break;
            }

            case QueryMode.BatchExecute:     // DataServiceContext.ExecuteBatch
            {
                LastUriRequest = query.RequestUri;
                int countBefore = context.Entities.Count + context.Links.Count;
                DataServiceResponse response = context.ExecuteBatch(query);
                int countAfter = context.Entities.Count + context.Links.Count;
                Assert.AreEqual(countBefore, countAfter, "should not materialize during ExecuteBatch");
                result = HandleQueryResponse(response, query, context);
            }
            break;

            case QueryMode.BatchAsyncExecute:     // DataServiceContext.BeginExecuteBatch and wait
            {
                int count = context.Entities.Count + context.Links.Count;
                LastUriRequest = query.RequestUri;
                IAsyncResult async = context.BeginExecuteBatch(null, null, query);
                if (!async.CompletedSynchronously)
                {
                    Assert.IsTrue(async.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, TestConstants.MaxTestTimeout), false), "BeginExecuteBatch timeout");
                }

                Assert.AreEqual(count, context.Entities.Count + context.Links.Count, "should not materialize until EndExecuteBatch");
                DataServiceResponse response = context.EndExecuteBatch(async);
                result = HandleQueryResponse(response, query, context);
                break;
            }

            case QueryMode.BatchAsyncExecuteWithCallback:     // DataServiceContext.BeginExecuteBatch with callback
            {
                ExecuteBatchCallback callback = new ExecuteBatchCallback();
                LastUriRequest = query.RequestUri;
                IAsyncResult async = context.BeginExecuteBatch(callback.CallbackMethod, new object[] { query, context }, query);

                Assert.IsTrue(callback.Finished.WaitOne(new TimeSpan(0, 0, TestConstants.MaxTestTimeout), false), "Asyncallback timeout {0}", LastUriRequest);
                Assert.IsTrue(async.IsCompleted);

                if (null != callback.CallbackFailure)
                {
                    Assert.IsNull(callback.CallbackResult, callback.CallbackFailure.ToString());
                    throw new Exception("failure in callback", callback.CallbackFailure);
                }

                result = callback.CallbackResult;
                Assert.IsNotNull(result);
                break;
            }

            default:
                Assert.Fail("shouldn't be here");
                break;
            }

            return((IEnumerable)result);
        }
Esempio n. 40
0
 /// <summary>
 /// factory method for SaveResult
 /// </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>
 /// <returns>a new instance of SaveResult or BatchSaveResult, depending on the options value.</returns>
 internal static BaseSaveResult CreateSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state)
 {
     if (!Util.IsBatch(options))
     {
         Debug.Assert(queries == null, "In non-batch case, queries must be null");
         return new SaveResult(context, method, options, callback, state);
     }
     else
     {
         return new BatchSaveResult(context, method, queries, options, callback, state);
     }
 }
Esempio n. 41
0
 public IEnumerable <T> ExecuteBatch <T>(DataServiceRequest request)
 {
     return(_context.ExecuteBatch(request)
            .Cast <QueryOperationResponse>()
            .SelectMany(o => o.Cast <T>()));
 }
Esempio n. 42
0
 internal BatchSaveResult(DataServiceContext context, string method, DataServiceRequest[] queries, SaveChangesOptions options, AsyncCallback callback, object state) : base(context, method, queries, options, callback, state)
 {
     this.Queries = queries;
     this.streamCopyBuffer = new byte[0xfa0];
 }
        public void QueryEntityInstanceBatchAsync()
        {
            this.RunOnAtomAndJsonFormats(
                this.CreateContext,
                (contextWrapper) =>
                {
                    contextWrapper.Context.IgnoreMissingProperties = true;

                    contextWrapper.Configurations.ResponsePipeline
                        .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
                        .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
                        .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

                    DataServiceRequest[] requests = new DataServiceRequest[] {
                        contextWrapper.CreateQuery<Person>("Person(-10)"),
                        contextWrapper.CreateQuery<Customer>("Customer"),
                    };

                    DataServiceResponse responses = null;
                    IAsyncResult r = contextWrapper.BeginExecuteBatch(
                        result =>
                        {
                            responses = contextWrapper.EndExecuteBatch(result);
                        },
                        null,
                        requests);

                    while (!r.IsCompleted)
                    {
                        Thread.Sleep(1000);
                    }

                    bool personVerified = false;
                    bool customerVerified = false;
                    foreach (QueryOperationResponse response in responses)
                    {
                        foreach (object p in response)
                        {
                            SpecialEmployee se1 = p as SpecialEmployee;
                            Customer c = p as Customer;
                            if (se1 != null)
                            {
                                Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", se1.CarsLicensePlate, "Unexpected CarsLicensePlate");
                                Assert.AreEqual(1, se1.BonusLevel, "Unexpected BonusLevel");
                                personVerified = true;
                            }

                            if (c != null)
                            {
                                Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected primitive property");
                                Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected complex property");
                                Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"), "Unexpected collection property");
                                customerVerified = true;
                            }
                        }
                    }

                    Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
                });
        }