private async Task <List <NorthwindSupplier> > GetAllSupplies()
        {
            DataServiceQueryContinuation <NorthwindSupplier> token = null;
            var query     = this.entities.Suppliers;
            var suppliers = new List <NorthwindSupplier>();

            var result = await Task <IEnumerable <NorthwindSupplier> > .Factory.FromAsync(query.BeginExecute(null, null), (ar) =>
            {
                return(query.EndExecute(ar));
            }) as QueryOperationResponse <NorthwindSupplier>;

            suppliers.AddRange(result);
            token = result.GetContinuation();
            do
            {
                if (token is not null)
                {
                    result = await Task <IEnumerable <NorthwindSupplier> > .Factory.FromAsync(query.BeginExecute(null, null), (ar) =>
                    {
                        return(query.EndExecute(ar));
                    }) as QueryOperationResponse <NorthwindSupplier>;

                    suppliers.AddRange(result);
                }
            }while ((token = result.GetContinuation()) is not null);

            return(suppliers);
        }
Exemple #2
0
        private async static Task <IList> ExecuteQueryAsync <T>(IQueryable query, Expression expression, IReadOnlyList <LambdaExpression> navigationPropertyAccessors)
        {
            var items    = new List <T>();
            var newQuery = (DataServiceQuery <T>)query.Provider.CreateQuery <T>(expression);

            DataServiceQueryContinuation <T> continuation = null;

            for (var response = (QueryOperationResponse <T>) await newQuery.ExecuteAsync(); response != null;
                 continuation = response.GetContinuation(), response = continuation == null ? null : (QueryOperationResponse <T>) await newQuery.Context.ExecuteAsync(continuation))
            {
                foreach (T item in response)
                {
                    foreach (LambdaExpression navigationPropertyAccessor in navigationPropertyAccessors)
                    {
                        var propertyExpression = (MemberExpression)navigationPropertyAccessor.Body;
                        if (((PropertyInfo)propertyExpression.Member).GetValue(item) is IEnumerable property)
                        {
                            DataServiceQueryContinuation itemsContinuation = response.GetContinuation(property);
                            while (itemsContinuation != null)
                            {
                                QueryOperationResponse itemsResponse = await newQuery.Context.LoadPropertyAsync(item, propertyExpression.Member.Name, itemsContinuation);

                                itemsContinuation = itemsResponse.GetContinuation();
                            }
                        }
                    }
                    items.Add(item);
                }
            }

            return(items);
        }
        public IEnumerable LoadPropertyPage(object entity, string propertyName, DataServiceQueryContinuation continuation)
        {
            QueryOperationResponse qoLoadPropResponse = null;

            SocketExceptionHandler.Execute(() => qoLoadPropResponse = this._DataServiceContext.LoadProperty(entity, propertyName, continuation));
            return(new QueryOperationResponseWrapper(qoLoadPropResponse));
        }
Exemple #4
0
 public PagedCollection(DataServiceContextWrapper context,
                        QueryOperationResponse <TConcrete> qor)
 {
     _context      = context;
     _currentPage  = (IReadOnlyList <TElement>)qor.ToList();
     _continuation = qor.GetContinuation();
 }
        public List <Project> GetProjIDs()
        {
            InfBaseModel infBaseModel = new InfBaseModel(uri);

            infBaseModel.SendingRequest2 += OnSendingRequest2;
            QueryOperationResponse <Project> qOR = (infBaseModel.Projects.Select(p => new Project()
            {
                Id = p.Id
            })
                                                    as DataServiceQuery <Project>)
                                                   .Execute() as QueryOperationResponse <Project>;
            DataServiceQueryContinuation <Project> token = null;
            List <Project> projects = new List <Project>();

            do
            {
                if (token != null)
                {
                    qOR = infBaseModel.Execute(token);
                }

                projects.AddRange(qOR);
            }while ((token = qOR.GetContinuation()) != null);

            return(projects);
        }
Exemple #6
0
        private async Task <IEnumerable <ChocolateyPackage> > RetrievePackagesInternal(
            DataServiceQueryContinuation <FeedPackage> query,
            IList <ChocolateyPackage> currentPackages,
            CancellationToken cancellationToken)
        {
            if (query == null || cancellationToken.IsCancellationRequested)
            {
                return(currentPackages);
            }

            var retrievePackagesTask = new TaskFactory(cancellationToken).FromAsync <IEnumerable <FeedPackage> >(
                this._feedClient.BeginExecute <FeedPackage>(query, null, null),
                queryAsyncResult => this._feedClient.EndExecute <FeedPackage>(queryAsyncResult));

            if (cancellationToken.IsCancellationRequested)
            {
                return(currentPackages);
            }

            var installedPackages = await this._installedPackages.RetrieveInstalledPackages();

            var queryOperation = await retrievePackagesTask as QueryOperationResponse <FeedPackage>;

            foreach (var feedPackage in queryOperation)
            {
                currentPackages.Add(ConvertToPackage(feedPackage, installedPackages));
            }

            this.RaisePageOfPackagesLoaded(currentPackages);

            var nextQuery = queryOperation.GetContinuation();

            return(await this.RetrievePackagesInternal(nextQuery, currentPackages, cancellationToken));
        }
        public void LoadPropertyWithNextLink()
        {
            var contextWrapper = this.CreateWrappedContext();

            var response = contextWrapper.Context.Customer.Expand(c => c.Orders).Execute() as QueryOperationResponse <Customer>;
            DataServiceQueryContinuation <Customer> customerContinuation = null;

            do
            {
                if (customerContinuation != null)
                {
                    response = contextWrapper.Execute <Customer>(customerContinuation);
                }

                foreach (var customer in response)
                {
                    DataServiceQueryContinuation <Order> orderContinuation = response.GetContinuation(customer.Orders);

                    while (orderContinuation != null)
                    {
                        var ordersResponse = contextWrapper.LoadProperty(customer, "Orders", orderContinuation);
                        orderContinuation = ordersResponse.GetContinuation();
                    }
                }
            } while ((customerContinuation = response.GetContinuation()) != null);
        }
Exemple #8
0
        public List <Employee> GetEmplIDs()
        {
            InfBaseModel infBaseModel = new InfBaseModel(uri);

            infBaseModel.SendingRequest2 += OnSendingRequest2;
            QueryOperationResponse <Employee> qOR;

            qOR = (infBaseModel.Employees.Select(e => new Employee()
            {
                Id = e.Id
            }) as DataServiceQuery <Employee>)
                  .Execute() as QueryOperationResponse <Employee>;

            DataServiceQueryContinuation <Employee> token = null;
            List <Employee> employees = new List <Employee>();

            do
            {
                if (token != null)
                {
                    qOR = infBaseModel.Execute(token);
                }
                employees.AddRange(qOR);
            } while ((token = qOR.GetContinuation()) != null);

            return(employees);
        }
        private async Task <List <NorthwindProduct> > GetAllProducts()
        {
            DataServiceQueryContinuation <NorthwindProduct> token = null;
            var query    = this.entities.Products;
            var products = new List <NorthwindProduct>();
            var result   = await Task <IEnumerable <NorthwindProduct> > .Factory.FromAsync(query.BeginExecute(null, null), (ar) =>
            {
                return(query.EndExecute(ar));
            }) as QueryOperationResponse <NorthwindProduct>;

            products.AddRange(result);
            token = result.GetContinuation();
            do
            {
                if (token is not null)
                {
                    result = await Task <IEnumerable <NorthwindProduct> > .Factory.FromAsync(this.entities.BeginExecute <NorthwindProduct>(token.NextLinkUri, null, null), (ar) =>
                    {
                        return(this.entities.EndExecute <NorthwindProduct>(ar));
                    }) as QueryOperationResponse <NorthwindProduct>;
                }

                products.AddRange(result);
            }while ((token = result.GetContinuation()) is not null);

            return(products);
        }
Exemple #10
0
        internal static object ProjectionInitializeEntity(ODataEntityMaterializer materializer, MaterializerEntry entry, Type expectedType, Type resultType, string[] properties, Func <object, object, Type, object>[] propertyValues)
        {
            if (entry.Entry == null)
            {
                throw new NullReferenceException(System.Data.Services.Client.Strings.AtomMaterializer_EntryToInitializeIsNull(resultType.FullName));
            }
            if (!entry.EntityHasBeenResolved)
            {
                ProjectionEnsureEntryAvailableOfType(materializer, entry, resultType);
            }
            else if (!resultType.IsAssignableFrom(entry.ActualType.ElementType))
            {
                throw new InvalidOperationException(System.Data.Services.Client.Strings.AtomMaterializer_ProjectEntityTypeMismatch(resultType.FullName, entry.ActualType.ElementType.FullName, entry.Entry.Id));
            }
            object resolvedObject = entry.ResolvedObject;

            for (int i = 0; i < properties.Length; i++)
            {
                StreamDescriptor         descriptor;
                string                   propertyName = properties[i];
                ClientPropertyAnnotation annotation   = entry.ActualType.GetProperty(propertyName, materializer.ResponseInfo.IgnoreMissingProperties);
                object                   target       = propertyValues[i](materializer, entry.Entry, expectedType);
                ODataProperty            property     = (from p in entry.Entry.Properties
                                                         where p.Name == propertyName
                                                         select p).FirstOrDefault <ODataProperty>();
                if ((((((property == null) && (entry.NavigationLinks != null)) ? (from l in entry.NavigationLinks
                                                                                  where l.Name == propertyName
                                                                                  select l).FirstOrDefault <ODataNavigationLink>() : null) != null) || (property != null)) || entry.EntityDescriptor.TryGetNamedStreamInfo(propertyName, out descriptor))
                {
                    if (entry.ShouldUpdateFromPayload && (annotation.EdmProperty.Type.TypeKind() == EdmTypeKind.Entity))
                    {
                        materializer.Log.SetLink(entry, annotation.PropertyName, target);
                    }
                    if (entry.ShouldUpdateFromPayload)
                    {
                        if (!annotation.IsEntityCollection)
                        {
                            if (!annotation.IsPrimitiveOrComplexCollection)
                            {
                                annotation.SetValue(resolvedObject, target, annotation.PropertyName, false);
                            }
                        }
                        else
                        {
                            IEnumerable list = (IEnumerable)target;
                            DataServiceQueryContinuation continuation = materializer.nextLinkTable[list];
                            Uri            nextLink = (continuation == null) ? null : continuation.NextLinkUri;
                            ProjectionPlan plan     = (continuation == null) ? null : continuation.Plan;
                            materializer.MergeLists(entry, annotation, list, nextLink, plan);
                        }
                    }
                    else if (annotation.IsEntityCollection)
                    {
                        materializer.FoundNextLinkForUnmodifiedCollection(annotation.GetValue(entry.ResolvedObject) as IEnumerable);
                    }
                }
            }
            return(resolvedObject);
        }
        /// <summary>
        /// Wrapper entry for the DataServiceContext.Execute method.
        /// </summary>
        /// <typeparam name="TElement">Element type for response.</typeparam>
        /// <param name="continuation">Continuation for query to execute.</param>
        /// <returns>The response for the specified <paramref name="continuation"/>.</returns>
        public QueryOperationResponse <TElement> Execute <TElement>(DataServiceQueryContinuation <TElement> continuation)
        {
#if (NETCOREAPP1_0 || NETCOREAPP2_0)
            throw new NotImplementedException();
#else
            return(this.wrappedInstance.Execute(continuation));
#endif
        }
Exemple #12
0
        public IEnumerable <T> Execute <T>(Type elementType, DataServiceQueryContinuation continuation)
        {
            // Get the generic execute method
            MethodInfo executeMethod = _executeMethodInfo.MakeGenericMethod(elementType);

            // Get the results from the continuation
            return((IEnumerable <T>)executeMethod.Invoke(_context, new object[] { continuation.NextLinkUri }));
        }
        /// <summary>
        /// Wrapper entry for the DataServiceContext.Execute method.
        /// </summary>
        /// <typeparam name="TElement">Element type for response.</typeparam>
        /// <param name="continuation">Continuation for query to execute.</param>
        /// <returns>The response for the specified <paramref name="continuation"/>.</returns>
        public QueryOperationResponse <TElement> Execute <TElement>(DataServiceQueryContinuation <TElement> continuation)
        {
#if SILVERLIGHT || PORTABLELIB
            throw new NotImplementedException();
#else
            return(this.wrappedInstance.Execute(continuation));
#endif
        }
Exemple #14
0
 public PagedCollection(DataServiceContextWrapper context, DataServiceCollection <TConcrete> collection)
 {
     _context     = context;
     _currentPage = (IReadOnlyList <TElement>)collection;
     if (_currentPage != null)
     {
         _continuation = collection.Continuation;
     }
 }
Exemple #15
0
 private void FoundNextLinkForCollection(IEnumerable collection, Uri link, ProjectionPlan plan)
 {
     if ((collection != null) && !base.nextLinkTable.ContainsKey(collection))
     {
         DataServiceQueryContinuation continuation = DataServiceQueryContinuation.Create(link, plan);
         base.nextLinkTable.Add(collection, continuation);
         Util.SetNextLinkForCollection(collection, continuation);
     }
 }
        public IEnumerable ExecuteOfT(Type entityType, DataServiceQueryContinuation continuationToken)
        {
            var             executeMethod      = typeof(DataServiceContext).GetMethods().Where(meth => meth.Name.StartsWith("Execute") && meth.GetParameters().Any(param => param.Name == "continuation")).Single();
            MethodInfo      method             = executeMethod.MakeGenericMethod(entityType);
            ConstructorInfo qorTypeConstructor = typeof(QueryOperationResponseWrapper <>).MakeGenericType(entityType).GetConstructor(new Type[] { typeof(QueryOperationResponse <>).MakeGenericType(entityType) });
            object          qoResponse         = method.Invoke(this._DataServiceContext, new object[] { continuationToken });

            return(qorTypeConstructor.Invoke(new object[] { qoResponse }) as QueryOperationResponseWrapper);
        }
Exemple #17
0
        /// <summary>Records the fact that a rel='next' link was found for the specified <paramref name="collection"/>.</summary>
        /// <param name="collection">Collection to add link to.</param>
        /// <param name="link">Link (possibly null).</param>
        /// <param name="plan">Projection plan for the collection (null allowed only if link is null).</param>
        internal void FoundNextLinkForCollection(IEnumerable collection, Uri link, ProjectionPlan plan)
        {
            Debug.Assert(plan != null || link == null, "plan != null || link == null");

            if (collection != null && !this.nextLinkTable.ContainsKey(collection))
            {
                DataServiceQueryContinuation continuation = DataServiceQueryContinuation.Create(link, plan);
                this.nextLinkTable.Add(collection, continuation);
                Util.SetNextLinkForCollection(collection, continuation);
            }
        }
        public void Continuation_Creates_Incorrect_DataServiceVersion()
        {
            // Regression test for:Client always sends DSV=2.0 when following a continuation token
            ProjectionPlan plan = new ProjectionPlan()
            {
                LastSegmentType = typeof(int),
                ProjectedType   = typeof(int)
            };

            var             continuationToken = DataServiceQueryContinuation.Create(new Uri("http://localhost/Set?$skiptoken='Me'"), plan);
            QueryComponents queryComponents   = continuationToken.CreateQueryComponents();

            Assert.AreSame(queryComponents.Version, Util.ODataVersionEmpty, "OData-Version of  query components should be empty for Continuation token");
        }
        /// <summary>
        /// Gets available Windows Azure offers from the Marketplace.
        /// </summary>
        /// <param name="countryCode">The country two character code. Uses 'US' by default </param>
        /// <returns>The list of offers</returns>
        public virtual List <WindowsAzureOffer> GetAvailableWindowsAzureOffers(string countryCode)
        {
            countryCode = string.IsNullOrEmpty(countryCode) ? "US" : countryCode;
            List <WindowsAzureOffer>             result             = new List <WindowsAzureOffer>();
            List <Offer>                         windowsAzureOffers = new List <Offer>();
            CatalogServiceReadOnlyDbContext      context            = new CatalogServiceReadOnlyDbContext(new Uri(Resources.MarketplaceEndpoint));
            DataServiceQueryContinuation <Offer> nextOfferLink      = null;

            do
            {
                DataServiceQuery <Offer> query = context.Offers
                                                 .AddQueryOption("$filter", "IsAvailableInAzureStores")
                                                 .Expand("Plans, Categories");
                QueryOperationResponse <Offer> offerResponse = query.Execute() as QueryOperationResponse <Offer>;
                foreach (Offer offer in offerResponse)
                {
                    List <Plan> allPlans = new List <Plan>(offer.Plans);
                    DataServiceQueryContinuation <Plan> nextPlanLink = null;

                    do
                    {
                        QueryOperationResponse <Plan> planResponse = context.LoadProperty(
                            offer,
                            "Plans",
                            nextPlanLink) as QueryOperationResponse <Plan>;
                        nextPlanLink = planResponse.GetContinuation();
                        allPlans.AddRange(offer.Plans);
                    } while (nextPlanLink != null);

                    IEnumerable <Plan>   validPlans     = offer.Plans.Where <Plan>(p => p.CountryCode == countryCode);
                    IEnumerable <string> offerLocations = offer.Categories.Select <Category, string>(c => c.Name)
                                                          .Intersect <string>(SubscriptionLocations);
                    if (validPlans.Count() > 0)
                    {
                        result.Add(new WindowsAzureOffer(
                                       offer,
                                       validPlans,
                                       offerLocations.Count() == 0 ? SubscriptionLocations : offerLocations));
                    }
                }

                nextOfferLink = offerResponse.GetContinuation();
            } while (nextOfferLink != null);

            return(result);
        }
Exemple #20
0
        private async static Task <IList> ExecuteQueryAsync <T>(IQueryable query, Expression expression, IReadOnlyList <LambdaExpression> navigationPropertyAccessors)
        {
            var items    = new List <T>();
            var newQuery = (DataServiceQuery <T>)query.Provider.CreateQuery <T>(expression);

            DataServiceQueryContinuation <T> continuation;

            for (var response = (QueryOperationResponse <T>) await newQuery.ExecuteAsync(); response != null;
                 continuation = response.GetContinuation(), response = continuation == null ? null : (QueryOperationResponse <T>) await newQuery.Context.ExecuteAsync(continuation))
            {
                foreach (T item in response)
                {
                    foreach (LambdaExpression navigationPropertyAccessor in navigationPropertyAccessors)
                    {
                        var propertyExpression = (MemberExpression)navigationPropertyAccessor.Body;
                        var propertyInfo       = (PropertyInfo)propertyExpression.Member;
                        if (propertyInfo.DeclaringType != item.GetType())
                        {
                            propertyInfo = item.GetType().GetProperty(propertyInfo.Name);
                        }

                        if (propertyInfo.GetValue(item) is IEnumerable property)
                        {
                            DataServiceQueryContinuation itemsContinuation = response.GetContinuation(property);
                            while (itemsContinuation != null)
                            {
                                QueryOperationResponse itemsResponse;
                                try
                                {
                                    itemsResponse = await newQuery.Context.LoadPropertyAsync(item, propertyExpression.Member.Name, itemsContinuation);
                                }
                                catch (InvalidOperationException e)
                                {
                                    throw new NotSupportedException(e.Message);
                                }
                                itemsContinuation = itemsResponse.GetContinuation();
                            }
                        }
                    }
                    items.Add(item);
                }
            }

            return(items);
        }
Exemple #21
0
        public async Task <IEnumerable <ChocolateyPackage> > LoadFirstPage()
        {
            var query = this._feedClient.Packages.Where(p => p.IsLatestVersion) as DataServiceQuery <FeedPackage>;

            var retrievePackagesTask = this.ExecuteQuery(query);

            var installedPackages = await this._installedPackages.RetrieveInstalledPackages();

            var queryResult = await retrievePackagesTask as QueryOperationResponse <FeedPackage>;

            var convertedPackages = queryResult.Select(package => this.ConvertToPackage(package, installedPackages)).ToList();

            this.MergePackagesIntoCache(convertedPackages);

            this._nextPage = queryResult.GetContinuation();

            return(convertedPackages);
        }
Exemple #22
0
        public static void runGetAllPages(Resources context, string filePath, TestType testType, TestWorkload testWorkload)
        {
            Stopwatch    sw     = new Stopwatch();
            StreamWriter stream = File.AppendText(filePath);

            // DataServiceQueryContinuation<T> contains the next link
            DataServiceQueryContinuation <SalesOrderLine> nextLink = null;

            // Get the first page
            sw.Start();
            var response = context.SalesOrderLines.Execute() as QueryOperationResponse <SalesOrderLine>;

            do
            {
                if (nextLink != null)
                {
                    sw.Start();
                    response = context.Execute <SalesOrderLine>(nextLink) as QueryOperationResponse <SalesOrderLine>;

                    sw.Stop();
                }
                else
                {
                    sw.Stop();
                }

                stream.WriteLine(Entity + "," + testType + "," + testWorkload + "," + sw.Elapsed.TotalMilliseconds.ToString());

                //forced loop to enumerate each item in the response
                foreach (SalesOrderLine salesLine in response)
                {
                    //Console.WriteLine("Sales Id, DataAreaId: " + salesLine.SalesOrderNumber + ", " + salesLine.dataAreaId);
                }
            }
            // Loop if there is a next link
            while ((nextLink = response.GetContinuation()) != null);



            stream.Flush();
            stream.Close();
        }
Exemple #23
0
        /// <summary>Set the continuation for the following results for a collection.</summary>
        /// <param name="collection">The collection to set the links to</param>
        /// <param name="continuation">The continuation for the collection.</param>
        internal static void SetNextLinkForCollection(object collection, DataServiceQueryContinuation continuation)
        {
            Debug.Assert(collection != null, "collection != null");

            // We do a convention call for setting Continuation. We'll invoke this
            // for all properties named 'Continuation' that is a DataServiceQueryContinuation
            // (assigning to a single one would make it inconsistent if reflection
            // order is changed).
            foreach (var property in collection.GetType().GetPublicProperties(true /*instanceOnly*/))
            {
                if (property.Name != "Continuation" || !property.CanWrite)
                {
                    continue;
                }

                if (typeof(DataServiceQueryContinuation).IsAssignableFrom(property.PropertyType))
                {
                    property.SetValue(collection, continuation, null);
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// Returns the next link URI for the collection key
        /// </summary>
        /// <param name="key">The collection for which the Uri is returned, or null, if the top level link is to be returned</param>
        /// <returns>An Uri pointing to the next page for the collection</returns>
        internal virtual DataServiceQueryContinuation GetContinuation(IEnumerable key)
        {
            Debug.Assert(this.materializer != null, "Materializer is null!");

            DataServiceQueryContinuation result;

            if (key == null)
            {
                if ((this.expectingPrimitiveValue && !this.moved) || (!this.expectingPrimitiveValue && !this.materializer.IsEndOfStream))
                {
                    // expectingSingleValue && !moved : haven't started parsing single value (single value should not have next link anyway)
                    // !expectingSingleValue && !IsEndOfStream : collection type feed did not finish parsing yet
                    throw new InvalidOperationException(Strings.MaterializeFromAtom_TopLevelLinkNotAvailable);
                }

                // we have already moved to the end of stream
                // are we singleton or just an entry?
                if (this.expectingPrimitiveValue || this.materializer.CurrentFeed == null)
                {
                    result = null;
                }
                else
                {
                    // DEVNOTE(pqian): The next link uri should never be edited by the client, and therefore it must be absolute
                    result = DataServiceQueryContinuation.Create(
                        this.materializer.CurrentFeed.NextPageLink,
                        this.materializer.MaterializeEntryPlan);
                }
            }
            else
            {
                if (!this.materializer.NextLinkTable.TryGetValue(key, out result))
                {
                    // someone has asked for a collection that's "out of scope" or doesn't exist
                    throw new ArgumentException(Strings.MaterializeFromAtom_CollectionKeyNotPresentInLinkTable);
                }
            }

            return(result);
        }
        List <Project> TryGetProjectsByPredicate(Expression <Func <Project, bool> > predicate, bool expand = true)
        {
            InfBaseModel infBaseModel = new InfBaseModel(uri);

            infBaseModel.SendingRequest2 += OnSendingRequest2;

            List <Project> projects = new List <Project>();
            QueryOperationResponse <Project> qORP;

            try
            {
                if (expand == true)
                {
                    qORP = (infBaseModel.Projects.Expand(p => p.Employees)
                            .Expand(p => p.Leader)
                            .Where(predicate) as DataServiceQuery <Project>)
                           .Execute() as QueryOperationResponse <Project>;
                }
                else
                {
                    qORP = (infBaseModel.Projects.Where(predicate) as DataServiceQuery <Project>)
                           .Execute() as QueryOperationResponse <Project>;
                }

                DataServiceQueryContinuation <Project> token = null;
                do
                {
                    if (token != null)
                    {
                        qORP = infBaseModel.Execute(token);
                    }
                    projects.AddRange(qORP);
                }while ((token = qORP.GetContinuation()) != null);
            }
            catch (DataServiceQueryException ex)
            {
                throw new LogicDataQueryException(ex, ex.Response.StatusCode);
            }
            return(projects);
        }
Exemple #26
0
        /// <summary>
        /// Gets a product report with all current products.
        /// </summary>
        /// <returns>Returns <see cref="ProductReport{T}"/>.</returns>
        public async Task <ProductReport <ProductPrice> > GetCurrentProducts()
        {
            DataServiceQueryContinuation <NorthwindProduct> token = null;

            var query    = (DataServiceQuery <NorthwindProduct>) this.entities.Products;
            var products = new List <NorthwindProduct>();

            var result = await Task <IEnumerable <NorthwindProduct> > .Factory.FromAsync(query.BeginExecute(null, null), (ar) =>
            {
                return(query.EndExecute(ar));
            }) as QueryOperationResponse <NorthwindProduct>;

            products.AddRange(result);

            token = result.GetContinuation();

            while (token != null)
            {
                result = await Task <IEnumerable <NorthwindProduct> > .Factory.FromAsync(this.entities.BeginExecute <NorthwindProduct>(token.NextLinkUri, null, null), (ar) =>
                {
                    return(this.entities.EndExecute <NorthwindProduct>(ar));
                }) as QueryOperationResponse <NorthwindProduct>;

                products.AddRange(result);

                token = result.GetContinuation();
            }

            var prices = from p in products
                         where !p.Discontinued
                         orderby p.ProductName
                         select new ProductPrice
            {
                Name  = p.ProductName,
                Price = p.UnitPrice ?? 0,
            };

            return(new ProductReport <ProductPrice>(prices));
        }
Exemple #27
0
        List <Employee> TryGetEmployeesByPredicate(Expression <Func <Employee, bool> > predicate, bool expand = true)
        {
            InfBaseModel infBaseModel = new InfBaseModel(uri);

            infBaseModel.SendingRequest2 += OnSendingRequest2;

            List <Employee> employees = new List <Employee>();
            QueryOperationResponse <Employee> qOR;

            try
            {
                if (expand == true)
                {
                    qOR = (infBaseModel.Employees.Expand(e => e.Projects)
                           .Expand(e => e.LeadProjects)
                           .Where(predicate) as DataServiceQuery <Employee>)
                          .Execute() as QueryOperationResponse <Employee>;
                }
                else
                {
                    qOR = (infBaseModel.Employees.Where(predicate) as DataServiceQuery <Employee>)
                          .Execute() as QueryOperationResponse <Employee>;
                }
                DataServiceQueryContinuation <Employee> token = null;
                do
                {
                    if (token != null)
                    {
                        qOR = infBaseModel.Execute(token);
                    }
                    employees.AddRange(qOR);
                } while ((token = qOR.GetContinuation()) != null);
            }
            catch (DataServiceQueryException ex)
            {
                throw new Exception("Вы не прошли аутентификацию! Необходимо ввести ваш логин и пароль.", ex);
            }
            return(employees);
        }
        public DataServiceQueryContinuation GetNextLinkUri(ICollection collection, bool catchException)
        {
            DataServiceQueryContinuation nextLink = null;

            try
            {
                nextLink = this._QueryResponse.GetContinuation(collection);
            }
            catch (ArgumentNullException arge)
            {
                if (catchException)
                {
                    AstoriaTestLog.WriteLine(arge.Message);
                    nextLink = null;
                }
                else
                {
                    throw;
                }
            }
            return(nextLink);
        }
        private IEnumerable <T> GetAll()
        {
            IEnumerable results = Execute(_query.Execute);

            DataServiceQueryContinuation continuation = null;

            do
            {
                lock (_context) {
                    foreach (T item in results)
                    {
                        yield return(item);
                    }
                }

                continuation = ((QueryOperationResponse)results).GetContinuation();

                if (continuation != null)
                {
                    results = _context.Execute <T>(_concreteType, continuation);
                }
            } while (continuation != null);
        }
Exemple #30
0
        public async Task <IEnumerable <ChocolateyPackage> > GetNextPage()
        {
            if (this._nextPage == null)
            {
                throw new InvalidOperationException("No page to retireve packages from.");
            }

            var retrievePackagesTask = Task.Factory.FromAsync <IEnumerable <FeedPackage> >(
                this._feedClient.BeginExecute <FeedPackage>(this._nextPage, null, null),
                queryAsyncResult => this._feedClient.EndExecute <FeedPackage>(queryAsyncResult));

            var installedPackages = await this._installedPackages.RetrieveInstalledPackages();

            var queryOperation = await retrievePackagesTask as QueryOperationResponse <FeedPackage>;

            var convertedPackages = queryOperation.Select(package => this.ConvertToPackage(package, installedPackages)).ToList();

            this.MergePackagesIntoCache(convertedPackages);

            this._nextPage = queryOperation.GetContinuation();

            return(this._packageCache);
        }