示例#1
0
        public IQueryable <UserDTO> GetUsers(string searchPhrase = null, SortType?sortDisplayName = null, int pageNumber = 1)
        {
            var users = this.GetAll();

            if (!string.IsNullOrEmpty(searchPhrase))
            {
                users = users.Where(x => x.DisplayName.Contains(searchPhrase));
            }

            if (sortDisplayName != null)
            {
                users = sortDisplayName == SortType.Ascending ?
                        users.OrderBy(x => x.DisplayName) :
                        users.OrderByDescending(x => x.DisplayName);
            }
            else
            {
                users = users.OrderBy(x => x.Id);
            }

            int skip = (pageNumber - 1) * Globals.UsersPageSize;

            users = users.Skip(skip).Take(Globals.UsersPageSize);

            return(users);
        }
示例#2
0
        protected override void InternalGET(System.Web.HttpContext context, HandlerTimedCache cache)
        {
            IList <SecurityRole> roles = UserHelper.GetUserRoles(context.User.Identity.Name);
            //Get the paging parameters...
            int page     = WebUtil.ParseIntParam(context, "page");
            int pageSize = WebUtil.ParseIntParam(context, "pageSize");

            // Check to see if this is a csv export request.  Runs the normal query (with no paging).
            bool csv = false;

            WebUtil.ParseOptionalBoolParam(context, "csv", ref csv);

            // If this is csv, we want all data - override any paging
            if (csv)
            {
                page     = -1;
                pageSize = -1;
            }

            // Now get the ordering parameters, if specified.
            int sortCol = -1;

            WebUtil.ParseOptionalIntParam(context, "sortBy", ref sortCol);
            SortType?sortDir = null;

            if (sortCol >= 0)
            {
                // Default is ascending sort, passing false means descending.
                bool ascending = true;
                WebUtil.ParseOptionalBoolParam(context, "sortasc", ref ascending);
                sortDir = ascending ? SortType.Asc : SortType.Desc;
            }

            string            indicatorId = WebUtil.GetParam(context, "indicator", false);
            NycResolutionType resolution  = WebUtil.ParseEnumParam <NycResolutionType>(context, "resolution");
            NycTimeframeType  timetype    = WebUtil.ParseEnumParam <NycTimeframeType>(context, "timetype");
            int minyear = WebUtil.ParseIntParam(context, "minyear");
            int maxyear = WebUtil.ParseIntParam(context, "maxyear");

            // These two params are for "scope".  These should be "ActualId" not "UID".
            string borough    = WebUtil.GetParam(context, "borough", true);
            string subborough = WebUtil.GetParam(context, "subborough", true);

            NycResultsWithMetadata list = NychanisHelper.Query(indicatorId, resolution, timetype, minyear, maxyear, borough, subborough, sortCol, sortDir, pageSize, page);

            // If this was a csv request, format it and return it instead
            if (csv)
            {
                // Generate actual csv data, determine if this is groupby'd or not
                string export = NychanisHelper.ResultsAsCsv(list, indicatorId);

                // Setup the response to handle this type of request
                context.Response.AddHeader("Content-Disposition", "attachment;filename=Furman_Center_Neighborhood_Info.csv");
                context.Response.ContentType = "text/csv";
                context.Response.Write(export);
                return;
            }
            // Return the results to the client
            context.Response.Write(WebUtil.ObjectToJson(list));
        }
示例#3
0
 /// <summary>
 ///     定义是否允许点击列表头进行排序
 /// </summary>
 /// <param name = "sortable"></param>
 /// <param name = "sortType">当datatype为local时有效。定义适当的排序类型。</param>
 public Column SetSortable(bool sortable, SortType sortType = SortType.Text, SortOrder firstSortOrder = SortOrder.Asc)
 {
     _sortable       = sortable;
     _sortType       = sortType;
     _firstSortOrder = firstSortOrder;
     return(this);
 }
示例#4
0
        public IQueryable<InvitationDTO> GetInvitations(string userId, SortType? sortDate, int pageNumber)
        {
            var allInvitations = this.invitationRepository.GetAll().Where(x => x.UserId == userId);
            var allUsers = this.userRepository.GetAll().ProjectTo<UserDTO>();
            var allGroups = this.groupRepository.GetAll();

            var invitations = from invitation in allInvitations
                              join user in allUsers on invitation.UserId equals user.Id
                              join currentGroup in allGroups on invitation.GroupId equals currentGroup.GroupId

                              select new InvitationDTO
                              {
                                  InvitationId = invitation.InvitationId,
                                  GroupId = invitation.GroupId,
                                  CreatedAt = invitation.CreatedAt,
                                  GroupName = currentGroup.Name,
                                  Username = user.Username,
                              };

            if (sortDate != null)
            {
                invitations = sortDate == SortType.Ascending ?
                    invitations.OrderBy(x => x.CreatedAt) :
                    invitations.OrderByDescending(x => x.CreatedAt);
            }
            else
            {
                invitations = invitations.OrderBy(x => x.InvitationId);
            }

            int skip = (pageNumber - 1) * Globals.InvitationsPageSize;
            invitations = invitations.Skip(skip).Take(Globals.InvitationsPageSize);

            return invitations;
        } 
        public IHttpActionResult GetUsers(string searchPhrase = null, SortType?sortDisplayName = null, int pageNumber = 1)
        {
            if (pageNumber < 1)
            {
                return(BadRequest("PageNumber must be positive"));
            }

            var users = this.userService.GetUsers(searchPhrase, sortDisplayName, pageNumber);

            return(Ok(users));
        }
 protected QueryTypeProperties(
     string moduleName, string prefix, QueryType?queryType, SortType?sortType,
     IEnumerable <Tuple <string, string> > baseParameters, IDictionary <string, string[]> props)
 {
     ModuleName     = moduleName;
     Prefix         = prefix;
     QueryType      = queryType;
     SortType       = sortType;
     BaseParameters = baseParameters;
     m_props        = props ?? new Dictionary <string, string[]>();
 }
示例#7
0
        public IHttpActionResult ViewInvitations(SortType?sortDate = null, int pageNumber = 1)
        {
            if (pageNumber < 1)
            {
                return(BadRequest("PageNumber must be positive"));
            }

            var currentUserId = User.Identity.GetUserId();
            var invitations   = this.groupService.GetInvitations(currentUserId, sortDate, pageNumber);

            return(Ok(invitations));
        }
示例#8
0
        private void UpdateSortType(SortType?sortType)
        {
            if (!sortType.HasValue)
            {
                return;
            }

            var shuffleOn = sortType.Value == SortType.Random;

            if (shuffleOn == _userSettings.ShuffleOn)
            {
                return;
            }

            _shuffleStatusChangedByPlayRequest = true;
            _userSettings.ShuffleOn            = shuffleOn;
            _userSettings.SaveAsync();
        }
示例#9
0
 public FilterEntity()
 {
     if (Take == 0)
     {
         Take = 10;
     }
     if (Skip == 0)
     {
         Skip = 0;
     }
     if (string.IsNullOrEmpty(SortBy))
     {
         SortBy = "Cx";
     }
     if (!SortType.HasValue)
     {
         SortType = Entities.SortType.ASC;
     }
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SortType?type = value as SortType?;

            if (!type.HasValue)
            {
                return(null);
            }
            switch (type.Value)
            {
            case SortType.Ascending:
                return("Rosnąco");

            case SortType.Descending:
                return("Malejąco");

            case SortType.NotSort:
                return("Brak sortowania");

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#11
0
        /// <summary>
        /// Queries for Nychanis data for the specified year range, resolution, and indicator.
        /// </summary>
        /// <param name="indicatorId">ID of the indicator being queried.</param>
        /// <param name="resolutionType">What resolution are we querying for.</param>
        /// <param name="timeUnitType">What type of time units should the data be in?</param>
        /// <param name="startYear">First year to include in the results.</param>
        /// <param name="endYear">Last year to include in the results.</param>
        /// <param name="scopeSubborough"></param>
        /// <param name="scopeBorough"></param>
        /// <param name="orderCol">The column to sort by.</param>
        /// <param name="orderDir">The direction to sort, ignored if order is less than zero.
        /// <param name="numPerPage">Number of records to be returned in the page sequence, if not less than zero</param>
        /// <param name="page">Which page in this page sequence is this request for.
        ///                        If null, assumed to be ascending.</param>
        /// <returns>The results!</returns>
        public static NycResultsWithMetadata Query(object indicatorId,
                                                   NycResolutionType resolutionType, NycTimeframeType timeUnitType, int startYear, int endYear,
                                                   object scopeBorough, object scopeSubborough,
                                                   int orderCol, SortType?orderDir, int numPerPage, int page)
        {
            NycResultsWithMetadata retVal = new NycResultsWithMetadata();
            // First load the indicator metadata, both because we need the display name, and because
            // if the query is for data that doesn't exist, we can skip a lot of work.
            NycIndicator indicator = GetIndicator(indicatorId);

            retVal.Indicator  = indicator.Name;
            retVal.Resolution = resolutionType.ToString();
            // Now verify the query against the metadata.
            retVal.MinYear = (startYear < indicator.MinYear) ? indicator.MinYear : startYear;
            retVal.MaxYear = (endYear > indicator.MaxYear) ? indicator.MaxYear : endYear;
            bool validRequest = (retVal.MaxYear >= retVal.MinYear);

            if (!validRequest)
            {
                // Return a completely blank result object.
                return(retVal);
            }

            // We only want to load time metadata for times this indicator actually has data for.
            DaoJoinCriteria joinCrit = new DaoJoinCriteria();

            joinCrit.RightCriteria = new DaoCriteria();
            joinCrit.RightCriteria.Expressions.Add(new EqualExpression("IndicatorId", indicatorId));
            joinCrit.RightCriteria.Expressions.Add(new EqualExpression("Resolution", resolutionType));
            joinCrit.Expressions.Add(new EqualJoinExpression("UID", "TimeId"));
            // Load the time metadata.
            joinCrit.LeftCriteria = new DaoCriteria();
            // These are not-ed so they are <= and >=;
            joinCrit.LeftCriteria.Expressions.Add(new GreaterExpression("Year", retVal.MaxYear, false));
            joinCrit.LeftCriteria.Expressions.Add(new LesserExpression("Year", retVal.MinYear, false));
            joinCrit.LeftCriteria.Expressions.Add(new EqualExpression("Type", timeUnitType));
            // Sort by value descending, so the most recent year comes first.
            joinCrit.Orders.Add(new JoinSortOrder("Value", SortType.Asc, true));
            List <JoinResult <NycTimeframe, NycResolutionForIndicator> > timeframes = _timeDao.Get(joinCrit, _resolutionDao);

            // We also need to know what all possible times are though, so we can render the fancy slider with appropriate gaps.
            joinCrit.LeftCriteria.Orders.Add(new SortOrder("Value", SortType.Asc));
            IList <NycTimeframe> allTimeframes = _timeDao.Get(joinCrit.LeftCriteria);

            // Use them to assemble the metadata, since one year is one column.
            retVal.Attrs = new List <AbstractNamedSortable>();
            retVal.Attrs.Add(new NycGeogColumnMetadata("Area"));
            IDictionary <object, int> colsByTimeId = new CheckedDictionary <object, int>();

            foreach (JoinResult <NycTimeframe, NycResolutionForIndicator> timeframe in timeframes)
            {
                colsByTimeId[timeframe.Left.UID] = retVal.Attrs.Count;
                retVal.Attrs.Add(new NycYearColumnMetadata(timeframe.Left, indicator.ValueType));
            }

            NycTableResults results = QueryNychanisData(indicatorId, resolutionType,
                                                        scopeBorough, scopeSubborough, colsByTimeId);

            retVal.TotalResults = results.Values.Count;

            // Don't do any further processing if there are no results
            if (results.Values.Count == 0)
            {
                return(retVal);
            }

            // If the user specified a sort order, use that, otherwise sort by the first column (area).
            List <KeyValuePair <int, SortType> > colSorts = new List <KeyValuePair <int, SortType> >();

            colSorts.Add(new KeyValuePair <int, SortType>(orderCol < 0 ? 0 : orderCol, orderDir ?? SortType.Asc));
            results.Values.Sort(new MultipleColumnListComparer(colSorts));

            // Truncate the results by the requested paging information
            retVal.Values = ResultsWithMetadata <AbstractNamedSortable> .GetPagedSubset(results.Values, numPerPage, page);

            // Now get context rows.  Always get City, unless we're querying for City.
            if (resolutionType != NycResolutionType.City)
            {
                List <IList <object> > contextRows = QueryNychanisData(indicatorId, NycResolutionType.City,
                                                                       null, null, colsByTimeId).Values;
                // Now, if they provided a borough scope and didn't ask for a borough resolution,
                // include borough.
                if ((resolutionType != NycResolutionType.Borough) && (scopeBorough != null))
                {
                    contextRows.AddRange(QueryNychanisData(indicatorId, NycResolutionType.Borough,
                                                           scopeBorough, null, colsByTimeId).Values);
                    // Then if not subborough but a subborough is provided, include that.
                    if ((resolutionType != NycResolutionType.SubBorough) && (scopeSubborough != null))
                    {
                        contextRows.AddRange(QueryNychanisData(indicatorId, NycResolutionType.SubBorough,
                                                               scopeBorough, scopeSubborough, colsByTimeId).Values);
                    }
                }
                retVal.ContextRows = contextRows;
            }
            // Now generate the map info for showing the results as a cloropleth layer.
            Config cfg           = Config.GetConfig("PDP.Data");
            string sldHandlerUrl = cfg.GetParameter("Mapping", "SldHandlerURL");

            retVal.MapInfo        = new NycMapInfo();
            retVal.MapInfo.Server = cfg.GetParameter("Mapping", "MapServerURL");
            retVal.MapInfo.Layers = new List <NycLayerInfo>();
            string layerName = Config.GetConfig("NYC.SLD").GetParameter("LayerNames", resolutionType.ToString(), null);

            // City doesn't have a map layer, so don't create any OL layers for it.
            if (layerName != null)
            {
                int possibleTimeIndex = 0;
                int actualTimeIndex   = 0;
                while (possibleTimeIndex < allTimeframes.Count)
                {
                    // We need to pad out the list of layers with blanks for timeframes that lack data.
                    NycLayerInfo layer = new NycLayerInfo();
                    layer.Name = allTimeframes[possibleTimeIndex].Name;
                    // Years that actually have data go up faster than all years, so check if the current
                    // possible year is lower than the next actual year.
                    if (allTimeframes[possibleTimeIndex].Value < timeframes[actualTimeIndex].Left.Value)
                    {
                        // Need to pad with a blank, so just let the blank layer object be added.
                        // Increment the possible time index to the next timeframe.
                        possibleTimeIndex++;
                    }
                    else
                    {
                        NycTimeframe time = timeframes[actualTimeIndex].Left;

                        // I think this check is no longer necessary, since we're probably
                        // always excluding unavailable data.  But if it ain't broke...
                        if (results.DataAvailableByTime[actualTimeIndex])
                        {
                            layer.Config                = new Dictionary <string, object>();
                            layer.Config["layers"]      = layerName;
                            layer.Config["styles"]      = "";
                            layer.Config["format"]      = "image/png";
                            layer.Config["tiled"]       = true;
                            layer.Config["srs"]         = "EPSG:4326";
                            layer.Config["transparent"] = true;
                            StringBuilder sb = new StringBuilder(sldHandlerUrl);
                            sb.Append("?indicator=").Append(indicatorId);
                            sb.Append("&resolution=").Append(resolutionType.ToString());
                            sb.Append("&time=").Append(time.UID);
                            if (scopeBorough != null)
                            {
                                sb.Append("&borough=").Append(scopeBorough);
                                if (scopeSubborough != null)
                                {
                                    sb.Append("&subborough=").Append(scopeSubborough);
                                }
                            }
                            layer.Config["SLD"] = sb.ToString();
                        }
                        // Increment both indexes.
                        possibleTimeIndex++;
                        actualTimeIndex++;
                    }

                    retVal.MapInfo.Layers.Add(layer);
                }

                // If we are creating layers, we must create a legend to describe them
                retVal.LegendInfo = GenerateLegendList(indicator, resolutionType);
            }
            return(retVal);
        }
示例#12
0
 public Column SetSortType(SortType sortType)
 {
     _sortType = sortType;
     return(this);
 }
示例#13
0
文件: Column.cs 项目: algola/backup
 /// <summary>
 /// <param>Indicates how column is sorted, default is TEXT</param>
 /// <param>INT - the data is interpreted as integer, </param>
 /// <param>FLOAT - the data is interpreted as decimal number </param>
 /// <param>DATE - the data is interpreted as data </param>
 /// <param>TEXT - the data is interpreted as text</param>
 /// </summary>
 /// <param name="sortType"></param>
 public Column setSortType(SortType sortType)
 {
     this._sortType = sortType;
     return this;
 }
示例#14
0
        protected override void InternalGET(HttpContext context, HandlerTimedCache cache)
        {
            IList <SecurityRole> roles = UserHelper.GetUserRoles(context.User.Identity.Name);

            //Get the paging parameters...
            int page     = WebUtil.ParseIntParam(context, "page");
            int pageSize = WebUtil.ParseIntParam(context, "pageSize");


            // Check to see if this is a csv export request.  Runs the normal query (with no paging).
            bool csv = false;

            WebUtil.ParseOptionalBoolParam(context, "csv", ref csv);

            // If this is csv, we want all data - override any paging
            if (csv)
            {
                page     = -1;
                pageSize = -1;
            }
            IList <IExpression> expressions = ParseExpressions(context);

            // Now get the ordering parameters, if specified.
            int sortCol = -1;

            WebUtil.ParseOptionalIntParam(context, "sortBy", ref sortCol);
            SortType?sortDir = null;

            if (sortCol >= 0)
            {
                // Default is ascending sort, passing false means descending.
                bool ascending = true;
                WebUtil.ParseOptionalBoolParam(context, "sortasc", ref ascending);
                sortDir = ascending ? SortType.Asc : SortType.Desc;
            }
            PdbTwoTableHelper dataHelper = new PdbTwoTableHelper(Config.GetConfig("PDP.Data"), "Properties", PdbEntityType.Properties);

            // Now get the grouping parameters, if specified.
            IList <string>         groupBys = WebUtil.GetJsonStringArrayParam(context, "groupby", true);
            PdbResultsWithMetadata list;

            if ((groupBys != null) && (groupBys.Count > 0))
            {
                list = dataHelper.GroupedQuery(expressions, groupBys, sortCol, sortDir, roles, pageSize, page);
            }
            else
            {
                list = dataHelper.Query(expressions, sortCol, sortDir, roles, pageSize, page);
            }

            // If this was a csv request, format it and return it instead
            if (csv)
            {
                // Generate actual csv data, determine if this is groupby'd or not
                string export = dataHelper.ResultsAsCsv(list, ((groupBys != null) && (groupBys.Count > 0)));

                // Setup the response to handle this type of request
                context.Response.AddHeader("Content-Disposition", "attachment;filename=Furman_Center_SHIP_Properties.csv");
                context.Response.ContentType = "text/csv";
                context.Response.Write(export);
                return;
            }
            context.Response.Write(WebUtil.ObjectToJson(list));
        }
示例#15
0
文件: Column.cs 项目: liujunhua/Smart
 /// <summary>
 ///     定义是否允许点击列表头进行排序
 /// </summary>
 /// <param name = "sortable"></param>
 /// <param name = "sortType">当datatype为local时有效。定义适当的排序类型。</param>
 public Column SetSortable(bool sortable, SortType sortType = SortType.Text, SortOrder firstSortOrder = SortOrder.Asc)
 {
     _sortable = sortable;
     _sortType = sortType;
     _firstSortOrder = firstSortOrder;
     return this;
 }
        /// <summary>
        /// Creates a field that holds <see cref="QueryTypeProperties{T}"/> for the module.
        /// </summary>
        protected FieldDeclarationSyntax CreatePropertiesField(
            Module module, string resultClassName, FieldDeclarationSyntax propsField, SortType?sortType)
        {
            var queryTypePropertiesType = SyntaxEx.GenericName("QueryTypeProperties", resultClassName);

            var propertiesInitializer = SyntaxEx.ObjectCreation(
                queryTypePropertiesType,
                SyntaxEx.Literal(module.Name),
                SyntaxEx.Literal(module.Prefix),
                module.QueryType == null
                    ? (ExpressionSyntax)SyntaxEx.NullLiteral()
                    : SyntaxEx.MemberAccess("QueryType", module.QueryType.ToString()),
                sortType == null
                    ? (ExpressionSyntax)SyntaxEx.NullLiteral()
                    : SyntaxEx.MemberAccess("SortType", sortType.ToString()),
                CreateTupleListExpression(GetBaseParameters(module)),
                propsField == null ? (ExpressionSyntax)SyntaxEx.NullLiteral() : (NamedNode)propsField,
                resultClassName == "object"
                    ? (ExpressionSyntax)SyntaxEx.LambdaExpression("_", SyntaxEx.NullLiteral())
                    : SyntaxEx.MemberAccess(resultClassName, "Parse"));

            return(SyntaxEx.FieldDeclaration(
                       new[] { SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword },
                       queryTypePropertiesType, ClassNameBase + "Properties", propertiesInitializer));
        }
示例#17
0
 /// <summary>
 /// <param>Indicates how column is sorted, default is TEXT</param>
 /// <param>INT - the data is interpreted as integer, </param>
 /// <param>FLOAT - the data is interpreted as decimal number </param>
 /// <param>DATE - the data is interpreted as data </param>
 /// <param>TEXT - the data is interpreted as text</param>
 /// </summary>
 /// <param name="sortType"></param>
 public Column setSortType(SortType sortType)
 {
     this._sortType = sortType;
     return(this);
 }
示例#18
0
 public void PlayArtist(Artist artist, SortType?sortType, Track firstTrack = null)
 {
     UpdatePlaylist(sortType, artist.Name, _trackFilterService.GetTracksByArtist(artist), firstTrack);
 }
示例#19
0
 public Pie Sort(SortType sort)
 {
     this.sort = sort;
     return(this);
 }
示例#20
0
 public void PlayAlbum(Album album, SortType?sortType, Track firstTrack = null)
 {
     UpdatePlaylist(sortType, album.ToString(), _trackFilterService.GetTracksFromAlbum(album), firstTrack);
 }
示例#21
0
 public void PlayGrouping(string grouping, SortType?sortType, Track firstTrack = null)
 {
     UpdatePlaylist(sortType, grouping, _trackFilterService.GetTracksByGrouping(grouping), firstTrack);
 }
示例#22
0
 public void PlayAll(SortType?sortType, Track firstTrack = null)
 {
     UpdatePlaylist(sortType, LibraryPlaylistName, _trackFilterService.GetAll(), firstTrack);
 }
示例#23
0
文件: Repository.cs 项目: stylkyn/ess
        public async Task <List <T> > FindManyAsync(Expression <Func <T, bool> > condition, SortType?sortType = null, Expression <Func <T, object> > sort = null)
        {
            var query = Collection().Find(condition);

            if (sortType != null && sort != null)
            {
                if (SortType.ASC == sortType)
                {
                    query = query.SortBy(sort);
                }
                else if (SortType.DESC == sortType)
                {
                    query = query.SortByDescending(sort);
                }
            }
            return(await query.ToListAsync());
        }
        /// <summary>
        /// Creates an entry method, that is used to execute query for normal modules
        /// or that can be used as a base for a query for query modules.
        /// </summary>
        protected void GenerateMethod(
            Module module, IEnumerable <Parameter> methodParameters, string resultClassName,
            FieldDeclarationSyntax propsField, string fileName, bool nullableParameters, SortType?sortType)
        {
            var propertiesField = CreatePropertiesField(module, resultClassName, propsField, sortType);

            ExpressionSyntax queryParameters = SyntaxEx.Invocation(
                SyntaxEx.MemberAccess("QueryParameters", SyntaxEx.GenericName("Create", resultClassName)));

            var queryParametersLocal = SyntaxEx.LocalDeclaration("var", "queryParameters", queryParameters);

            var documentationElements = new List <XmlElementSyntax>();

            var summary = SyntaxEx.DocumentationSummary(module.Description);

            documentationElements.Add(summary);

            var parameters = new List <ParameterSyntax>();
            IList <StatementSyntax> statements = new List <StatementSyntax>();

            statements.Add(queryParametersLocal);

            methodParameters = methodParameters
                               .Where(p => !p.Deprecated)
                               .Where(p => p.Name != "continue")
                               .OrderByDescending(p => p.Required);

            foreach (var methodParameter in methodParameters)
            {
                var nullable      = nullableParameters && !methodParameter.Required;
                var typeName      = Wiki.TypeManager.GetTypeName(methodParameter, ClassNameBase, nullable, false);
                var parameterName = GetPropertyName(methodParameter.Name);

                // this type cannot be processed
                if (typeName == null)
                {
                    continue;
                }

                var parameter = SyntaxEx.Parameter(typeName, parameterName, nullable ? SyntaxEx.NullLiteral() : null);

                parameters.Add(parameter);

                ExpressionSyntax valueExpression = (NamedNode)parameter;

                if (nullable && typeName.EndsWith("?"))
                {
                    valueExpression = SyntaxEx.MemberAccess(valueExpression, "Value");
                }

                ExpressionSyntax newQueryParameters;
                if (typeName == "System.IO.Stream")
                {
                    newQueryParameters = SyntaxEx.Invocation(
                        SyntaxEx.MemberAccess(queryParametersLocal, "AddFile"),
                        SyntaxEx.Literal(methodParameter.Name),
                        valueExpression);
                }
                else
                {
                    newQueryParameters = SyntaxEx.Invocation(
                        SyntaxEx.MemberAccess(queryParametersLocal, "AddSingleValue"),
                        SyntaxEx.Literal(methodParameter.Name),
                        SyntaxEx.Invocation(SyntaxEx.MemberAccess(valueExpression, "ToQueryString")));
                }
                var queryParametersAssignment = SyntaxEx.Assignment(queryParametersLocal, newQueryParameters);

                if (nullable)
                {
                    var assignmentWithCheck = SyntaxEx.If(
                        SyntaxEx.NotEquals((NamedNode)parameter, SyntaxEx.NullLiteral()), queryParametersAssignment);

                    statements.Add(assignmentWithCheck);
                }
                else
                {
                    statements.Add(queryParametersAssignment);
                }

                var parameterDocumentation = SyntaxEx.DocumentationParameter(parameterName, methodParameter.Description);

                documentationElements.Add(parameterDocumentation);
            }

            statements = GenerateMethodBody(
                SyntaxEx.ObjectCreation(
                    SyntaxEx.GenericName("QueryProcessor", resultClassName),
                    SyntaxFactory.IdentifierName("m_wiki"),
                    (NamedNode)propertiesField), (NamedNode)queryParametersLocal, statements);

            var modifiers = new List <SyntaxKind> {
                SyntaxKind.PublicKeyword
            };

            if (statements == null)
            {
                modifiers.Add(SyntaxKind.AbstractKeyword);
            }

            var method = SyntaxEx.MethodDeclaration(
                modifiers, GenerateMethodResultType(), ClassNameBase, parameters, statements)
                         .WithLeadingTrivia(SyntaxFactory.Trivia(SyntaxEx.DocumentationComment(documentationElements)));

            AddMembersToClass(fileName, propertiesField, method);
        }
示例#25
0
文件: Repository.cs 项目: stylkyn/ess
        public async Task <(List <T>, int)> FindManyIncludeTotalAsync(Expression <Func <T, bool> > condition, SortType?sortType = null, Expression <Func <T, object> > sort = null, int?skip = null, int?take = null)
        {
            var query = Collection().Find(condition);

            if (sortType != null && sort != null)
            {
                if (SortType.ASC == sortType)
                {
                    query = query.SortBy(sort);
                }
                else if (SortType.DESC == sortType)
                {
                    query = query.SortByDescending(sort);
                }
            }
            var totalTask = query.CountDocumentsAsync();

            if (skip != null)
            {
                query = query.Skip(skip);
            }
            if (take != null)
            {
                query = query.Limit(take);
            }

            var queryTask = query.ToListAsync();
            await Task.WhenAll(queryTask, totalTask);

            return(queryTask.Result, (int)totalTask.Result);
        }
示例#26
0
        public async Task <ActionResult <PagedResult <GetProductViewModel> > > GetProducts([Required] int pageNumber, string search, string type, string manufacturer,
                                                                                           bool isOnDiscount, int?priceMin, int?priceMax, SortType?sortType)
        {
            var products = await productRespository.GetAllAsync(pageNumber, search, type, manufacturer, isOnDiscount, priceMin, priceMax, sortType);

            return(Ok(new PagedResult <GetProductViewModel>
            {
                Result = products.Select(p => new GetProductViewModel(p)),
                CurrentPage = products.CurrentPage,
                TotalPages = products.TotalPages,
                HasNext = products.HasNext
            }));
        }
示例#27
0
        /// <summary>
        /// 获取商品列表数据
        /// </summary>
        /// <param name="clusterId">群Id</param>
        /// <param name="channelId">渠道id</param>
        /// <param name="categoryId">分类id</param>
        /// <param name="brandId">品牌id</param>
        /// <param name="starAge">开始年龄</param>
        /// <param name="endAge">结束年龄</param>
        /// <param name="startPrice">开始价格</param>
        /// <param name="endPrice">结束价格</param>
        /// <param name="sortType">排序类型</param>
        /// <param name="pageSize">每页数据条数</param>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageTotal">数据总数</param>
        /// <returns></returns>
        public List <Vi_Web_Pdt_List> GetGoodsList(int clusterId, int channelId, int categoryId, int brandId,
                                                   int starAge, int endAge, decimal startPrice, decimal endPrice,
                                                   SortType?sortType, int pageSize, int pageIndex,
                                                   out int pageTotal)
        {
            channelId = 102;
            var holycaDb = new HolycaEntities();

            if (sortType == null)
            {
                sortType = SortType.SalesDesc;
            }

            var queryTxt = from c in holycaDb.Vi_Web_Pdt_List
                           where c.intHerdID == clusterId && c.intChannelID == channelId
                           select c;

            #region 处理查询条件

            if (categoryId > 0)
            {
                queryTxt = queryTxt.Where(p => p.intWebType == categoryId || p.intWebChildType == categoryId || p.intWebThirdType == categoryId);
            }

            if (brandId > 0)
            {
                queryTxt = queryTxt.Where(p => p.intBrandID == brandId);
            }

            if (starAge > 0)
            {
                queryTxt = queryTxt.Where(p => p.intStartAge <= starAge);
            }

            if (endAge > 0)
            {
                queryTxt = queryTxt.Where(p => p.intEndAge >= endAge);
            }

            if (startPrice > 0)
            {
                queryTxt = queryTxt.Where(p => p.numHerdPrice >= startPrice);
            }

            if (endPrice > 0)
            {
                queryTxt = queryTxt.Where(p => p.numHerdPrice <= endPrice);
            }

            switch (sortType)
            {
            case SortType.EnableTimeAsc:
                queryTxt = queryTxt.OrderBy(o => o.intIsNew);
                break;

            case SortType.EnableTimeDesc:
                queryTxt = queryTxt.OrderByDescending(o => o.intIsNew);
                break;

            case SortType.PriceAsc:
                queryTxt = queryTxt.OrderBy(o => o.numHerdPrice);
                break;

            case SortType.PriceDesc:
                queryTxt = queryTxt.OrderByDescending(o => o.numHerdPrice);
                break;

            case SortType.SalesAsc:
                queryTxt = queryTxt.OrderBy(o => o.intSalesVolume);
                break;

            case SortType.SalesDesc:
                queryTxt = queryTxt.OrderByDescending(o => o.intSalesVolume);
                break;
            }

            #endregion

            pageTotal = queryTxt.Count();
            var list = queryTxt.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();

            return(list);
        }
示例#28
0
        public void Sort(Range key1 = null, SortOrder?order1 = null, Range key2 = null, SortType?type = null, SortOrder?order2 = null, Range key3 = null, SortOrder?order3 = null, YesNoGuess?header = YesNoGuess.No)
        {
            //if (!(key1 is String) && !(key1 is Range) && key1 != null)
            //    throw new ArgumentException("Key1 must be a string (range named) or a range object");

            //if (!(key2 is String) && !(key2 is Range) && key2 != null)
            //    throw new ArgumentException("Key2 must be a string (range named) or a range object");

            //if (!(key3 is String) && !(key3 is Range) && key3 != null)
            //    throw new ArgumentException("Key3 must be a string (range named) or a range object");

            InternalObject.GetType().InvokeMember("Sort", System.Reflection.BindingFlags.InvokeMethod, null, InternalObject, ComArguments.Prepare(key1, order1, key2, order2, key3, order3, header));
        }
示例#29
0
 public void PlayPlaylist(string playlistName, List <Track> tracks, SortType?sortType, Track firstTrack = null)
 {
     UpdatePlaylist(sortType, playlistName, tracks, firstTrack);
 }
示例#30
0
        public ActionResult Index(string no, string kw, int?page, SortType?sort, decimal?priceMin, decimal?priceMax, string color)
        {
            if (!page.HasValue || page.Value < 1)
            {
                page = 1;
            }
            var size  = 12;
            var count = 0;

            //获取一级分类
            no = no ?? String.Empty;
            var classOneNo = no ?? String.Empty;
            var classTwoNo = String.Empty;

            if (no.Length < 8)
            {
                classOneNo = FlhConfig.CLASSNO_CLASS_PREFIX;
                classTwoNo = String.Empty;
            }
            else if (no.Length > 8)
            {
                classOneNo = no.Substring(0, 8);
                classTwoNo = no.Left(12);
            }
            else if (no.Length == 8)
            {
                classOneNo = FlhConfig.CLASSNO_CLASS_PREFIX;
                classTwoNo = no;
            }

            var classOneName = String.Empty;
            var classTwoName = String.Empty;
            var classOne     = _ClassesManager.EnabledClasses.FirstOrDefault(d => d.no == classOneNo);

            if (classOne != null)
            {
                if (classOneNo.Length <= 4)
                {
                    classOne.name = "所有分类";
                }
                classOneName = classOne.name;
            }


            List <ListModel.ClassItem> classes = new List <Models.Product.ListModel.ClassItem>();

            classes.Add(new ListModel.ClassItem {
                Name = classOne.name, No = classOne.no
            });

            var subClasses = _ClassesManager.GetChildren(classOneNo)
                             .OrderByDescending(d => d.order_by)
                             .Select(d => new Flh.WebSite.Models.Product.ListModel.ClassItem {
                Name = d.name, No = d.no
            }).ToArray();

            classes.AddRange(subClasses);

            if (!String.IsNullOrWhiteSpace(classTwoNo))
            {
                var classTwo = subClasses.FirstOrDefault(d => d.No == classTwoNo);
                if (classTwo != null)
                {
                    classTwoName = classTwo.Name;
                }
            }

            var products = _ProductManager.Search(new ProductSearchArgs
            {
                Keyword  = kw,
                ClassNo  = String.IsNullOrWhiteSpace(no) ? String.Empty : no,
                PriceMin = priceMin,
                PriceMax = priceMax,
                Limit    = size,
                Start    = (page.Value - 1) * size,
                Sort     = sort,
                Color    = color,
            }, out count);

            return(View(new Models.Product.ListModel()
            {
                No = (no ?? String.Empty).Trim(),
                Keyword = (kw ?? String.Empty).Trim(),
                Color = color,
                ClassItems = classes.ToArray(),
                ClassOneNo = classOneNo,
                ClassOneName = classOneName,
                ClassTwoName = classTwoName,
                PriceMin = priceMin,
                PriceMax = priceMax,
                Sort = sort,
                Items = new PageModel <Models.Product.ListModel.Item>(products
                                                                      .Select(p => new Models.Product.ListModel.Item
                {
                    Pid = p.pid,
                    Name = p.name,
                    No = p.classNo,
                    Order = p.sortNo,
                    Color = p.color,
                    Image = p.imagePath,
                    Material = p.material,
                    Size = p.size,
                    Technique = p.technique
                }), page.Value, (int)Math.Ceiling((double)count / (double)size))
            }));
        }
示例#31
0
        public async Task <(List <UserModel>, int)> SearchUser(string fullText, int skip, int take, SortType?sortType, UserSortField?sortField)
        {
            if (sortType == null)
            {
                sortType = SortType.DESC;
            }
            Expression <Func <UserModel, object> > sortFunc = x => x.CreatedDate;

            switch (sortField)
            {
            case UserSortField.Email:
                sortFunc = x => x.Email; break;

            case UserSortField.Lastname:
                sortFunc = x => x.Personal.Lastname; break;

            case UserSortField.Firstname:
                sortFunc = x => x.Personal.Firstname; break;

            case UserSortField.CompanyName:
                sortFunc = x => x.Company.CompanyName; break;
            }

            string fullTextCleared = fullText?.Trim()?.ToLower() ?? "";
            var    result          = await FindManyIncludeTotalAsync(x =>
                                                                     fullTextCleared == "" ||
                                                                     x.Email.ToLower().Contains(fullTextCleared) ||
                                                                     (x.Personal != null && x.Personal.Firstname != null && x.Personal.Firstname.ToLower().Contains(fullTextCleared)) ||
                                                                     (x.Personal != null && x.Personal.Lastname != null && x.Personal.Lastname.Contains(fullTextCleared)) ||
                                                                     (x.Company != null && x.Company.CompanyName != null && x.Company.CompanyName.Contains(fullTextCleared)),
                                                                     sortType,
                                                                     sortFunc,
                                                                     skip,
                                                                     take
                                                                     );

            return(result);
        }
示例#32
0
 private void UpdatePlaylist(SortType?sortType, string playlistName, List <Track> tracks, Track startAt,
                             bool isAnOrderedPlaylist = false)
 {
     UpdateSortType(sortType);
     _playlist.Set(playlistName, tracks, startAt, _userSettings.ShuffleOn, isAnOrderedPlaylist);
 }