Пример #1
7
        /// <summary>
        /// Applies the roles filter.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="model">The model.</param>
        /// <returns>Query with roles filter applied</returns>
        private IQueryable<Models.User> ApplyRolesFilter(IQueryable<Models.User> query, GetUsersModel model)
        {
            if (model.FilterByRoles != null && model.FilterByRoles.Any(role => !string.IsNullOrWhiteSpace(role)))
            {
                var predicate = (model.FilterByRolesConnector == FilterConnector.Or)
                    ? PredicateBuilder.False<Models.User>()
                    : PredicateBuilder.True<Models.User>();

                foreach (var roleName in model.FilterByRoles)
                {
                    if (!string.IsNullOrWhiteSpace(roleName))
                    {
                        Expression<Func<Models.User, bool>> whereClause = user => user.UserRoles.Any(userRole => userRole.Role.Name == roleName && !userRole.Role.IsDeleted);
                        if (model.FilterByRolesConnector == FilterConnector.Or)
                        {
                            predicate = PredicateBuilder.Or(predicate, whereClause);
                        }
                        else
                        {
                            predicate = PredicateBuilder.And(predicate, whereClause);
                        }
                    }
                }

                query = query.Where(predicate);
            }

            return query;
        }
Пример #2
0
 //Method to fill the contents of a grid view with an IQueryable argument
 //protected void FillGrid(object sender, IQueryable q, GridViewSortEventArgs e)
 //{
 //    GridView1.DataSource = q;
 //    //GridView1.DataSourceID = String.Empty;
 //    gridView_Sorting(sender, e, GridView1);
 //    //GridView1.DataBind();
 //    GridView1.AutoGenerateColumns = true;
 //    GridView1.Visible = true;
 //    //GridView1.EnableSortingAndPagingCallbacks = true;
 //}
 protected void FillGrid(object sender, IQueryable q)
 {
     GridView1.DataSource = q;
     GridView1.DataBind();
     GridView1.AutoGenerateColumns = true;
     GridView1.Visible = true;
 }
Пример #3
0
        public IQueryable<ReclamacaoViewModel> GetReclamacoes()
        {
            // int filtro = int.Parse(DropDownList1.SelectedValue);
            string filtro = DropDownList1.SelectedItem.ToString();
            DateTime inicio = calInicio.SelectedDate;
            DateTime fim = calFim.SelectedDate;
            ReclamaPoaEntities _db = new ReclamaPoaEntities();

            query = from r in _db.Reclamacoes
                    where filtro == r.Bairro.Nome && r.Data >= inicio && r.Data <= fim
                    select new ReclamacaoViewModel
                    {
                        ReclamacaoId = r.ReclamacaoId,
                        Titulo = r.Titulo,
                        Descricao = r.Descricao,
                        Data = r.Data,
                        Endereco = r.Endereco,
                        Situacao = r.Situacao.ToString(),
                        Bairro = r.Bairro.Nome,
                        Categoria = r.Categoria.Nome,
                        UrlImagem = r.UrlImagem
                    };

            lvbairros.DataBind();
            return query;
        }
Пример #4
0
 public IEnumerable<ContributionInfo> ContributionsList(IQueryable<Contribution> query)
 {
     var q2 = from c in query
              let bd = c.BundleDetails.FirstOrDefault()
              select new ContributionInfo
                  {
                      BundleId = bd == null ? 0 : bd.BundleHeaderId,
                      ContributionAmount = c.ContributionAmount,
                      ContributionDate = c.ContributionDate,
                      ContributionId = c.ContributionId,
                      ContributionType = c.ContributionType.Description,
                      ContributionTypeId = c.ContributionTypeId,
                      Fund = c.ContributionFund.FundName,
                      NonTaxDed =
                          c.ContributionTypeId == ContributionTypeCode.NonTaxDed ||
                          (c.ContributionFund.NonTaxDeductible ?? false),
                      StatusId = c.ContributionStatusId,
                      Status = c.ContributionStatus.Description,
                      Name = c.Person.Name,
                      PeopleId = c.PeopleId ?? 0,
                      Description = c.ContributionDesc,
                      CheckNo = c.CheckNo
                  };
     return q2;
 }
        private IQueryable<ProductsListViewModel> GetSorted(IQueryable<ProductsListViewModel> allProducts, string sortOrder)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.DateSortParm = String.IsNullOrEmpty(sortOrder) ? "Date" : "";
            ViewBag.PriceSortParm = sortOrder == "Price" ? "price_desc" : "Price";
            ViewBag.RatingSortParm = sortOrder == "Rating" ? "rating_desc" : "Rating";

            switch (sortOrder)
            {
                case "Rating":
                    allProducts = allProducts.OrderBy(p => p.Rating);
                    break;
                case "rating_desc":
                    allProducts = allProducts.OrderByDescending(p => p.Rating);
                    break;
                case "Price":
                    allProducts = allProducts.OrderBy(p => p.Price);
                    break;
                case "price_desc":
                    allProducts = allProducts.OrderByDescending(p => p.Price);
                    break;
                case "Date":
                    allProducts = allProducts.OrderByDescending(p => p.ReleaseDate);
                    break;
                default:
                    allProducts = allProducts.OrderBy(p => p.ReleaseDate);
                    break;
            }

            return allProducts;
        }
Пример #6
0
 private IQueryable<SubscriptionPost> AddNeededWhereClauses(string query,
     IQueryable<SubscriptionPost> subscriptionPosts)
 {
     foreach (var whereClause in GetWhereClausesFromQuery(query))
     {
         switch (whereClause.PropertyName)
         {
             case PropertyName.Author:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Authors.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Content:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Content.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Categories:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Categories.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Feed:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Subscription.Title.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
             case PropertyName.Title:
                 subscriptionPosts = subscriptionPosts
                     .Where(x => x.Title.Contains(whereClause.Text) == whereClause.MustContainText);
                 break;
         }
     }
     return subscriptionPosts;
 }
Пример #7
0
 public static List<BlogPostVModel> BlogPosts(IQueryable<SeqPost> result)
 {
     List<BlogPostVModel> blogList = new List<BlogPostVModel>();
     BlogPostVModel post;
     if (result == null) return blogList;
     foreach (SeqPost sp in result) {
         post = new BlogPostVModel();
         post.BlogPostId = sp.PostId;
         post.Title = sp.Title;
         post.Description = sp.Description;
         post.ExtendedDescription = sp.ExtendedText;
         post.Excerpt = sp.Excerpt;
         post.CreateDate = sp.CreateDate;
         post.Permalink = sp.Permalink;
         foreach (SeqTag st in sp.SeqTags) {
            TagVModel tvm = new TagVModel();
            tvm.BlogId = st.BlogId;
            tvm.TagId = st.TagId;
            tvm.Name = st.Name;
            post.Tags.Add(tvm);
         }
         blogList.Add(post);
     }
     return blogList;
 }
Пример #8
0
        public override IQueryable GetQueryable(IQueryable source)
        {
            string selectedValue = DropDownList1.SelectedValue;
            if (String.IsNullOrEmpty(selectedValue))
            {
                return source;
            }

            if (selectedValue == NullValueString)
            {
                return ApplyEqualityFilter(source, Column.Name, null);
            }

            IDictionary dict = new Hashtable();
            Column.ExtractForeignKey(dict, selectedValue);
            foreach (DictionaryEntry entry in dict)
            {
                string key = (string)entry.Key;
                if (DefaultValues != null)
                {
                    DefaultValues[key] = entry.Value;
                }
                source = ApplyEqualityFilter(source, Column.GetFilterExpression(key), entry.Value);
            }
            return source;
        }
Пример #9
0
 public void QueryLog(IQueryable linqQuery)
 {
     _querytype = QueryType.LINQ;
     _linqQuery = linqQuery.Expression.ToString();
     _StoreSQL = ToTraceString(linqQuery);
     CreateLogEntry();
 }
Пример #10
0
		public UpdatedPackages(
			IQueryable<IPackage> installedPackages,
			IPackageRepository aggregrateRepository)
		{
			this.installedPackages = installedPackages;
			this.sourceRepository = aggregrateRepository;
		}
Пример #11
0
        public IQueryable ApplySelectAndExpand(IQueryable queryable, HttpRequestMessage request )
        {
            var result = queryable;
              var hasSelectOrExpand = false;

              var map = request.RequestUri.ParseQueryString();

              var selectQueryString = map["$select"];
              if (!string.IsNullOrWhiteSpace(selectQueryString)) {
            var selectClauses = selectQueryString.Split(',').Select(sc => sc.Replace('/', '.')).ToList();
            var elementType = TypeFns.GetElementType(queryable.GetType());
            var func = QueryBuilder.BuildSelectFunc(elementType, selectClauses);
            result = func(result);
            hasSelectOrExpand = true;
              }

              var expandsQueryString = map["$expand"];
              if (!string.IsNullOrWhiteSpace(expandsQueryString)) {
            if (!string.IsNullOrWhiteSpace(selectQueryString)) {
              throw new Exception("Use of both 'expand' and 'select' in the same query is not currently supported");
            }
            expandsQueryString.Split(',').Select(s => s.Trim()).ToList().ForEach(expand => {
              result = ((dynamic) result).Include(expand.Replace('/', '.'));
            });
            hasSelectOrExpand = true;
              }

              return hasSelectOrExpand ? result : null;
        }
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseCollectionResult" /> class.
        /// </summary>
        /// <param name="query">The query that returns a collection of objects.</param>
        /// <param name="edmType">The EDM type reference of the objects.</param>
        /// <param name="context">The context where the action is executed.</param>
        protected BaseCollectionResult(IQueryable query, IEdmTypeReference edmType, ApiContext context)
            : base(edmType, context)
        {
            Ensure.NotNull(query, "query");

            this.Query = query;
        }
Пример #13
0
        public IQueryable<EnhancedStudentInformation> ApplyFilter(IQueryable<EnhancedStudentInformation> query, StudentMetricsProviderQueryOptions providerQueryOptions)
        {
            //If the Staff USI Isn't set, then no-op.
            if (providerQueryOptions.StaffUSI <= 0)
                return query;

            //The only way a Staff member can be associated with a student at LEA is via the Staff Cohort tables.  Only check that one table.
            if (providerQueryOptions.LocalEducationAgencyId.HasUsableValue() && !providerQueryOptions.SchoolId.HasUsableValue())
            {
                var staffStudentCohorts = StaffStudentCohortRepository.GetAll();
                IQueryable<StaffCohort> staffCohort = StaffCohortRepository.GetAll().Where(sc => sc.StaffUSI == providerQueryOptions.StaffUSI);

                return query.Where(si => staffStudentCohorts
                    .SelectMany(ssc => staffCohort.Where(sc => ssc.StaffCohortId == sc.StaffCohortId).Select(sc => ssc))
                    .Any(ssc => ssc.StudentUSI == si.StudentUSI));
            }

            //At the school level, a staff member can be associated by Cohort or by Section.  This view collapses the two.
            var ssa = StaffStudentAssociationRepository.GetAll();
            return query.Where(student => ssa.Any(ms => ms.StudentUSI == student.StudentUSI
                                                        && ms.SchoolId == student.SchoolId
                //This filters on school id, because if a teacher is a teacher at two schools,
                //We need to filter on the Staff Section records only for the current school.
                                                        && ms.SchoolId == providerQueryOptions.SchoolId.GetValueOrDefault()
                                                        && ms.StaffUSI == providerQueryOptions.StaffUSI));
        }
        /// <summary>
        /// Filters the device list with the supplied filters
        /// </summary>
        /// <param name="list">Devices to filter</param>
        /// <param name="filters">Filters to apply</param>
        /// <returns>Set of devices that pass all the filters</returns>
        public static IQueryable<dynamic> FilterDeviceList(
            IQueryable<dynamic> list, 
            List<FilterInfo> filters)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            if (filters == null)
            {
                return list;
            }

            list = list.Where(GetIsNotNull).AsQueryable();

            foreach (var f in filters)
            {
                if ((f != null) && !string.IsNullOrEmpty(f.ColumnName))
                {
                    list = FilterItems(list, f);
                }
            }

            return list;
        }
Пример #15
0
        public static async Task<IQueryable<Package>> SearchCore(
            ISearchService searchService,
            HttpRequestBase request,
            IQueryable<Package> packages, 
            string searchTerm, 
            string targetFramework, 
            bool includePrerelease,
            CuratedFeed curatedFeed)
        {
            SearchFilter searchFilter;
            // We can only use Lucene if:
            //  a) We are looking for the latest version of a package OR the Index contains all versions of each package
            //  b) The sort order is something Lucene can handle
            if (TryReadSearchFilter(searchService.ContainsAllVersions, request.RawUrl, out searchFilter))
            {
                searchFilter.SearchTerm = searchTerm;
                searchFilter.IncludePrerelease = includePrerelease;
                searchFilter.CuratedFeed = curatedFeed;
                searchFilter.SupportedFramework = targetFramework;

                var results = await GetResultsFromSearchService(searchService, searchFilter);

                return results;
            }

            if (!includePrerelease)
            {
                packages = packages.Where(p => !p.IsPrerelease);
            }

            return packages.Search(searchTerm);
        }
        public PackageListViewModel(IQueryable<Package> packages,
            string searchTerm,
            string sortOrder,
            int totalCount,
            int pageIndex,
            int pageSize,
            UrlHelper url,
            bool includePrerelease)
        {
            // TODO: Implement actual sorting
            IEnumerable<ListPackageItemViewModel> items;
            using (MiniProfiler.Current.Step("Querying and mapping packages to list"))
            {
                items = packages.ToList()
                                .Select(pv => new ListPackageItemViewModel(pv, needAuthors: false));
            }
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = totalCount;
            SortOrder = sortOrder;
            SearchTerm = searchTerm;
            int pageCount = (TotalCount + PageSize - 1) / PageSize;

            var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
                items,
                PageIndex,
                pageCount,
                page => url.PackageList(page, sortOrder, searchTerm, includePrerelease)
            );
            Items = pager.Items;
            FirstResultIndex = 1 + (PageIndex * PageSize);
            LastResultIndex = FirstResultIndex + Items.Count() - 1;
            Pager = pager;
            IncludePrerelease = includePrerelease ? "true" : null;
        }
 public GroupDescriptorExpressionBuilder(IQueryable queryable, GroupDescriptor groupDescriptor, GroupDescriptorExpressionBuilder childBuilder, IQueryable notPagedData)
     : base(queryable)
 {
     this.groupDescriptor = groupDescriptor;
     this.childBuilder = childBuilder;
     this.notPagedData = notPagedData;
 }
Пример #18
0
        private static List<Quest401kTransactionDto> MapModelToDto(IQueryable<Quest401KTransactions> transactions)
        {
            //return transactions.Project().To<Quest401kTransactionDto>().ToList();
            var transactionsDtos = new List<Quest401kTransactionDto>();
            foreach (var transaction in transactions)
            {
                var dto = new Quest401kTransactionDto
                {
                    Id = transaction.Id,
                    Row = transaction.Row,
                    Ticker = transaction.Ticker,
                    Date = transaction.Date,
                    Trantype = transaction.Trantype,
                    Amount = transaction.Amount,
                    Shares = transaction.Shares,
                    Nav = transaction.Nav
                };

                var subTransactionsDtos = new List<Quest401kSubTransactionDto>();
                foreach (var subTransaction in transaction.SubTransactions)
                {
                    var subTransactionDto = new Quest401kSubTransactionDto
                    {
                        Id = subTransaction.Id,
                        Trantype = subTransaction.Trantype,
                        Amount = subTransaction.Amount,
                        Shares = subTransaction.Shares
                    };
                    subTransactionsDtos.Add(subTransactionDto);
                }
                dto.SubTransactions = subTransactionsDtos;
                transactionsDtos.Add(dto);
            }
            return transactionsDtos;
        }
        protected override void EstablishContext()
        {
            //Prepare supplied data collections
            suppliedStudentInformationData = GetSuppliedStudentInformation();
            suppliedRootMetricNode = GetSuppliedRootNode();
            suppliedRootMetricHierarchy = GetSuppliedRootMetricHierarchy();
            suppliedRootIEnumerableOfKeyValuePair = GetSuppliedRootKeyValuePairs();

            //Set up the mocks
            studentInformationRepository = mocks.StrictMock<IRepository<StudentInformation>>();
            rootMetricNodeResolver = mocks.StrictMock<IRootMetricNodeResolver>();
            domainMetricService = mocks.StrictMock<IDomainMetricService<StudentSchoolMetricInstanceSetRequest>>();
            metricTreeToIEnumerableOfKeyValuePairProvider = mocks.StrictMock<IMetricTreeToIEnumerableOfKeyValuePairProvider>();

            //Set expectations
            Expect.Call(studentInformationRepository.GetAll()).Return(suppliedStudentInformationData);
            Expect.Call(rootMetricNodeResolver.GetRootMetricNode()).Return(suppliedRootMetricNode);

            Expect.Call(domainMetricService.Get(null))
                .Constraints(
                    new ActionConstraint<StudentSchoolMetricInstanceSetRequest>(x =>
                    {
                        Assert.That(x.SchoolId == suppliedSchoolId);
                        Assert.That(x.StudentUSI == suppliedStudentUSI);
                        Assert.That(x.MetricVariantId == suppliedRootMetricNode.MetricVariantId);
                    })
                ).Return(suppliedRootMetricHierarchy);
            Expect.Call(metricTreeToIEnumerableOfKeyValuePairProvider.FlattenMetricTree((ContainerMetric) suppliedRootMetricHierarchy.RootNode)).Return(suppliedRootIEnumerableOfKeyValuePair);
        }
        public override IQueryable GetQueryable(IQueryable source)
        {
            string searchString = textBox.Text.Trim();
            if (String.IsNullOrEmpty(searchString))
                return source;

            ConstantExpression searchFilter = Expression.Constant(searchString);

            ParameterExpression param = Expression.Parameter(source.ElementType);
            MemberExpression property = Expression.Property(param, this.Column.Name);
            if (Nullable.GetUnderlyingType(property.Type) != null)
                property = Expression.Property(property, "Value");

            MethodInfo method = typeof(String).GetMethod("Contains", new[] { typeof(String) });

            var containsMethodExp = Expression.Call(property, method, searchFilter);
            var containsLambda = Expression.Lambda(containsMethodExp, param);

            var resultExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new Type[] { source.ElementType },
                source.Expression,
                Expression.Quote(containsLambda));

            return source.Provider.CreateQuery(resultExpression);
        }
Пример #21
0
        public void AddSampleDocuments()
        {
            AddDocument(new SampleDocument { Name = "Documents Bill", Id = "X.Y.1.2", Version = new Version("1.0"), NullableScalar = 5 });
            AddDocument(new SampleDocument { Name = "Bills Document", Id = "X.Z.1.3", Version = new Version("1.5"), NullableScalar = 1, NumericBool = true});

            documents = provider.AsQueryable<SampleDocument>();
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="AggregateCatalog"/> class
        ///     with the specified catalogs.
        /// </summary>
        /// <param name="catalogs">
        ///     An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add
        ///     to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to 
        ///     create an <see cref="AggregateCatalog"/> that is empty.
        /// </param>
        /// <exception cref="ArgumentException">
        ///     <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
        /// </exception>
        public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
        {
            Requires.NullOrNotNullElements(catalogs, "catalogs");

            this._catalogs = new ComposablePartCatalogCollection(catalogs, this.OnChanged, this.OnChanging);
            this._partsQuery = this._catalogs.AsQueryable().SelectMany(catalog => catalog.Parts);
        }
Пример #23
0
        private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
        {
            if (rule.field == "CustomerId")
            {
                int result;
                if (!int.TryParse(rule.data, out result))
                    return customers;
                return customers.Where(c => c.CustomerID == Convert.ToInt32(rule.data));

            }
            if (rule.field == "Name")
                return from c in customers
                       where c.FirstName.Contains(rule.data) || c.LastName.Contains(rule.data)
                       select c;
            if (rule.field == "Company")
                return customers.Where(c => c.CompanyName.Contains(rule.data));
            if (rule.field == "EmailAddress")
                return customers.Where(c => c.EmailAddress.Contains(rule.data));
            if (rule.field == "Last Modified")
            {
                DateTime result;
                if (!DateTime.TryParse(rule.data, out result))
                    return customers;
                if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
                    return customers;
                return customers.Where(c => c.ModifiedDate.Date == Convert.ToDateTime(rule.data).Date);
            }
            if (rule.field == "Telephone")
                return customers.Where(c => c.Phone.Contains(rule.data));
            return customers;
        }
        public PackageListViewModel(
            IQueryable<Package> packages,
            DateTime? indexTimestampUtc,
            string searchTerm,
            int totalCount,
            int pageIndex,
            int pageSize,
            UrlHelper url,
            string curatedFeed)
        {
            // TODO: Implement actual sorting
            IEnumerable<ListPackageItemViewModel> items = packages.ToList().Select(pv => new ListPackageItemViewModel(pv));
            PageIndex = pageIndex;
            IndexTimestampUtc = indexTimestampUtc;
            PageSize = pageSize;
            TotalCount = totalCount;
            SearchTerm = searchTerm;
            int pageCount = (TotalCount + PageSize - 1) / PageSize;

            var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
                items,
                PageIndex,
                pageCount,
                page => curatedFeed == null ?
                    url.PackageList(page, searchTerm) :
                    url.CuratedPackageList(page, searchTerm, curatedFeed)
                );
            Items = pager.Items;
            FirstResultIndex = 1 + (PageIndex * PageSize);
            LastResultIndex = FirstResultIndex + Items.Count() - 1;
            Pager = pager;
        }
Пример #25
0
 protected override void ExecuteTest()
 {
     studentResults = filter.ApplyFilter(query, new StudentMetricsProviderQueryOptions
     {
         SchoolId = SuppliedSchoolId2
     });
 }
Пример #26
0
        public override Expression BuildLinqExpression(IQueryable query, Expression expression, Expression item = null)
        {
            var leftExpression = this.LeftNode.BuildLinqExpression(query, expression, item);
            var rightExpression = this.RightNode.BuildLinqExpression(query, expression, item);

            // Nasty workaround to avoid comparison of Aggregate functions to true or false which breaks Entity framework
            if (leftExpression.Type == typeof(bool) && rightExpression.Type == typeof(bool) && rightExpression is ConstantExpression)
            {
                if ((bool)(rightExpression as ConstantExpression).Value)
                {
                    return leftExpression;
                }

                return Expression.Not(leftExpression);
            }

            if (rightExpression.Type == typeof(bool) && leftExpression.Type == typeof(bool)
                && leftExpression is ConstantExpression)
            {
                if ((bool)(leftExpression as ConstantExpression).Value)
                {
                    return rightExpression;
                }

                return Expression.Not(rightExpression);
            }

            NormalizeTypes(ref leftExpression, ref rightExpression);

            return ApplyEnsuringNullablesHaveValues(Expression.Equal, leftExpression, rightExpression);
        }
        public static MemberAccessExpressionBuilderBase MemberAccess(IQueryable source, Type memberType, string memberName)
        {
            var builder = MemberAccess(source.ElementType, memberType, memberName);
            builder.Options.LiftMemberAccessToNull = source.Provider.IsLinqToObjectsProvider();

            return builder;
        }
        protected override void EstablishContext()
        {
            //Prepare supplied data collections
            suppliedStudentMetricBenchmarkAssessmentData = GetSuppliedStudentMetricBenchmarkAssessment();
            suppliedSchoolGoal = GetSuppliedMetricGoal();
            suppliedMetricState = GetSuppliedMetricState();

            //Set up the mocks
            metricNodeResolver = mocks.StrictMock<IMetricNodeResolver>();
            studentMetricBenchmarkAssessmentRepository = mocks.StrictMock<IRepository<StudentMetricBenchmarkAssessment>>();
            metricGoalProvider = mocks.StrictMock<IMetricGoalProvider>();
            metricStateProvider = mocks.StrictMock<IMetricStateProvider>();
            metricInstanceSetKeyResolver = mocks.StrictMock<IMetricInstanceSetKeyResolver<StudentSchoolMetricInstanceSetRequest>>();

            //Set expectations
            Expect.Call(metricNodeResolver.GetMetricNodeForStudentFromMetricVariantId(suppliedSchoolId, suppliedMetricVariantId)).Return(GetMetricMetadataNode());
            Expect.Call(studentMetricBenchmarkAssessmentRepository.GetAll()).Return(suppliedStudentMetricBenchmarkAssessmentData);
            Expect.Call(
                metricInstanceSetKeyResolver.GetMetricInstanceSetKey(null))
                .Constraints(
                    new ActionConstraint<StudentSchoolMetricInstanceSetRequest>(x =>
                    {
                        Assert.That(x.SchoolId == suppliedSchoolId);
                        Assert.That(x.MetricVariantId == suppliedMetricVariantId);
                        Assert.That(x.StudentUSI == suppliedStudentUSI);
                    })
                ).Return(suppliedMetricInstanceSetKey);
            Expect.Call(metricGoalProvider.GetMetricGoal(suppliedMetricInstanceSetKey, suppliedMetricId)).Return(suppliedSchoolGoal);
            Expect.Call(metricStateProvider.GetState(suppliedMetricId, suppliedMetricValueStr, "System.Double")).Repeat.Any().Return(suppliedMetricState);
            Expect.Call(metricStateProvider.GetState(suppliedMetricId, "", "System.Double")).Return(suppliedMetricState);
        }
        public static MvcHtmlString CreateFilteredRequestTable(this HtmlHelper helper, IQueryable<FilteredRequestRecord> filteredRequestRecords, Localizer T)
        {
            StringBuilder sb = new StringBuilder();

            if (filteredRequestRecords == null || !filteredRequestRecords.Any())
            {
                sb.AppendLine(T("No requests are filtered yet.").Text);
            }
            else
            {
                sb.AppendLine("<table><tr>");
                sb.AppendFormat("<th>{0}</th>", T("Request time"));
                sb.AppendFormat("<th>{0}</th>", T("Url"));
                sb.AppendFormat("<th>{0}</th>", T("User Host Address"));
                sb.AppendFormat("<th>{0}</th>", T("User Agent"));
                sb.AppendLine("</tr>");

                foreach (FilteredRequestRecord filteredRequest in filteredRequestRecords.OrderByDescending(r => r.RequestTime))
                {
                    sb.AppendLine("<tr>");
                    sb.AppendFormat("<td>{0}</td>", filteredRequest.RequestTime);
                    sb.AppendFormat("<td>{0}</td>", filteredRequest.Url);
                    sb.AppendFormat("<td>{0}</td>", filteredRequest.UserHostAddress);
                    sb.AppendFormat("<td>{0}</td>", filteredRequest.UserAgent);
                    sb.AppendLine("</tr>");
                }
                sb.AppendLine("</table>");
            }
            return new MvcHtmlString(sb.ToString());
        }
Пример #30
0
 /// <summary>
 /// 返回数据条数
 /// </summary>
 /// <param name="entityQueryable"></param>
 public int ResultDataCount(IQueryable <T_Sys_Users> entityQueryable)
 {
     return(_repository.ResultDataCount(entityQueryable));
 }
Пример #31
0
 public IQueryable <TEntity> Include <TEntity, TProperty>(IQueryable <TEntity> source, Expression <Func <TEntity, TProperty> > navigationPropertyPath) where TEntity : class
 {
     return(EntityFrameworkQueryableExtensions.Include(source, navigationPropertyPath));
 }
Пример #32
0
 public static IQueryable <ChatUser> Online(this IQueryable <ChatUser> source)
 {
     return(source.Where(u => u.Status != (int)UserStatus.Offline));
 }
Пример #33
0
 protected override IQueryable <User> ApplySorting(IQueryable <User> query, PagedResultRequestDto input)
 {
     return(query.OrderBy(r => r.UserName));
 }
Пример #34
0
        /// <summary>Gets the query to fetch the typed list EmployeeJoined</summary>
        /// <param name="root">Optional. If specified (not null) it's used as the root of the query to fetch the typed list, otherwise a new IQueryable(Of EmployeeClassificationEntity) is used</param>
        /// <returns>IQueryable</returns>
        public IQueryable <LLBLGenPro.OrmCookbook.TypedListClasses.EmployeeJoinedRow> GetEmployeeJoinedTypedList(IQueryable <EmployeeClassificationEntity> root = null)
        {
            var current0 = root ?? this.EmployeeClassification;
            var current1 = from employeeClassification in current0
                           join employee in this.Employee on employeeClassification.EmployeeClassificationKey equals employee.EmployeeClassificationKey
                           select new LLBLGenPro.OrmCookbook.TypedListClasses.EmployeeJoinedRow()
            {
                CellPhone = employee.CellPhone, EmployeeKey = employee.EmployeeKey, FirstName = employee.FirstName, LastName = employee.LastName, MiddleName = employee.MiddleName, OfficePhone = employee.OfficePhone, Title = employee.Title, EmployeeClassificationKey = employeeClassification.EmployeeClassificationKey, EmployeeClassificationName = employeeClassification.EmployeeClassificationName, IsEmployee = employeeClassification.IsEmployee, IsExempt = employeeClassification.IsExempt
            };

            return(current1);
        }
Пример #35
0
 public static async Task <CustomList <T> > CreateAsync(IQueryable <T> source)
 {
     return(new CustomList <T>(List <T> list));  //do whatever you need in the contructor, constructor omitted
 }
Пример #36
0
 public override void BulkDelete(IQueryable <TEntity> query)
 {
     query.Delete();
 }
Пример #37
0
 public override void BulkUpdate(IQueryable <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression)
 {
     query.Update(updateExpression);
 }
Пример #38
0
        public async Task <InventoryObject[]> GetAllInventoryObjectsAsync()
        {
            IQueryable <InventoryObject> query = _appDbContext.InventoryObjects;

            return(await query.ToArrayAsync());
        }
Пример #39
0
        public static IQueryable <T> ApplySort <T>(this IQueryable <T> source, string orderBy,
                                                   Dictionary <string, PropertyMappingValue> mappingDictionary)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (mappingDictionary == null)
            {
                throw new ArgumentNullException(nameof(mappingDictionary));
            }

            if (string.IsNullOrWhiteSpace(orderBy))
            {
                return(source);
            }

            // the orderBy string is separated by ",", so we split it.
            var orderByAfterSplit = orderBy.Split(',');

            // apply each orderby clause in reverse order - otherwise, the
            // IQueryable will be ordered in the wrong order
            foreach (var orderByClause in orderByAfterSplit.Reverse())
            {
                // trim the orderBy clause, as it might contain leading
                // or trailing spaces. Can't trim the var in foreach,
                // so use another var.
                var trimmedOrderByClause = orderByClause.Trim();

                // if the sort option ends with with " desc", we order
                // descending, ortherwise ascending
                var orderDescending = trimmedOrderByClause.EndsWith(" desc");

                // remove " asc" or " desc" from the orderBy clause, so we
                // get the property name to look for in the mapping dictionary
                var indexOfFirstSpace = trimmedOrderByClause.IndexOf(" ");
                var propertyName      = indexOfFirstSpace == -1 ?
                                        trimmedOrderByClause : trimmedOrderByClause.Remove(indexOfFirstSpace);

                // find the matching property
                if (!mappingDictionary.ContainsKey(propertyName))
                {
                    throw new ArgumentException($"Key mapping for {propertyName} is missing");
                }

                // get the PropertyMappingValue
                var propertyMappingValue = mappingDictionary[propertyName];

                if (propertyMappingValue == null)
                {
                    throw new ArgumentNullException("propertyMappingValue");
                }

                // Run through the property names in reverse
                // so the orderby clauses are applied in the correct order
                foreach (var destinationProperty in
                         propertyMappingValue.DestinationProperties.Reverse())
                {
                    // revert sort order if necessary
                    if (propertyMappingValue.Revert)
                    {
                        orderDescending = !orderDescending;
                    }
                    source = source.OrderBy(destinationProperty +
                                            (orderDescending ? " descending" : " ascending"));
                }
            }
            return(source);
        }
Пример #40
0
 /// <summary>
 /// 分页数据
 /// </summary>
 /// <param name="sortKey">排序</param>
 /// <param name="pageNumber">当前页数</param>
 /// <param name="pageSize">展示数据条数</param>
 /// <returns>返回符合条件数据列表</returns>
 public IQueryable <T_Sys_Users> FindDataByPageFilter(string sortKey, int pageNumber, int pageSize, IQueryable <T_Sys_Users> entityList = null)
 {
     return(_repository.FindDataByPageFilter(sortKey, pageNumber, pageSize, entityList));
 }
Пример #41
0
 public ExcelResult(IQueryable rows, string fileName, string[] headers, string[] properties, string title)
     : this(rows, fileName, headers, properties, title, null, null, null)
 {
 }
Пример #42
0
        // GET: Agencies
        public async Task <ActionResult> Index(string sortOrder, string currentFilter, string searchString, int?page)
        {
            //return View(await agencys.ToListAsync());

            ViewBag.NameSortParm          = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
            ViewBag.ContactPersonSortParm = sortOrder == "ContactPerson" ? "ContactPerson_desc" : "ContactPerson";
            ViewBag.EmailSortParm         = sortOrder == "Email" ? "Email_desc" : "Email";
            ViewBag.PhoneNumberSortParm   = sortOrder == "Phone" ? "Phone_desc" : "Phone";
            //ViewBag.SubscriptionSortParm = sortOrder == "Subscription" ? "Subscription_desc" : "Subscription";
            ViewBag.AmountSortParm = sortOrder == "Amount" ? "Amount_desc" : "Amount";
            ViewBag.PaidSortParm   = sortOrder == "Paid" ? "Paid_desc" : "Paid";

            IQueryable <AgencyViewModel> agencysData = from agencys in db.Agencys.Include(a => a.Subscription)
                                                       select new AgencyViewModel()
            {
                AgencyID      = agencys.AgencyID,
                Name          = agencys.Name,
                ContactPerson = agencys.ContactPerson,
                Email         = agencys.Email,
                Phone         = agencys.Phone,
                //Subscription = agencys.Subscription.Name,
                Amount = agencys.Subscription.Amount,
                Paid   = agencys.Subscription.Paid
            };

            //Paging
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            //Filtering
            if (!String.IsNullOrEmpty(searchString))
            {
                agencysData = agencysData.Where
                                  (s => s.Name.ToString().ToUpper().Contains(searchString.ToUpper()) ||
                                  s.ContactPerson.ToString().ToUpper().Contains(searchString.ToUpper())
                                  );
            }
            switch (sortOrder)
            {
            case "Name_desc":
                agencysData = agencysData.OrderByDescending(s => s.Name);
                break;

            case "ContactPerson":
                agencysData = agencysData.OrderBy(s => s.ContactPerson);
                break;

            case "ContactPerson_desc":
                agencysData = agencysData.OrderByDescending(s => s.ContactPerson);
                break;

            case "Email":
                agencysData = agencysData.OrderBy(s => s.Email);
                break;

            case "Email_desc":
                agencysData = agencysData.OrderByDescending(s => s.Email);
                break;

            case "Phone":
                agencysData = agencysData.OrderBy(s => s.Phone);
                break;

            case "Phone_desc":
                agencysData = agencysData.OrderByDescending(s => s.Phone);
                break;

            //case "Subscription":
            //    agencysData = agencysData.OrderBy(s => s.Subscription);
            //    break;
            //case "Subscription_desc":
            //    agencysData = agencysData.OrderByDescending(s => s.Subscription);
            //    break;
            case "Amount":
                agencysData = agencysData.OrderBy(s => s.Amount);
                break;

            case "Amount_desc":
                agencysData = agencysData.OrderByDescending(s => s.Amount);
                break;

            case "Paid":
                agencysData = agencysData.OrderBy(s => s.Paid);
                break;

            case "Paid_desc":
                agencysData = agencysData.OrderByDescending(s => s.Paid);
                break;

            default:
                agencysData = agencysData.OrderBy(s => s.Name);
                break;
            }
            int pageSize   = 15;
            int pageNumber = (page ?? 1);

            return(View(await agencysData.ToPagedListAsync(pageNumber, pageSize)));
        }
Пример #43
0
 public IQueryable <TSource> OrderByDescending(IQueryable <TSource> query, string[] keyNames, object comparer)
 {
     return(AddOrAppendOrderBy(query, keyNames, false, comparer));
 }
Пример #44
0
 private static IQueryable <T> OfNotDeleted <T>(this IQueryable <T> query) where T : class, IIsDeletedFlagEntity
 {
     return(query.Where(_ => !_.IsDeleted));
 }
Пример #45
0
 public IQueryable <TSource> OrderBy(IQueryable <TSource> query, string[] keyNames)
 {
     return(AddOrAppendOrderBy(query, keyNames, true));
 }
Пример #46
0
 public ExcelResult(IQueryable rows, string fileName, string[] headers)
     : this(rows, fileName, null, null, null, null, null, null)
 {
 }
 public static IQueryable <T> SelectPage <T>(this IQueryable <T> collection, Page page)
 {
     return(collection.Skip((page.Number - 1) * page.Size).Take(page.Size));
 }
Пример #48
0
 public IQueryable <TSource> OrderByDescending(IQueryable <TSource> query, string[] keyNames)
 {
     return(AddOrAppendOrderBy(query, keyNames, false));
 }
        public bool IsNameDuplicated(CountryLocation model)
        {
            IQueryable <CountryLocation> items = FindAll(x => x.Name == model.Name && !x.IsDeleted && x.Id != model.Id && x.OfficeId == model.OfficeId);

            return(items.Count() > 0 ? true : false);
        }
Пример #50
0
 protected override IQueryable <Role> ApplySorting(IQueryable <Role> query, PagedRoleResultRequestDto input)
 {
     return(query.OrderBy(r => r.DisplayName));
 }
        private IQueryable FilterOnKeys(IQueryable queryable, IEdmCollectionType edmCollectionType,
                                        KeyValuePathSegment segmentKey)
        {
            // need to filter down the entity 
            var entityType = GetEdmEntityType(edmCollectionType);

            // make sure we found the key and entity
            if (entityType == null || segmentKey == null)
            {
                throw new WebAPIDataServiceException("Keys not found", new KeyNotFoundException());
            }

            var entityKeys = entityType.DeclaredKey.Select(dk => dk.Name).ToArray();

            // key can be pass in either , or name value pair
            var segmentKeys = segmentKey.Value.Split(',');
            if (segmentKeys.Length == entityKeys.Length)
            {
                //ToDo this won't handle the edge cases where a value contains an equal sign 
                var passedInKeys = segmentKeys.Select(k => k.Split('='))
                                              .Where(k => k.Length == 2)
                                              .Select(
                                                  k =>
                                                  new KeyValuePair<string, string>(k[0], k[1]))
                                              .ToArray();

                if (passedInKeys.Length > 0)
                {
                    if (!entityKeys.OrderBy(k => k)
                                   .SequenceEqual(passedInKeys.Select(kv => kv.Key)
                                                              .OrderBy(n => n)))
                    {
                        throw new WebAPIDataServiceException("Keys don't match entity model", new KeyNotFoundException());
                    }
                }
                else
                {
                    // build up keyvalue pairs from entitykeys
                    passedInKeys = segmentKeys.Zip(entityKeys,
                                                   (s, k) => new KeyValuePair<string, string>(k, s))
                                              .ToArray();
                }

                // need to build the where clause
                var type = GetIEdmTypeToCLRType(entityType);
                var tSource = Expression.Parameter(type);
                var bodyList = new List<Expression>();

                foreach (var keyPairs in passedInKeys)
                {
                    var tProperty = Expression.Property(tSource, keyPairs.Key);
                    var proptype = type.GetProperty(keyPairs.Key).PropertyType;
                    var keyValue = keyPairs.Value;
                    if (proptype == typeof (string))
                    {
                        // strings usually start with ' and end with ' in OData Calls
                        if (keyValue.StartsWith("'") && keyValue.EndsWith("'"))
                        {
                            keyValue = keyValue.Substring(1, keyValue.Length - 2);
                        }
                    }
                    // Since using EF going to parameterize this
                    var tupleType = typeof (Tuple<>).MakeGenericType(proptype);
                    var tuple = Activator.CreateInstance(tupleType,
                                                         Convert.ChangeType(keyValue, proptype));
                    bodyList.Add(Expression.Equal(tProperty,
                                                  Expression.Property(Expression.Constant(tuple),
                                                                      "Item1")));
                }

                // build up the body expressions adding the And method between each check check
                var body = bodyList[0];
                for (var b = 1; b < bodyList.Count; b++)
                {
                    body = Expression.And(body, bodyList[b]);
                }

                // Expression<Func<TSource, bool>> predicate
                var where =
                    Expression.Lambda(typeof (Func<,>).MakeGenericType(type, typeof (bool)),
                                      body,
                                      tSource);

                // Call the Queryable.Where
                var call = Expression.Call(typeof (Queryable), "Where", new[] {type}, queryable.Expression, where);

                // return back the IQueryable
                return queryable.Provider.CreateQuery(call);
            }
            throw new WebAPIDataServiceException("Keys don't match entity model", new KeyNotFoundException());
        }
        public Task <T> GetFirtOrDefaultAsync(Expression <Func <T, bool> > predicate, params Expression <Func <T, object> >[] includes)
        {
            IQueryable <T> query = SetIncludeWithFilter(predicate, includes);

            return(query.FirstOrDefaultAsync());
        }
Пример #53
0
 public Task <T> FirstOrDefaultAsync <T>(IQueryable <T> source)
 {
     return(EntityFrameworkQueryableExtensions.FirstOrDefaultAsync(source));
 }
Пример #54
0
 public static IQueryable<Recipient> Active(this IQueryable<Recipient> source)
   => source.Where(e => e.Active);
        private void Init()
        {
            IQueryable <Achievement> achievements =
                (new[]
            {
                new Achievement
                {
                    Id = 1,
                    GameId = 1,
                    Name = "Achievement 1 for Game 1",
                    Description = "Achievement Description",
                    ImageUrl = "http://example.com/image.png"
                },
                new Achievement
                {
                    Id = 2,
                    GameId = 1,
                    Name = "Achievement 2 for Game 1",
                    Description = "Achievement Description",
                    ImageUrl = "http://example.com/image.png"
                },
                new Achievement
                {
                    Id = 3,
                    GameId = 1,
                    Name = "Achievement 3 for Game 1",
                    Description = "Achievement Description",
                    ImageUrl = "http://example.com/image.png"
                },
                new Achievement
                {
                    Id = 4,
                    GameId = 2,
                    Name = "Achievement 1 for Game 2",
                    Description = "Achievement Description",
                    ImageUrl = "http://example.com/image.png"
                },
                new Achievement
                {
                    Id = 5,
                    GameId = 2,
                    Name = "Achievement 2 for Game 2",
                    Description = "Achievement Description",
                    ImageUrl = "http://example.com/image.png"
                }
            }).AsQueryable();

            IQueryable <Game> games =
                (new[]
            {
                new Game {
                    Id = 1, Abbreviation = "game1", Name = "Game 1"
                },
                new Game {
                    Id = 2, Abbreviation = "game2", Name = "Game 2"
                }
            }).AsQueryable();

            IQueryable <User> users =
                (new[]
            {
                new User {
                    FacebookUserId = 1234567890, SteamUserId = "user1"
                },
                new User {
                    FacebookUserId = 1234567891, SteamUserId = "user2"
                }
            }).AsQueryable();

            IQueryable <UserAchievement> userAchievements =
                (new[]
            {
                new UserAchievement
                {
                    Id = 1,
                    AchievementId = 1,
                    Date = DateTime.Now,
                    SteamUserId = "user1",
                    Achievement = achievements.Single(a => a.Id == 1)
                },
                new UserAchievement
                {
                    Id = 2,
                    AchievementId = 2,
                    Date = DateTime.Now,
                    SteamUserId = "user1",
                    Achievement = achievements.Single(a => a.Id == 2)
                },
                new UserAchievement
                {
                    Id = 3,
                    AchievementId = 3,
                    Date = DateTime.Now,
                    SteamUserId = "user1",
                    Achievement = achievements.Single(a => a.Id == 3)
                }
            }).AsQueryable();

            Achievements     = achievements;
            Games            = games;
            UserAchievements = userAchievements;
            Users            = users;
        }
Пример #56
0
 public IQueryable <TEntity> Include <TEntity>(IQueryable <TEntity> source, string navigationPropertyPath) where TEntity : class
 {
     return(EntityFrameworkQueryableExtensions.Include(source, navigationPropertyPath));
 }
Пример #57
0
 public Task <T> FirstOrDefaultAsync <T>(IQueryable <T> source, Expression <Func <T, bool> > predicate)
 {
     return(EntityFrameworkQueryableExtensions.FirstOrDefaultAsync(source, predicate));
 }
Пример #58
0
 public Task <TSource> SingleOrDefaultAsync <TSource>(IQueryable <TSource> source, Expression <Func <TSource, bool> > predicate)
 {
     return(EntityFrameworkQueryableExtensions.SingleOrDefaultAsync(source, predicate));
 }
Пример #59
0
 public Task <int> CountAsync <T>(IQueryable <T> source, Expression <Func <T, bool> > predicate)
 {
     return(EntityFrameworkQueryableExtensions.CountAsync(source, predicate));
 }
        public void Country_Get_All()
        {
            //Arrange
            data = new List<Country>() {
           new Country() { Id = 1, Name = "US" },
           new Country() { Id = 2, Name = "India" },
           new Country() { Id = 3, Name = "Russia" }
          }.AsQueryable();
            mockContext = new Mock<IContext>();
            mockSet = new Mock<IDbSet<Country>>();

           
            mockSet.Setup(m => m.Provider).Returns(data.Provider);
            mockSet.Setup(m => m.Expression).Returns(data.Expression);
            mockSet.Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            mockContext.SetupGet(c => c.Countries).Returns(mockSet.Object);

            _service = new CountryService(mockContext.Object);


            //Act
            IQueryable<Country> results = _service.GetAll() as IQueryable<Country>;

            //Assert
            Assert.IsNotNull(results);
            Assert.AreEqual(3, results.ToList().Count);

         
        }