コード例 #1
0
        /// <summary>
        /// Find all playlists in this account.
        /// </summary>
        /// <param name="pageSize">Number of playlists returned per page. A page is a subset of all of the playlists that 
        /// satisfy the request. The maximum page size is 50.</param>
        /// <param name="pageNumber">The zero-indexed number of the page to return.</param>
        /// <param name="sortBy">The property that you'd like to sort the results by.</param>
        /// <param name="sortOrder">The order that you'd like the results sorted - ascending or descending.</param>
        /// <param name="videoFields">A list of the fields you wish to have populated in the Videos 
        /// contained in the playlists. If you omit this parameter, the method returns the following fields of the 
        /// Video: id, name, shortDescription, longDescription, creationDate, publisheddate, lastModifiedDate, linkURL, 
        /// linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics, playsTotal, playsTrailingWeek. 
        /// If you use a token with URL access, this method also returns the Videos' FLVURL, renditions, FLVFullLength, 
        /// videoFullLength.</param>
        /// <param name="playlistFields">A list of the fields you wish to have populated in the Playlists 
        /// contained in the returned object. If you omit this parameter, all playlist fields are returned.</param>
        /// <param name="customFields">A list of the custom fields you wish to have populated in the videos 
        /// contained in the returned object. If you omit this parameter, no custom fields are returned, unless you include 
        /// the value 'customFields' in the video_fields parameter.</param>
        /// <param name="getItemCount">If true, also return how many total results there are.</param>
        /// <returns>A collection of Playlists that is the specified subset of all the playlists in this account.</returns>
        public BrightcoveItemCollection<BrightcovePlaylist> FindAllPlaylists(int pageSize, int pageNumber, SortBy sortBy, SortOrder sortOrder, IEnumerable<string> videoFields, 
            IEnumerable<string> playlistFields, IEnumerable<string> customFields, bool getItemCount)
        {
            NameValueCollection parms = BuildBasicReadParams("find_all_playlists");

            parms.Add("page_size", pageSize.ToString());
            parms.Add("page_number", pageNumber.ToString());
            parms.Add("sort_by", sortBy.ToBrightcoveName());
            parms.Add("sort_order", sortOrder.ToBrightcoveName());
            parms.Add("get_item_count", getItemCount.ToString().ToLower());

            if (videoFields != null)
            {
                parms.AddRange("video_fields", videoFields);
            }

            if (playlistFields != null)
            {
                parms.AddRange("playlist_fields", playlistFields);
            }

            if (customFields != null)
            {
                parms.AddRange("custom_fields", customFields);
            }

            return RunQuery<BrightcoveItemCollection<BrightcovePlaylist>>(parms);
        }
コード例 #2
0
        public async Task<List<CandidateUser>> GetCandidatesListBySearchModelAsync(int? minSalary, int? maxSalary, int? minExperienceInYears, int? maxExperienceInYears, SortBy sortBy, List<Skill> skills)
        {
            var filter = GetSalaryExperienceFilter(minSalary, maxSalary, minExperienceInYears, maxExperienceInYears);
            var skillsName = skills.Select(r => r.NameToLower).ToList();
            var matchBson = GetMatchedSkillsStageBson(skillsName);
            var projectBson = GetCandidateProjectionBson(skillsName, skills.Count);
            var sortDefinition = GetCandidateSortDefinition(sortBy);

            var candidatesQuery = dbContext.CandidateUsers
                .Aggregate()
                .Match(filter)
                .Match(new BsonDocumentFilterDefinition<CandidateUser>(matchBson))
                .Project(new BsonDocumentProjectionDefinition<CandidateUser, BsonDocument>(projectBson))
                .Match(new BsonDocumentFilterDefinition<BsonDocument>(new BsonDocument("Matched", true)))
                .Project(new BsonDocumentProjectionDefinition<BsonDocument, CandidateUser>(new BsonDocument("Skills", 1).Add("Salary", 1).Add("ExperienceInYears", 1).Add("Name", 1).Add("ModificationDate",1).Add("ExperienceDescription", 1)));

            if (sortDefinition != null)
            {
                candidatesQuery = candidatesQuery.Sort(sortDefinition);
            }

            var candidates = await candidatesQuery.ToListAsync();
            return candidates;

        }
コード例 #3
0
ファイル: ApiHelpers.cs プロジェクト: ninjaAB/NGitHub
 public static string GetParametersString(int page, SortBy sort, OrderBy direction)
 {
     return string.Format("page={0}&sort={1}&direction={2}",
                          page,
                          sort.GetText(),
                          direction.GetText());
 }
コード例 #4
0
 public QueryStringFactoryTestsWithSort(SortBy sortBy, Order order, string expectedSortBy, string expectedOrder)
 {
     _sortBy = sortBy;
     _order = order;
     _expectedSortBy = expectedSortBy;
     _expectedOrder = expectedOrder;
 }
コード例 #5
0
 /// <summary>
 /// Get all articles for a given section.
 /// </summary>
 /// <param name="section"></param>
 /// <param name="sortBy"></param>
 /// <param name="sortDirection"></param>
 /// <returns></returns>
 public IList GetAllArticlesBySection(Section section, SortBy sortBy, SortDirection sortDirection)
 {
     string hql = "from Article a left join fetch a.Category where a.Section.Id = :sectionId "
         + GetOrderByClause(sortBy, sortDirection, "a");
     IQuery q = this._sessionManager.OpenSession().CreateQuery(hql);
     q.SetInt32("sectionId", section.Id);
     return q.List();
 }
コード例 #6
0
ファイル: SortOrderFactory.cs プロジェクト: magahl/Cignium
 public static ContactSorter GetSorter(SortBy sortBy)
 {
     switch (sortBy)
     {
         case SortBy.FirstName:
             return new FirstNameSorter();
             break;
         case SortBy.LastName:
             return new LastNameSorter();
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
コード例 #7
0
        public UserSettings()
        {
            Timeout = new List<string>()
            {
                "10 seconds","20 seconds","30 seconds"
            };
            KeepItemsFor = new List<string>()
            {
                "6 hours","12 hours","1 day"
            };

            _ignoreReadItems = true;
            _imagesEnabled = true;
            _sortItemsBy = SortBy.Date;
        }
コード例 #8
0
 public static IComparer SortOrder(SortBy s)
 {
     if (s == SortBy.FruitName)
     {
         return new SortByName();
     }
     else if (s == SortBy.FruitPrice)
     {
         return new SortByPrice();
     }
     else
     {
         //default order
         return new SortByName();
     }
 }
コード例 #9
0
        /// <summary>
        /// Find all audio tracks in the Brightcove media library for this account.
        /// </summary>
        /// <param name="pageSize">Number of items returned per page. Maximum page size is 100.</param>
        /// <param name="pageNumber">The zero-indexed number of the page to return.</param>
        /// <param name="sortBy">The field by which to sort the results.</param>
        /// <param name="sortOrder">How to order the results: ascending or descending.</param>
        /// <param name="audioTrackFields">A list of the fields you wish to have populated in the audiotracks 
        /// contained in the returned object.</param>
        /// <param name="getItemCount">If true, also return how many total results there are.</param>
        /// <returns>A collection of audio tracks matching the specified search criteria.</returns>
        public BrightcoveItemCollection<BrightcoveAudioTrack> FindAllAudioTracks(int pageSize, int pageNumber, SortBy sortBy, SortOrder sortOrder, IEnumerable<string> audioTrackFields, bool getItemCount)
        {
            NameValueCollection parms = BuildBasicReadParams("find_all_audiotracks");

            parms.Add("get_item_count", getItemCount.ToString().ToLower());
            parms.Add("page_size", pageSize.ToString());
            parms.Add("page_number", pageNumber.ToString());
            parms.Add("sort_by", sortBy.ToBrightcoveName());
            parms.Add("sort_order", sortOrder.ToBrightcoveName());

            if (audioTrackFields != null)
            {
                parms.AddRange("audiotrack_fields", audioTrackFields);
            }

            return RunQuery<BrightcoveItemCollection<BrightcoveAudioTrack>>(parms);
        }
コード例 #10
0
        /// <summary>
        /// Generates user reputation object
        /// </summary>
        /// <param name="creator"></param>
        /// <param name="modClass"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static UserReputationList GetUserReputationList(IDnaDataReaderCreator creator, int modClassId, int modStatus,
            int days, int startIndex, int itemsPerPage, SortBy sortBy, SortDirection sortDirection)
        {
            UserReputationList userRepList = new UserReputationList()
            {
                days = days,
                modClassId = modClassId,
                modStatus = modStatus,
                startIndex = startIndex,
                itemsPerPage = itemsPerPage,
                sortBy = sortBy,
                sortDirection = sortDirection
            };

            using (IDnaDataReader dataReader = creator.CreateDnaDataReader("getuserreputationlist"))
            {
                dataReader.AddParameter("modClassId", modClassId);
                dataReader.AddParameter("modStatus", modStatus);
                dataReader.AddParameter("startIndex", startIndex);
                dataReader.AddParameter("itemsPerPage", itemsPerPage);
                dataReader.AddParameter("days", days);
                dataReader.AddParameter("sortby", sortBy.ToString());
                dataReader.AddParameter("sortdirection", sortDirection.ToString());
                
                dataReader.Execute();

                while(dataReader.Read())
                {
                    var userRep = new UserReputation();
                    userRep.UserId = dataReader.GetInt32NullAsZero("userid");
                    userRep.ModClass = ModerationClassListCache.GetObject().ModClassList.FirstOrDefault(x => x.ClassId == dataReader.GetInt32NullAsZero("modclassid"));
                    userRep.CurrentStatus = (ModerationStatus.UserStatus)dataReader.GetInt32NullAsZero("currentstatus");
                    userRep.ReputationDeterminedStatus = (ModerationStatus.UserStatus)dataReader.GetInt32NullAsZero("ReputationDeterminedStatus");
                    userRep.ReputationScore = dataReader.GetInt16("accumulativescore");
                    userRep.LastUpdated = new DateElement(dataReader.GetDateTime("lastupdated"));
                    userRep.UserName = dataReader.GetStringNullAsEmpty("UserName");
                    
                    userRepList.Users.Add(userRep);
                    userRepList.totalItems = dataReader.GetInt32NullAsZero("total");
                }
            }
            return userRepList;
        }
コード例 #11
0
        private void GetParameters()
        {
            _modClassId = 0;
            if(InputContext.DoesParamExist("s_modclassid", "s_modclassid"))
            {
                _modClassId = InputContext.GetParamIntOrZero("s_modclassid", "s_modclassid");
            }

            _modStatus = (int)BBC.Dna.Moderation.Utils.ModerationStatus.UserStatus.Restricted;
            if(InputContext.DoesParamExist("s_modstatus", "s_modstatus"))
            {
                _modStatus = (int)Enum.Parse(typeof(BBC.Dna.Moderation.Utils.ModerationStatus.UserStatus), InputContext.GetParamStringOrEmpty("s_modstatus", "s_modstatus")); ;
            }

            _days =1;
            if(InputContext.DoesParamExist("s_days", "s_days"))
            {
                _days = InputContext.GetParamIntOrZero("s_days", "s_days");
            }

            _startIndex = 0;
            if (InputContext.DoesParamExist("s_startIndex", "startIndex"))
            {
                _startIndex = InputContext.GetParamIntOrZero("s_startIndex", "s_startIndex");
            }

            if (InputContext.DoesParamExist("s_sortby", "sortby"))
            {
                sortBy = (SortBy)Enum.Parse(typeof(SortBy), InputContext.GetParamStringOrEmpty("s_sortby", ""));
            }

            if (InputContext.DoesParamExist("s_sortdirection", "sortdirection"))
            {
                sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), InputContext.GetParamStringOrEmpty("s_sortdirection", "s_sortdirection"));
            }

        }
コード例 #12
0
        /// <summary>
        /// Advanced Search
        /// </summary>
        /// <param name="advancedSearch"> Object advandced search</param>
        /// <returns></returns>
        public List<SearchDocumentResult> AdvancedSearch(AdvancedSearchDto advancedSearch, SortBy sortBy)
        {
            var result = new List<SearchDocumentResult>();

            if (advancedSearch != null)
            {
                try
                {
                    string strResponse = string.Empty;

                    // String search query
                    string strQuery = BuildSearchQuery(advancedSearch);

                    // String search option
                    string strOption = BuildSearchOption(SearchOptionConst.And, false);

                    // Call Amazon Cloud Search API Service
                    AmazonCloudSearcher ObjCloudSearch = new AmazonCloudSearcher();
                    strResponse = ObjCloudSearch.SearchRequest(ApiEndpoint,
                                                                ApiVersion,
                                                                strQuery,
                                                                strOption,
                                                                "_all_fields,_score",
                                                                SearchOptionConst.SortByScoreDesc,
                                                                DataFormat.Json);

                    result = GetSearchDocumentList(strResponse);
                    return result;
                }
                catch (Exception e)
                {
                    Log.Error("Advanced search error. Message: " + e.Message + " Stack trace: " + e.StackTrace);
                }
            }

            return null;
        }
コード例 #13
0
        public async Task<List<JobOffer>> GetOffersByOfferSearchModelAsync(List<Skill> skills, int? minSalary, int? maxSalary, string name, SortBy sortBy)
        {
            var filter = GetSalaryNameFilter(minSalary, maxSalary, name);
            var skillsName = skills.Select(r => r.NameToLower).ToList();
            var matchBson = GetMatchedSkillsStageBson(skillsName);
            var projectBson = GetOfferProjectionBson(skillsName, skills.Count);
            var sortDefinition = GetSortDefinition(sortBy);

            var offersQuery = dbContext.JobOffers
                .Aggregate()
                .Match(filter)
                .Match(new BsonDocumentFilterDefinition<JobOffer>(matchBson))
                .Project(new BsonDocumentProjectionDefinition<JobOffer, BsonDocument>(projectBson))
                .Match(new BsonDocumentFilterDefinition<BsonDocument>(new BsonDocument("Matched", true)))
                .Project(new BsonDocumentProjectionDefinition<BsonDocument, JobOffer>(new BsonDocument("RecruiterId", 1).Add("Salary", 1).Add("Name", 1).Add("Skills", 1).Add("ModificationDate", 1).Add("Description", 1)));

            if (sortDefinition!=null)
            {
                offersQuery = offersQuery.Sort(sortDefinition);
            }
            var offers = await offersQuery.ToListAsync();

            return offers;
        }
コード例 #14
0
 /// <summary>
 /// Obtain an unused ID to assign to a new player from the DB
 /// </summary>
 /// <returns></returns>
 public static int getUnusedID()
 {
     return((getPlayerCount() > 0)
         ? (int)getAllUsersCollection().Find(Query.Null).SetSortOrder(SortBy.Ascending("_id")).Last()["_id"] + 1
         : 1);
 }
コード例 #15
0
        public IEnumerable <T> FindPaged <T>(QueryFilter filter, ObjectId rootId, bool deepSearch, SortBy sortBy, int pageSize) where T : IConfigurable, new()
        {
            T t = (default(T) == null) ? Activator.CreateInstance <T>() : default(T);
            IMailboxStoreType mailboxStoreType = t as IMailboxStoreType;

            return(mailboxStoreType.FindPaged <T>(this, filter, rootId, deepSearch, sortBy, pageSize));
        }
コード例 #16
0
 public static void deleteTags(string Id)
 {
     MongoCollection <Tags> objCollection = db.GetCollection <Tags>("c_Tags");
     var result = objCollection.FindAndRemove(Query.EQ("_id", ObjectId.Parse(Id)),
                                              SortBy.Ascending("_id"));
 }
コード例 #17
0
        /// <summary>
        /// Refreshes the GridFS file info from the server.
        /// </summary>
        public void Refresh()
        {
            using (_server.RequestStart(_serverInstance))
            {
                var gridFS          = new MongoGridFS(_server, _databaseName, _settings);
                var database        = gridFS.GetDatabase();
                var filesCollection = gridFS.GetFilesCollection(database);

                MongoCursor <BsonDocument> cursor;
                if (_id != null)
                {
                    cursor = filesCollection.Find(Query.EQ("_id", _id));
                }
                else if (_name != null)
                {
                    cursor = filesCollection.Find(Query.EQ("filename", _name)).SetSortOrder(SortBy.Descending("uploadDate"));
                }
                else
                {
                    throw new InvalidOperationException("Cannot refresh FileInfo when both Id and Name are missing.");
                }
                var fileInfo = cursor.SetLimit(1).FirstOrDefault();
                CacheFileInfo(fileInfo); // fileInfo will be null if file does not exist
            }
        }
コード例 #18
0
 public SiblingInsertionAttribute(SortBy accordingTo)
 {
     AccordingTo = accordingTo;
 }
コード例 #19
0
		/// <summary>
		/// Retrieves the videos uploaded by the specified user id. This method can be used to find videos submitted using
		/// the consumer-generated media (CGM) module.
		/// </summary>
		/// <param name="userId">The id of the user whose videos we'd like to retrieve.</param>
		/// <param name="pageSize">Number of items returned per page. A page is a subset of all of the items that satisfy the 
		/// request. The maximum page size is 100.</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="sortBy">The field by which to sort the results.</param>
		/// <returns>An ItemCollection representing the requested page of Videos uploaded by the specified user, 
		/// in the order specified.</returns>
		public BrightcoveItemCollection<BrightcoveVideo> FindVideosByUserId(string userId, int pageSize, int pageNumber, SortBy sortBy)
		{
			return FindVideosByUserId(userId, pageSize, pageNumber, sortBy, SortOrder.Ascending);
		}
コード例 #20
0
        private async Task <IEnumerable <T> > Find <T>(ObjectSerializer Serializer, IMongoCollection <BsonDocument> Collection,
                                                       int Offset, int MaxCount, FilterDefinition <BsonDocument> BsonFilter, params string[] SortOrder)
        {
            IFindFluent <BsonDocument, BsonDocument> ResultSet = Collection.Find <BsonDocument>(BsonFilter);

            if (SortOrder.Length > 0)
            {
                SortDefinition <BsonDocument> SortDefinition = null;

                foreach (string SortBy in SortOrder)
                {
                    if (SortDefinition is null)
                    {
                        if (SortBy.StartsWith("-"))
                        {
                            SortDefinition = Builders <BsonDocument> .Sort.Descending(Serializer.ToShortName(SortBy.Substring(1)));
                        }
                        else
                        {
                            SortDefinition = Builders <BsonDocument> .Sort.Ascending(Serializer.ToShortName(SortBy));
                        }
                    }
                    else
                    {
                        if (SortBy.StartsWith("-"))
                        {
                            SortDefinition = SortDefinition.Descending(Serializer.ToShortName(SortBy.Substring(1)));
                        }
                        else
                        {
                            SortDefinition = SortDefinition.Ascending(Serializer.ToShortName(SortBy));
                        }
                    }
                }

                ResultSet = ResultSet.Sort(SortDefinition);
            }

            if (Offset > 0)
            {
                ResultSet = ResultSet.Skip(Offset);
            }

            if (MaxCount < int.MaxValue)
            {
                ResultSet = ResultSet.Limit(MaxCount);
            }

            IAsyncCursor <BsonDocument> Cursor = await ResultSet.ToCursorAsync();

            LinkedList <T>          Result = new LinkedList <T>();
            BsonDeserializationArgs Args   = new BsonDeserializationArgs()
            {
                NominalType = typeof(T)
            };

            while (await Cursor.MoveNextAsync())
            {
                foreach (BsonDocument Document in Cursor.Current)
                {
                    BsonDocumentReader         Reader  = new BsonDocumentReader(Document);
                    BsonDeserializationContext Context = BsonDeserializationContext.CreateRoot(Reader);

                    T Obj = (T)Serializer.Deserialize(Context, Args);
                    Result.AddLast(Obj);
                }
            }

            return(Result);
        }
コード例 #21
0
        public async Task <IActionResult> Index(
            int page          = 1,
            string submit     = null,
            SortBy sort       = SortBy.IdDesc,
            DateTime?DateFrom = null,
            DateTime?DateTo   = null,
            string Nature     = null,
            int?CountyId      = null,
            Guid?TypeId       = null,
            string SourceName = null,
            string Street     = null,
            string City       = null,
            int?StateId       = null,
            string PostalCode = null
            )
        {
            // ViewModel
            var model = new PublicSearchViewModel()
            {
                DateFrom          = DateFrom,
                DateTo            = DateTo,
                CountyId          = CountyId,
                Nature            = Nature,
                TypeId            = TypeId,
                SourceName        = SourceName,
                Street            = Street,
                City              = City,
                StateId           = StateId,
                PostalCode        = PostalCode,
                Sort              = sort,
                CountySelectList  = await GetCountiesSelectListAsync(),
                ConcernSelectList = await GetAreasOfConcernSelectListAsync(),
                StateSelectList   = await GetStatesSelectListAsync(),
            };

            if (string.IsNullOrEmpty(submit))
            {
                return(View(model));
            }

            if (DateFrom.HasValue && DateTo.HasValue &&
                DateFrom.Value > DateTo.Value)
            {
                var msg = "The beginning date must precede the end date.";
                ViewData["AlertMessage"] = new AlertViewModel(msg, AlertStatus.Error, "Error");
            }
            else
            {
                // Search
                var complaints = _context.Complaints.AsNoTracking()
                                 .Where(e => !e.Deleted && e.ComplaintClosed);

                // Filters
                if (DateFrom.HasValue)
                {
                    complaints = complaints
                                 .Where(e => DateFrom.Value <= e.DateReceived);
                }
                if (DateTo.HasValue)
                {
                    complaints = complaints
                                 .Where(e => e.DateReceived.Date <= DateTo.Value);
                }
                if (CountyId.HasValue)
                {
                    complaints = complaints
                                 .Where(e => e.ComplaintCountyId.HasValue && e.ComplaintCountyId.Value == CountyId.Value);
                }
                if (!string.IsNullOrEmpty(Nature))
                {
                    complaints = complaints
                                 .Where(e => e.ComplaintNature.ToLower().Contains(Nature.ToLower()));
                }
                if (TypeId.HasValue)
                {
                    complaints = complaints
                                 .Where(e => (e.PrimaryConcernId.HasValue && e.PrimaryConcernId.Value == TypeId.Value) ||
                                        (e.SecondaryConcernId.HasValue && e.SecondaryConcernId.Value == TypeId.Value));
                }
                if (!string.IsNullOrEmpty(SourceName))
                {
                    complaints = complaints
                                 .Where(e => e.SourceFacilityName.ToLower().Contains(SourceName.ToLower()));
                }
                if (!string.IsNullOrEmpty(Street))
                {
                    complaints = complaints
                                 .Where(e => e.SourceStreet.ToLower().Contains(Street.ToLower()) ||
                                        e.SourceStreet2.ToLower().Contains(Street.ToLower()));
                }
                if (!string.IsNullOrEmpty(City))
                {
                    complaints = complaints
                                 .Where(e => e.SourceCity.ToLower().Contains(City.ToLower()) || e.ComplaintCity.ToLower().Contains(City.ToLower()));
                }
                if (StateId.HasValue)
                {
                    complaints = complaints
                                 .Where(e => e.SourceStateId.HasValue && e.SourceStateId.Value == StateId.Value);
                }
                if (!string.IsNullOrEmpty(PostalCode))
                {
                    complaints = complaints
                                 .Where(e => e.SourcePostalCode.ToLower().Contains(PostalCode.ToLower()));
                }

                // Count
                var count = await complaints.CountAsync().ConfigureAwait(false);

                // Sort
                switch (sort)
                {
                default:
                case SortBy.IdAsc:
                    complaints = complaints.OrderBy(e => e.Id);
                    break;

                case SortBy.IdDesc:
                    complaints         = complaints.OrderByDescending(e => e.Id);
                    model.IdSortAction = SortBy.IdAsc;
                    break;

                case SortBy.ReceivedDateAsc:
                    complaints = complaints.OrderBy(e => e.DateReceived)
                                 .ThenBy(e => e.Id);
                    break;

                case SortBy.ReceivedDateDesc:
                    complaints = complaints.OrderByDescending(e => e.DateReceived)
                                 .ThenBy(e => e.Id);
                    model.ReceivedDateSortAction = SortBy.ReceivedDateAsc;
                    break;
                }

                // Include
                complaints = complaints
                             .Include(e => e.CurrentOffice)
                             .Include(e => e.SourceState);

                // Paging
                complaints = complaints
                             .Skip((page - 1) * CTS.PageSize)
                             .Take(CTS.PageSize);

                // Select
                var items = await complaints
                            .Select(e => new PublicSearchResultsViewModel(e))
                            .ToListAsync().ConfigureAwait(false);

                model.Complaints = new PaginatedList <PublicSearchResultsViewModel>(items, count, page);
            }

            return(View(model));
        }
コード例 #22
0
 public SiblingInsertionAttribute(SortBy accordingTo)
 {
     AccordingTo = accordingTo;
 }
コード例 #23
0
 internal IConfigurable[] Find <T>(QueryFilter filter, ObjectId rootId, bool deepSearch, SortBy sortBy) where T : IConfigurable, new()
 {
     return(this.DataProvider.Find <T>(filter, rootId, deepSearch, sortBy));
 }
コード例 #24
0
ファイル: MongoHelper.cs プロジェクト: xuan2261/MongoHelper
        /// <summary>
        /// 按条件分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query">查询条件</param>
        /// <param name="pageIndex">页次</param>
        /// <param name="pageRow">每页显示记录数</param>
        /// <param name="total">总记录数</param>
        /// <returns></returns>
        public List <T> FindMoreForPageByCondi <T>(IMongoQuery query, int pageIndex, int pageRow, ref long total)
        {
            List <T> list = new List <T>();

            try
            {
                total = this._db.GetCollection(typeof(T).Name).FindAs <T>(query).Count();//获取总记录数
                if (pageIndex == 1)
                {
                    list = this._db.GetCollection(typeof(T).Name).FindAs <T>(query).SetSortOrder(SortBy.Descending("CreateDate")).SetLimit(pageRow).ToList();
                }
                else
                {
                    var bd    = this._db.GetCollection(typeof(T).Name).Find(query).SetSortOrder("_id:1").SetLimit((pageIndex - 1) * pageRow).Last(); //获取最后一个ID主键
                    var el    = bd.GetElement(0);
                    var value = el.Value;
                    list = this._db.GetCollection(typeof(T).Name).FindAs <T>(query).SetSortOrder("_id:1").SetSkip(pageRow).SetLimit(pageRow).ToList();
                }
            }
            catch (Exception ex)
            {
            }
            return(list);
        }
コード例 #25
0
ファイル: Employees.cs プロジェクト: kjb7749/testImport
 public EmployeeComparer(SortBy sortBy)
 {
     SortOn = sortBy;
 }
コード例 #26
0
		/// <summary>
		/// Searches videos according to the criteria provided by the user.
		/// </summary>
		/// <param name="all">Specifies the field:value pairs for search criteria that MUST be present in 
		/// the index in order to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="any">Specifies the field:value pairs for search criteria AT LEAST ONE of which 
		/// must be present to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="none">Specifies the field:value pairs for search criteria that MUST NOT be present 
		/// to return a hit in the result set. If the field's name is not present, it is assumed to be 
		/// name and shortDescription.</param>
		/// <param name="pageSize">Number of items returned per page. (max 100)</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="exact">If true, disables fuzzy search and requires an exact match of search terms. 
		/// A fuzzy search does not require an exact match of the indexed terms, but will return a hit for 
		/// terms that are closely related based on language-specific criteria. The fuzzy search is 
		/// available only if your account is based in the United States.</param>
		/// <param name="sortBy">Specifies the field by which to sort results.</param>
		/// <param name="sortOrder">Specifies the direction in which to sort results</param>
		/// <param name="videoFields">A list of the fields you wish to have populated in the Videos contained 
		/// in the returned object. If you omit this parameter, the method returns the following fields of 
		/// the video: id, name, shortDescription, longDescription, creationDate, publisheddate, lastModifiedDate, 
		/// linkURL, linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics, playsTotal, 
		/// playsTrailingWeek. If you use a token with URL access, this method also returns FLVURL, renditions, 
		/// FLVFullLength, videoFullLength.</param>
		/// <param name="customFields">A list of the custom fields you wish to have populated in the videos 
		/// contained in the returned object. If you omit this parameter, no custom fields are returned, unless you 
		/// include the value 'customFields' in the video_fields parameter.</param>
		/// <returns>A collection of videos matching the specified criteria.</returns>
		public BrightcoveItemCollection<BrightcoveVideo> SearchVideos(IEnumerable<FieldValuePair> all, IEnumerable<FieldValuePair> any, IEnumerable<FieldValuePair> none,
																	  int pageSize, int pageNumber, bool exact, SortBy sortBy, SortOrder sortOrder,
																	  IEnumerable<string> videoFields, IEnumerable<string> customFields)
		{
			return SearchVideos(all, any, none, pageSize, pageNumber, exact, sortBy, sortOrder, videoFields, customFields, true);
		}
コード例 #27
0
		/// <summary>
		/// Retrieves the videos uploaded by the specified user id. This method can be used to find videos submitted using
		/// the consumer-generated media (CGM) module.
		/// </summary>
		/// <param name="userId">The id of the user whose videos we'd like to retrieve.</param>
		/// <param name="pageSize">Number of items returned per page. A page is a subset of all of the items that satisfy the 
		/// request. The maximum page size is 100.</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="sortBy">The field by which to sort the results.</param>
		/// <param name="sortOrder">How to order the results: ascending or descending.</param>
		/// <param name="videoFields">A list of the fields you wish to have populated in the 
		/// Videos contained in the returned object. If you omit this parameter, the method returns the 
		/// following fields of the video: id, name, shortDescription, longDescription, creationDate, 
		/// publisheddate, lastModifiedDate, linkURL, linkText, tags, videoStillURL, thumbnailURL, 
		/// referenceId, length, economics, playsTotal, playsTrailingWeek. If you use a token with URL 
		/// access, this method also returns FLVURL, renditions, FLVFullLength, videoFullLength.</param>
		/// <param name="customFields">A list of the custom fields you wish to have populated 
		/// in the videos contained in the returned object. If you omit this parameter, no custom fields are 
		/// returned, unless you include the value 'customFields' in the video_fields parameter.</param>
		/// <param name="getItemCount">If true, also return how many total results there are.</param>
		/// <returns>An ItemCollection representing the requested page of Videos uploaded by the specified user, 
		/// in the order specified.</returns>
		public BrightcoveItemCollection<BrightcoveVideo> FindVideosByUserId(string userId, int pageSize, int pageNumber, SortBy sortBy, SortOrder sortOrder,
																			IEnumerable<string> videoFields, IEnumerable<string> customFields, bool getItemCount)
		{
			NameValueCollection parms = BuildBasicReadParams("find_videos_by_user_id");

			parms.Add("user_id", userId);
			parms.Add("page_size", pageSize.ToString());
			parms.Add("page_number", pageNumber.ToString());
			parms.Add("sort_by", sortBy.ToBrightcoveName());
			parms.Add("sort_order", sortOrder.ToBrightcoveName());
			parms.Add("get_item_count", getItemCount.ToString().ToLower());

			if (videoFields != null)
			{
				parms.AddRange("video_fields", videoFields);
			}

			if (customFields != null)
			{
				parms.AddRange("custom_fields", customFields);
			}

			return RunQuery<BrightcoveItemCollection<BrightcoveVideo>>(parms);
		}
コード例 #28
0
ファイル: ContactInfoDAL.cs プロジェクト: usmanasif/pyramid
 public static void deleteContactInfo(string Id)
 {
     MongoCollection <ContactInfo> objCollection = db.GetCollection <ContactInfo>("c_ContactInfo");
     var result = objCollection.FindAndRemove(Query.EQ("_id", ObjectId.Parse(Id)),
                                              SortBy.Ascending("_id"));
 }
コード例 #29
0
 /// <summary>
 /// Sorts the given missions with the given method
 /// </summary>
 /// <param name="missions">Missions.</param>
 /// <param name="sortBy">Sort by.</param>
 public static void Sort(List<Mission> missions, SortBy sortBy)
 {
     if (sortBy == SortBy.NAME) {
         missions.Sort (Mission.SortByName);
     } else if (sortBy == SortBy.REWARD) {
         missions.Sort (Mission.SortByReward);
     } else if (sortBy == SortBy.PACKAGE_ORDER) {
         missions.Sort (Mission.SortByPackageOrder);
     }
 }
コード例 #30
0
        internal void OrganizeSelection(SortBy sortBy, ProgressBy progressBy, string filterMod, bool initializing = false)
        {
            int displayMusicID = tMusicPlayer.AllMusic[DisplayBox].music;

            if (sortBy == SortBy.ID)
            {
                musicData = musicData.OrderBy(x => x.music).ToList();
            }
            if (sortBy == SortBy.Name)
            {
                musicData = musicData.OrderBy(x => x.name).ToList();
            }

            DisplayBox = tMusicPlayer.AllMusic.FindIndex(x => x.music == displayMusicID);

            SelectionList.Clear();

            if (!viewMode)
            {
                // Current view mode is GRID
                ItemSlotRow newRow = new ItemSlotRow(0, 400, 50);
                int         col    = 0;
                int         row    = 0;
                for (int i = 0; i < musicData.Count; i++)
                {
                    // Filter checks do not happen when initializing
                    // Include all music boxes if FilterMod is left empty
                    // Otherwise find music boxes with the same mod name as the selected filter mod
                    // If Availability isn't 'None' check if the box is obtained or not
                    if (!initializing)
                    {
                        MusicPlayerPlayer modplayer = Main.LocalPlayer.GetModPlayer <MusicPlayerPlayer>();
                        bool CheckFilterMod         = filterMod != "" && (musicData[i].mod != filterMod);
                        bool CheckObtained          = progressBy == ProgressBy.Obtained && modplayer.MusicBoxList.All(x => x.Type != musicData[i].musicbox);
                        bool CheckUnobtained        = progressBy == ProgressBy.Unobtained && modplayer.MusicBoxList.Any(x => x.Type == musicData[i].musicbox);

                        if (CheckFilterMod || CheckObtained || CheckUnobtained)
                        {
                            continue;
                        }
                    }

                    SelectionSlots[i]             = new MusicBoxSlot(musicData[i].musicbox, 0.85f);
                    SelectionSlots[i].Left.Pixels = 20f + (SelectionSlots[i].Width.Pixels + 10f) * col;
                    SelectionSlots[i].Top.Pixels  = (newRow.Height.Pixels / 2f) - (SelectionSlots[i].Height.Pixels / 2f);
                    SelectionSlots[i].Id          = $"SelectionSlotGrid_{i}";
                    newRow.Append(SelectionSlots[i]);
                    col++;
                    if (col == 5)
                    {
                        row++;
                        col = 0;
                        SelectionList.Add(newRow);
                        newRow = new ItemSlotRow(row, 400, 50);
                    }
                }
                if (col != 0)
                {
                    // Add the last row if we did not complete it
                    SelectionList.Add(newRow);
                }
            }
            else
            {
                // Current view mode is LIST
                ItemSlotRow newRow;
                for (int i = 0; i < musicData.Count; i++)
                {
                    // Include all music boxes if FilterMod is left empty
                    // Otherwise find music boxes with the same mod name as the selected filter mod
                    // If Availability isn't 'None' check if the box is obtained or not
                    if (!initializing)
                    {
                        MusicPlayerPlayer modplayer = Main.LocalPlayer.GetModPlayer <MusicPlayerPlayer>();
                        bool CheckFilterMod         = filterMod != "" && (musicData[i].mod != filterMod);
                        bool CheckObtained          = progressBy == ProgressBy.Obtained && modplayer.MusicBoxList.All(x => x.Type != musicData[i].musicbox);
                        bool CheckUnobtained        = progressBy == ProgressBy.Unobtained && modplayer.MusicBoxList.Any(x => x.Type == musicData[i].musicbox);

                        if (CheckFilterMod || CheckObtained || CheckUnobtained)
                        {
                            continue;
                        }
                    }

                    newRow = new ItemSlotRow(i, panelTextures[2].Bounds.Width, panelTextures[2].Bounds.Height);

                    // Item Slot
                    SelectionSlots[i]             = new MusicBoxSlot(musicData[i].musicbox, 0.85f);
                    SelectionSlots[i].Left.Pixels = 20f;
                    SelectionSlots[i].Top.Pixels  = (newRow.Height.Pixels / 2f) - (SelectionSlots[i].Height.Pixels / 2f);
                    SelectionSlots[i].Id          = $"SelectionSlotList_{i}";
                    newRow.Append(SelectionSlots[i]);

                    // Play button
                    HoverButton playSong = new HoverButton(buttonTextures, new Rectangle(24, 0, 22, 22))
                    {
                        Id = $"altplay_{musicData[i].music}",
                    };
                    playSong.Width.Pixels  = 22f;
                    playSong.Height.Pixels = 22f;
                    playSong.Left.Pixels   = SelectionSlots[i].Left.Pixels + SelectionSlots[i].Width.Pixels + 8f;
                    playSong.Top.Pixels    = (newRow.Height.Pixels / 2f) - (playSong.Height.Pixels / 2f);
                    playSong.OnClick      += (a, b) => ListViewPlaySong(playSong.Id);
                    newRow.Append(playSong);

                    // Song name and mod
                    UIText songName = new UIText(musicData[i].name, 0.85f);
                    songName.Left.Pixels = playSong.Left.Pixels + playSong.Width.Pixels + 8f;
                    songName.Top.Pixels  = (newRow.Height.Pixels / 2f) - 15f;
                    newRow.Append(songName);

                    UIText songMod = new UIText(musicData[i].mod, 0.85f);
                    songMod.Left.Pixels = playSong.Left.Pixels + playSong.Width.Pixels + 8f;
                    songMod.Top.Pixels  = (newRow.Height.Pixels / 2f) + 4f;
                    newRow.Append(songMod);

                    SelectionList.Add(newRow);
                }
            }

            SelectionList.SetScrollbar(selectionScrollBar);
        }
コード例 #31
0
 /// <summary>
 /// Selects the next sorting mechanism
 /// </summary>
 private void nextSort()
 {
     currentSort = currentSort.Next ();
     if (currentSort == SortBy.PACKAGE_ORDER && !currentPackage.ownOrder) {
         currentSort = currentSort.Next ();
     }
 }
コード例 #32
0
 public SortByEnum Get()
 {
     return(SortBy.From(GetRecord().Name));
 }
コード例 #33
0
 ADPagedReader <TResult> IConfigurationSession.FindPaged <TResult>(ADObjectId rootId, QueryScope scope, QueryFilter filter, SortBy sortBy, int pageSize)
 {
     return(base.InvokeWithAPILogging <ADPagedReader <TResult> >(() => this.GetSession().FindPaged <TResult>(rootId, scope, filter, sortBy, pageSize), "FindPaged"));
 }
コード例 #34
0
 public static void deleteEntertainment(string Id)
 {
     MongoCollection <Entertainment> objCollection = db.GetCollection <Entertainment>("c_Entertainment");
     var result = objCollection.FindAndRemove(Query.EQ("_id", ObjectId.Parse(Id)),
                                              SortBy.Ascending("_id"));
 }
コード例 #35
0
        public async Task <DataResult <Task <DomainProjectForAdmin> > > GetAsyncSequenceAsync(DataQueryOptions filter)
        {
            var query = new List <IMongoQuery>(filter.Filters.Count);

            // filtering
            List <DataFilterRule> filters = filter.Filters.Where(f => f.Value != null).ToList();

            foreach (DataFilterRule dataFilterRule in filters)
            {
                DataFilterRule f = dataFilterRule;

                if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                                   StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by name
                    query.Add(Query.Text(f.Value.ToString().ToLowerInvariant()));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by product type
                    var productId = Int32.Parse(f.Value.ToString());
                    query.Add(Query <ProjectEntity> .EQ(p => p.ProductId, productId));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.UserId),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user id
                    query.Add(Query <ProjectEntity> .EQ(p => p.UserId, f.Value.ToString()));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.UserName),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user name
                    List <UserEntity> profiles = await _userRepository.FindByNameAsync(f.Value.ToString());

                    if (profiles.Count == 0)
                    {
                        // no users found
                        return(new DataResult <Task <DomainProjectForAdmin> >(new Task <DomainProjectForAdmin>[] { }));
                    }

                    List <string> allIds = profiles.Select(prof => prof.Id).ToList();
                    query.Add(Query <ProjectEntity> .Where(p => allIds.Contains(p.UserId)));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // by created date
                    var date = (DateTime)f.Value;
                    switch (f.Type)
                    {
                    case DataFilterTypes.Equal:
                        query.Add(Query <ProjectEntity> .EQ(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThan:
                        query.Add(Query <ProjectEntity> .LT(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThanOrEqual:
                        query.Add(Query <ProjectEntity> .LTE(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThan:
                        query.Add(Query <ProjectEntity> .GT(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThanOrEqual:
                        query.Add(Query <ProjectEntity> .GTE(p => p.Created, date));
                        break;
                    }
                }
                else
                {
                    throw new NotSupportedException(string.Format("Filter {0} by property {1} is not supported", f.Type, f.Name));
                }
            }

            if (!filters.Any() && !string.IsNullOrEmpty(filter.OrderBy))
            {
                // MongoDb 2.6 HACK!!!
                // adding fake query to hint proper index

                if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                                   StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by name
                    query.Add(Query <ProjectEntity> .Exists(p => p.Name));
                }
                else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by created
                    query.Add(Query <ProjectEntity> .Exists(p => p.Created));
                }
                else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by product type
                    query.Add(Query <ProjectEntity> .Exists(p => p.ProductId));
                }
            }

            MongoCursor <ProjectEntity> cursor = _projectRepository.Collection.Find(query.Count > 0 ? Query.And(query) : Query.Null);
            IMongoSortBy sortOrder             = null;

            // sorting
            if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                               StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by name
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Name)
                    : SortBy <ProjectEntity> .Descending(p => p.Name);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by created
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Created)
                    : SortBy <ProjectEntity> .Descending(p => p.Created);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by product type
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.ProductId)
                    : SortBy <ProjectEntity> .Descending(p => p.ProductId);
            }

            if (sortOrder != null)
            {
                cursor.SetSortOrder(sortOrder);
            }

            // paging

            if (filter.Skip.HasValue)
            {
                cursor.SetSkip(filter.Skip.Value);
            }

            if (filter.Take.HasValue)
            {
                cursor.SetLimit(filter.Take.Value);
            }

            // Count of results
            long?count = null;

            if (filter.Count)
            {
                count = cursor.Count();
            }

            // post-processing

            return(new DataResult <Task <DomainProjectForAdmin> >(cursor.Select(GetProjectDataAsync), count));
        }
コード例 #36
0
        private void Sort_Click(object sender, EventArgs e)
        {
            if (ComboBox1.SelectedItem != null)
            {
                string txt = ComboBox1.SelectedItem.ToString();
                if (RadioButton1.Checked)
                {
                    switch (txt)
                    {
                    case "Car name":
                        var query = SortBy.Ascending("Car_name");
                        List <Form1.CarTable> list = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query).ToList();
                        metroGrid2.DataSource = list;
                        break;

                    case "Company":
                        var query1 = SortBy.Ascending("Car_company");
                        List <Form1.CarTable> list1 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query1).ToList();
                        metroGrid2.DataSource = list1;
                        break;

                    case "Model No.":
                        var query2 = SortBy.Ascending("Model");
                        List <Form1.CarTable> list2 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query2).ToList();
                        metroGrid2.DataSource = list2;
                        break;

                    case "Price":
                        var query3 = SortBy.Ascending("Price");
                        List <Form1.CarTable> list3 = collection.FindAllAs <Form1.CarTable>().OrderBy(c => double.Parse(c.Price)).ToList();
                        metroGrid2.DataSource = list3;
                        break;

                    case "Colour":
                        var query4 = SortBy.Ascending("Colour");
                        List <Form1.CarTable> list4 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query4).ToList();
                        metroGrid2.DataSource = list4;
                        break;

                    case "Mileage":
                        var query5 = SortBy.Ascending("Mileage");
                        List <Form1.CarTable> list5 = collection.FindAllAs <Form1.CarTable>().OrderBy(c => double.Parse(c.Mileage)).ToList();
                        metroGrid2.DataSource = list5;
                        break;

                    case "Class":
                        var query6 = SortBy.Ascending("Car_class");
                        List <Form1.CarTable> list6 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query6).ToList();
                        metroGrid2.DataSource = list6;
                        break;

                    case "Fuel":
                        var query7 = SortBy.Ascending("Fuel_type");
                        List <Form1.CarTable> list7 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query7).ToList();
                        metroGrid2.DataSource = list7;
                        break;
                    }
                }
                else if (RadioButton2.Checked)
                {
                    switch (txt)
                    {
                    case "Car name":
                        var query = SortBy.Descending("Car_name");
                        List <Form1.CarTable> list = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query).ToList();
                        metroGrid2.DataSource = list;
                        break;

                    case "Company":
                        var query1 = SortBy.Descending("Car_company");
                        List <Form1.CarTable> list1 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query1).ToList();
                        metroGrid2.DataSource = list1;
                        break;

                    case "Model No.":
                        var query2 = SortBy.Descending("Model");
                        List <Form1.CarTable> list2 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query2).ToList();
                        metroGrid2.DataSource = list2;
                        break;

                    case "Price":
                        var query3 = SortBy.Descending("Price");
                        List <Form1.CarTable> list3 = collection.FindAllAs <Form1.CarTable>().OrderBy(c => double.Parse(c.Price)).Reverse().ToList();
                        metroGrid2.DataSource = list3;
                        break;

                    case "Colour":
                        var query4 = SortBy.Descending("Colour");
                        List <Form1.CarTable> list4 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query4).ToList();
                        metroGrid2.DataSource = list4;
                        break;

                    case "Mileage":
                        var query5 = SortBy.Descending("Mileage");
                        List <Form1.CarTable> list5 = collection.FindAllAs <Form1.CarTable>().OrderBy(c => double.Parse(c.Mileage)).Reverse().ToList();
                        metroGrid2.DataSource = list5;
                        break;

                    case "Class":
                        var query6 = SortBy.Descending("Car_class");
                        List <Form1.CarTable> list6 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query6).ToList();
                        metroGrid2.DataSource = list6;
                        break;

                    case "Fuel":
                        var query7 = SortBy.Descending("Fuel_type");
                        List <Form1.CarTable> list7 = collection.FindAllAs <Form1.CarTable>().SetSortOrder(query7).ToList();
                        metroGrid2.DataSource = list7;
                        break;
                    }
                }
                else
                {
                    MessageBox.Show("Fields cannot be blank");
                }
                metroGrid2.Columns[0].Visible = false;
                metroGrid2.Columns[9].Visible = false;
            }
            else
            {
                MessageBox.Show("Fields cannot be blank");
            }
            Clear();
        }
コード例 #37
0
 public Pagination <IEnumerable <Item>, SortBy> CartItemss(int page, int pageSize, SortBy sortby)
 {
     return(new Pagination <IEnumerable <Item>, SortBy>()
     {
         PageSize = pageSize,
         CurrentPage = page,
         TotalCount = cartservice.TotalItems(),
         Data = cartservice.CartItems(page - 1, pageSize, sortby),
         Sorter = sortby
     });
 }
コード例 #38
0
 public UnitComparer(SortBy sortBy)
 {
     this.sortBy = sortBy;
 }
コード例 #39
0
 public Pagination <IEnumerable <Item>, SortBy> PagedItems(int page, int pageSize, SortBy sortby)
 {
     return(new Pagination <IEnumerable <Item>, SortBy>()
     {
         PageSize = pageSize,
         CurrentPage = page,
         TotalCount = itemsrepository.ItemssCount(),
         Data = itemsrepository.FilteredItems(page - 1, pageSize, sortby),
         Sorter = sortby
     });
 }
コード例 #40
0
        public ICollection <Organization> GetByCriteria(string criteria, PagingOptions paging, OrganizationSortBy sortBy, bool?paid = null, bool?suspended = null)
        {
            var options = new MongoOptions().WithPaging(paging);

            if (!String.IsNullOrWhiteSpace(criteria))
            {
                options.Query = options.Query.And(Query.Matches(FieldNames.Name, new BsonRegularExpression(String.Format("/{0}/i", criteria))));
            }

            if (paid.HasValue)
            {
                if (paid.Value)
                {
                    options.Query = options.Query.And(Query.NE(FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
                else
                {
                    options.Query = options.Query.And(Query.EQ(FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
            }

            if (suspended.HasValue)
            {
                if (suspended.Value)
                {
                    options.Query = options.Query.And(
                        Query.Or(
                            Query.And(
                                Query.NE(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                                Query.NE(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing)),
                                Query.NE(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Canceled))
                                ),
                            Query.EQ(FieldNames.IsSuspended, new BsonBoolean(true))));
                }
                else
                {
                    options.Query = options.Query.And(
                        Query.Or(
                            Query.EQ(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                            Query.EQ(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing)),
                            Query.EQ(FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Canceled))
                            ),
                        Query.EQ(FieldNames.IsSuspended, new BsonBoolean(false)));
                }
            }

            switch (sortBy)
            {
            case OrganizationSortBy.Newest:
                options.SortBy = SortBy.Descending(FieldNames.Id);
                break;

            case OrganizationSortBy.Subscribed:
                options.SortBy = SortBy.Descending(FieldNames.SubscribeDate);
                break;

            case OrganizationSortBy.MostActive:
                options.SortBy = SortBy.Descending(FieldNames.TotalEventCount);
                break;

            default:
                options.SortBy = SortBy.Ascending(FieldNames.Name);
                break;
            }

            return(Find <Organization>(options));
        }
コード例 #41
0
		/// <summary>
		/// Searches videos according to the criteria provided by the user.
		/// </summary>
		/// <param name="all">Specifies the field:value pairs for search criteria that MUST be present in 
		/// the index in order to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="any">Specifies the field:value pairs for search criteria AT LEAST ONE of which 
		/// must be present to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="none">Specifies the field:value pairs for search criteria that MUST NOT be present 
		/// to return a hit in the result set. If the field's name is not present, it is assumed to be 
		/// name and shortDescription.</param>
		/// <param name="pageSize">Number of items returned per page. (max 100)</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="exact">If true, disables fuzzy search and requires an exact match of search terms. 
		/// A fuzzy search does not require an exact match of the indexed terms, but will return a hit for 
		/// terms that are closely related based on language-specific criteria. The fuzzy search is 
		/// available only if your account is based in the United States.</param>
		/// <param name="sortBy">Specifies the field by which to sort results.</param>
		/// <param name="sortOrder">Specifies the direction in which to sort results</param>
		/// <param name="videoFields">A list of the fields you wish to have populated in the Videos contained 
		/// in the returned object. If you omit this parameter, the method returns the following fields of 
		/// the video: id, name, shortDescription, longDescription, creationDate, publisheddate, lastModifiedDate, 
		/// linkURL, linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics, playsTotal, 
		/// playsTrailingWeek. If you use a token with URL access, this method also returns FLVURL, renditions, 
		/// FLVFullLength, videoFullLength.</param>
		/// <param name="customFields">A list of the custom fields you wish to have populated in the videos 
		/// contained in the returned object. If you omit this parameter, no custom fields are returned, unless you 
		/// include the value 'customFields' in the video_fields parameter.</param>
		/// <param name="getItemCount">If true, also return how many total results there are.</param>
		/// <returns>A collection of videos matching the specified criteria.</returns>
		public BrightcoveItemCollection<BrightcoveVideo> SearchVideos(IEnumerable<FieldValuePair> all, IEnumerable<FieldValuePair> any, IEnumerable<FieldValuePair> none,
																	  int pageSize, int pageNumber, bool exact, SortBy sortBy, SortOrder sortOrder,
																	  IEnumerable<string> videoFields, IEnumerable<string> customFields, bool getItemCount)
		{
			NameValueCollection parms = BuildBasicReadParams("search_videos");

			parms.Add("get_item_count", getItemCount.ToString().ToLower());
			parms.Add("exact", exact.ToString().ToLower());
			parms.Add("page_size", pageSize.ToString());
			parms.Add("page_number", pageNumber.ToString());
			parms.Add("sort_by", sortBy.ToBrightcoveName());
			parms.Add("sort_order", sortOrder.ToBrightcoveName());

			if (videoFields != null)
			{
				parms.AddRange("video_fields", videoFields);
			}

			if (customFields != null)
			{
				parms.AddRange("custom_fields", customFields);
			}

			if (all != null)
			{
				parms.AddRange("all", all.Select(o => o.ToBrightcoveString()));
			}

			if (any != null)
			{
				parms.AddRange("any", any.Select(o => o.ToBrightcoveString()));
			}

			if (none != null)
			{
				parms.AddRange("none", none.Select(o => o.ToBrightcoveString()));
			}

			return RunQuery<BrightcoveItemCollection<BrightcoveVideo>>(parms);
		}
コード例 #42
0
        public IQueryable <Complaint> SearchComplaints(
            SortBy sort = SortBy.IdDesc,
            SearchComplaintStatus?complaintStatus = null,
            SearchDeleteStatus?deleteStatus       = null,
            DateTime?DateReceivedFrom             = null,
            DateTime?DateReceivedTo          = null,
            string ReceivedById              = null,
            DateTime?DateComplaintClosedFrom = null,
            DateTime?DateComplaintClosedTo   = null,
            string CallerName          = null,
            string CallerRepresents    = null,
            string ComplaintNature     = null,
            string ComplaintLocation   = null,
            string ComplaintDirections = null,
            string ComplaintCity       = null,
            int?ComplaintCountyId      = null,
            Guid?ConcernId             = null,
            string SourceFacilityId    = null,
            string SourceFacilityName  = null,
            string SourceContactName   = null,
            string SourceStreet        = null,
            string SourceCity          = null,
            int?SourceStateId          = null,
            string SourcePostalCode    = null,
            Guid?Office  = null,
            string Owner = null
            )
        {
            var complaints = _context.Complaints.AsNoTracking();

            // Filters
            if (complaintStatus.HasValue)
            {
                switch (complaintStatus.Value)
                {
                case SearchComplaintStatus.Closed:
                    complaints = complaints.Where(e => e.Status == ComplaintStatus.Closed);
                    break;

                case SearchComplaintStatus.New:
                    complaints = complaints.Where(e => e.Status == ComplaintStatus.New);
                    break;

                case SearchComplaintStatus.ReviewPending:
                    complaints = complaints.Where(e => e.Status == ComplaintStatus.ReviewPending);
                    break;

                case SearchComplaintStatus.UnderInvestigation:
                    complaints = complaints.Where(e => e.Status == ComplaintStatus.UnderInvestigation);
                    break;

                case SearchComplaintStatus.Open:
                    complaints = complaints.Where(e => e.Status != ComplaintStatus.Closed);
                    break;
                }
            }

            if (deleteStatus.HasValue)
            {
                if (deleteStatus.Value == SearchDeleteStatus.Deleted)
                {
                    complaints = complaints.Where(e => e.Deleted);
                }
                // Do not filter if deleteStatus.Value == SearchDeleteStatus.All
            }
            else
            {
                complaints = complaints
                             .Where(e => !e.Deleted);
            }

            if (DateReceivedFrom.HasValue)
            {
                complaints = complaints.Where(e => DateReceivedFrom.Value <= e.DateReceived);
            }

            if (DateReceivedTo.HasValue)
            {
                complaints = complaints.Where(e => e.DateReceived.Date <= DateReceivedTo.Value);
            }

            if (!string.IsNullOrEmpty(ReceivedById))
            {
                complaints = complaints.Where(e => e.ReceivedById == ReceivedById);
            }

            if (DateComplaintClosedFrom.HasValue)
            {
                complaints = complaints.Where(e => e.DateComplaintClosed.HasValue && DateComplaintClosedFrom.Value <= e.DateComplaintClosed.Value);
            }

            if (DateComplaintClosedTo.HasValue)
            {
                complaints = complaints.Where(e => e.DateComplaintClosed.HasValue && e.DateComplaintClosed.Value.Date <= DateComplaintClosedTo.Value);
            }

            if (!string.IsNullOrEmpty(CallerName))
            {
                complaints = complaints.Where(e => e.CallerName.ToLower().Contains(CallerName.ToLower()));
            }

            if (!string.IsNullOrEmpty(CallerRepresents))
            {
                complaints = complaints.Where(e => e.CallerRepresents.ToLower().Contains(CallerRepresents.ToLower()));
            }

            if (!string.IsNullOrEmpty(ComplaintNature))
            {
                complaints = complaints.Where(e => e.ComplaintNature.ToLower().Contains(ComplaintNature.ToLower()));
            }

            if (!string.IsNullOrEmpty(ComplaintLocation))
            {
                complaints = complaints.Where(e => e.ComplaintLocation.ToLower().Contains(ComplaintLocation.ToLower()));
            }

            if (!string.IsNullOrEmpty(ComplaintDirections))
            {
                complaints = complaints.Where(e => e.ComplaintDirections.ToLower().Contains(ComplaintDirections.ToLower()));
            }

            if (!string.IsNullOrEmpty(ComplaintCity))
            {
                complaints = complaints.Where(e => e.ComplaintCity.ToLower().Contains(ComplaintCity.ToLower()));
            }

            if (ComplaintCountyId.HasValue)
            {
                complaints = complaints.Where(e => e.ComplaintCountyId.HasValue && e.ComplaintCountyId.Value == ComplaintCountyId.Value);
            }

            if (ConcernId.HasValue)
            {
                complaints = complaints
                             .Where(e => (e.PrimaryConcernId.HasValue && e.PrimaryConcernId.Value == ConcernId.Value) ||
                                    (e.SecondaryConcernId.HasValue && e.SecondaryConcernId.Value == ConcernId.Value));
            }

            if (!string.IsNullOrEmpty(SourceFacilityId))
            {
                complaints = complaints.Where(e => e.SourceFacilityId.ToLower().Contains(SourceFacilityId.ToLower()));
            }

            if (!string.IsNullOrEmpty(SourceFacilityName))
            {
                complaints = complaints.Where(e => e.SourceFacilityName.ToLower().Contains(SourceFacilityName.ToLower()));
            }

            if (!string.IsNullOrEmpty(SourceContactName))
            {
                complaints = complaints.Where(e => e.SourceContactName.ToLower().Contains(SourceContactName.ToLower()));
            }

            if (!string.IsNullOrEmpty(SourceStreet))
            {
                complaints = complaints
                             .Where(e => e.SourceStreet.ToLower().Contains(SourceStreet.ToLower()) ||
                                    e.SourceStreet2.ToLower().Contains(SourceStreet.ToLower()));
            }

            if (!string.IsNullOrEmpty(SourceCity))
            {
                complaints = complaints.Where(e => e.SourceCity.ToLower().Contains(SourceCity.ToLower()));
            }

            if (SourceStateId.HasValue)
            {
                complaints = complaints.Where(e => e.SourceStateId.HasValue && e.SourceStateId.Value == SourceStateId.Value);
            }

            if (!string.IsNullOrEmpty(SourcePostalCode))
            {
                complaints = complaints.Where(e => e.SourcePostalCode.ToLower().Contains(SourcePostalCode.ToLower()));
            }

            if (Office.HasValue)
            {
                complaints = complaints.Where(e => e.CurrentOfficeId == Office.Value);
            }

            if (!string.IsNullOrEmpty(Owner))
            {
                complaints = complaints.Where(e => e.CurrentOwnerId == Owner);
            }

            // Sort
            complaints = sort switch
            {
                SortBy.IdAsc => complaints.OrderBy(e => e.Id),
                SortBy.ReceivedDateAsc => complaints.OrderBy(e => e.DateReceived).ThenBy(e => e.Id),
                SortBy.ReceivedDateDesc => complaints.OrderByDescending(e => e.DateReceived).ThenBy(e => e.Id),
                SortBy.StatusAsc => complaints.OrderBy(e => (int)e.Status).ThenBy(e => e.Id),
                SortBy.StatusDesc => complaints.OrderByDescending(e => (int)e.Status).ThenBy(e => e.Id),
                _ => complaints.OrderByDescending(e => e.Id),
            };

            return(complaints
                   .Include(e => e.CurrentOffice)
                   .Include(e => e.CurrentOwner)
                   .Include(e => e.ReceivedBy)
                   .Include(e => e.SourceState));
        }
コード例 #43
0
		/// <summary>
		/// Searches videos according to the criteria provided by the user.
		/// </summary>
		/// <param name="all">Specifies the field:value pairs for search criteria that MUST be present in 
		/// the index in order to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="any">Specifies the field:value pairs for search criteria AT LEAST ONE of which 
		/// must be present to return a hit in the result set. If the field's name is not present, it is 
		/// assumed to be name and shortDescription.</param>
		/// <param name="none">Specifies the field:value pairs for search criteria that MUST NOT be present 
		/// to return a hit in the result set. If the field's name is not present, it is assumed to be 
		/// name and shortDescription.</param>
		/// <param name="pageSize">Number of items returned per page. (max 100)</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="exact">If true, disables fuzzy search and requires an exact match of search terms. 
		/// A fuzzy search does not require an exact match of the indexed terms, but will return a hit for 
		/// terms that are closely related based on language-specific criteria. The fuzzy search is 
		/// available only if your account is based in the United States.</param>
		/// <param name="sortBy">Specifies the field by which to sort results.</param>
		/// <param name="sortOrder">Specifies the direction in which to sort results</param>
		public BrightcoveItemCollection<BrightcoveVideo> SearchVideos(IEnumerable<FieldValuePair> all, IEnumerable<FieldValuePair> any, IEnumerable<FieldValuePair> none,
																	  int pageSize, int pageNumber, bool exact, SortBy sortBy, SortOrder sortOrder)
		{
			return SearchVideos(all, any, none, pageSize, pageNumber, exact, sortBy, sortOrder, null, null);
		}
コード例 #44
0
ファイル: PostRepository.cs プロジェクト: eshengsky/iBlog
 /// <summary>
 /// 获取筛选条件下的所有文章
 /// </summary>
 /// <param name="cateAlias"></param>
 /// <param name="pageIndex"></param>
 /// <param name="pageSize"></param>
 /// <param name="sortBy"></param>
 /// <param name="filtType"></param>
 /// <param name="keyword"></param>
 /// <returns></returns>
 public async Task<PostResult> GetPosts(string cateAlias, int pageIndex, int pageSize, SortBy sortBy = SortBy.Latest, FiltType filtType = FiltType.Content, string keyword = "")
 {
     var result = new PostResult();
     var query = await _posts.Collection.Find(x => x.IsActive).ToListAsync();
     if (!string.IsNullOrWhiteSpace(cateAlias))
     {
         query = query.Where(x => x.CategoryAlias.ToUpper() == cateAlias.ToUpper()).ToList();
     }
     if (!string.IsNullOrWhiteSpace(keyword))
     {
         if (filtType == FiltType.Title)
         {
             query = query.Where(x => x.Title.Contains(keyword)).ToList();
         }
         else if (filtType == FiltType.Label)
         {
             query = query.Where(x => x.Labels.Contains(keyword)).ToList();
         }
         else if (filtType == FiltType.Datetime)
         {
             DateTime dt;
             DateTime.TryParse(keyword, out dt);
             query = query.Where(x => x.CreateTime.Date == dt.Date).ToList();
         }
         else
         {
             query = query.Where(x => x.Content != null ? (x.Title.Contains(keyword) || x.Summary.Contains(keyword) || x.Content.Contains(keyword)) : (x.Title.Contains(keyword) || x.Summary.Contains(keyword))).ToList();
         }
     }
     result.PostCount = query.Count;
     if (sortBy == SortBy.Hotest)
     {
         query = query.OrderByDescending(x => x.ViewCount).ThenByDescending(x => x.CreateTime).ToList();
     }
     else
     {
         query = query.OrderByDescending(x => x.CreateTime).ToList();
     }
     result.PostList = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
     return result;
 }
コード例 #45
0
		/// <summary>
		/// Retrieves the videos uploaded by the specified user id. This method can be used to find videos submitted using
		/// the consumer-generated media (CGM) module.
		/// </summary>
		/// <param name="userId">The id of the user whose videos we'd like to retrieve.</param>
		/// <param name="pageSize">Number of items returned per page. A page is a subset of all of the items that satisfy the 
		/// request. The maximum page size is 100.</param>
		/// <param name="pageNumber">The zero-indexed number of the page to return.</param>
		/// <param name="sortBy">The field by which to sort the results.</param>
		/// <param name="sortOrder">How to order the results: ascending or descending.</param>
		/// <param name="videoFields">A list of the fields you wish to have populated in the 
		/// Videos contained in the returned object. If you omit this parameter, the method returns the 
		/// following fields of the video: id, name, shortDescription, longDescription, creationDate, 
		/// publisheddate, lastModifiedDate, linkURL, linkText, tags, videoStillURL, thumbnailURL, 
		/// referenceId, length, economics, playsTotal, playsTrailingWeek. If you use a token with URL 
		/// access, this method also returns FLVURL, renditions, FLVFullLength, videoFullLength.</param>
		/// <returns>An ItemCollection representing the requested page of Videos uploaded by the specified user, 
		/// in the order specified.</returns>
		public BrightcoveItemCollection<BrightcoveVideo> FindVideosByUserId(string userId, int pageSize, int pageNumber, SortBy sortBy, SortOrder sortOrder,
																			IEnumerable<string> videoFields)
		{
			return FindVideosByUserId(userId, pageSize, pageNumber, sortBy, sortOrder, videoFields, null);
		}
コード例 #46
0
        internal static SortBy ShowSortMenu(SortBy currentSortBy)
        {
            var newSortBy = new SortBy();

            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg == null) return null;

            dlg.Reset();
            dlg.SetHeading(495); // Sort options

            // Add generic sortby fields
            GUIListItem pItem = new GUIListItem(Translation.Title);
            dlg.Add(pItem);
            pItem.ItemId = (int)SortingFields.Title;

            pItem = new GUIListItem(Translation.ReleaseDate);
            dlg.Add(pItem);
            pItem.ItemId = (int)SortingFields.ReleaseDate;

            pItem = new GUIListItem(Translation.Score);
            dlg.Add(pItem);
            pItem.ItemId = (int)SortingFields.Score;

            pItem = new GUIListItem(Translation.Votes);
            dlg.Add(pItem);
            pItem.ItemId = (int)SortingFields.Votes;

            pItem = new GUIListItem(Translation.Runtime);
            dlg.Add(pItem);
            pItem.ItemId = (int)SortingFields.Runtime;

            // Trending
            if (GUIWindowManager.ActiveWindow == (int)TraktGUIWindows.TrendingMovies ||
                GUIWindowManager.ActiveWindow == (int)TraktGUIWindows.TrendingShows) {
                pItem = new GUIListItem(Translation.Watchers);
                dlg.Add(pItem);
                pItem.ItemId = (int)SortingFields.PeopleWatching;
            }

            // Watchlist
            if (GUIWindowManager.ActiveWindow == (int)TraktGUIWindows.WatchedListMovies ||
                GUIWindowManager.ActiveWindow == (int)TraktGUIWindows.WatchedListShows) {
                pItem = new GUIListItem(Translation.Inserted);
                dlg.Add(pItem);
                pItem.ItemId = (int)SortingFields.WatchListInserted;
            }

            // set the focus to currently used sort method
            dlg.SelectedLabel = (int)currentSortBy.Field;

            // show dialog and wait for result
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            if (dlg.SelectedId == -1) return null;

            switch (dlg.SelectedId)
            {
                case (int)SortingFields.Title:
                    newSortBy.Field = SortingFields.Title;
                    break;

                case (int)SortingFields.ReleaseDate:
                    newSortBy.Field = SortingFields.ReleaseDate;
                    newSortBy.Direction = SortingDirections.Descending;
                    break;

                case (int)SortingFields.Score:
                    newSortBy.Field = SortingFields.Score;
                    newSortBy.Direction = SortingDirections.Descending;
                    break;

                case (int)SortingFields.Votes:
                    newSortBy.Field = SortingFields.Votes;
                    newSortBy.Direction = SortingDirections.Descending;
                    break;

                case (int)SortingFields.Runtime:
                    newSortBy.Field = SortingFields.Runtime;
                    break;

                case (int)SortingFields.PeopleWatching:
                    newSortBy.Field = SortingFields.PeopleWatching;
                    newSortBy.Direction = SortingDirections.Descending;
                    break;

                case (int)SortingFields.WatchListInserted:
                    newSortBy.Field = SortingFields.WatchListInserted;
                    break;

                default:
                    newSortBy.Field = SortingFields.Title;
                    break;
            }

            return newSortBy;
        }
コード例 #47
0
        public override void ReadSectionSettings()
        {
            base.ReadSectionSettings();

                try
                {
                    this._allowComments = Convert.ToBoolean(base.Section.Settings["ALLOW_COMMENTS"]);
                    this._allowAnonymousComments = Convert.ToBoolean(base.Section.Settings["ALLOW_ANONYMOUS_COMMENTS"]);
                    this._allowSyndication = Convert.ToBoolean(base.Section.Settings["ALLOW_SYNDICATION"]);
                    this._showArchive = Convert.ToBoolean(base.Section.Settings["SHOW_ARCHIVE"]);
                    this._showAuthor = Convert.ToBoolean(base.Section.Settings["SHOW_AUTHOR"]);
                    this._showCategory = Convert.ToBoolean(base.Section.Settings["SHOW_CATEGORY"]);
                    this._showDateTime = Convert.ToBoolean(base.Section.Settings["SHOW_DATETIME"]);
                    this._numberOfArticlesInList = Convert.ToInt32(base.Section.Settings["NUMBER_OF_ARTICLES_IN_LIST"]);
                    this._displayType = (DisplayType)Enum.Parse(typeof(DisplayType), base.Section.Settings["DISPLAY_TYPE"].ToString());
                    this._sortBy = (SortBy)Enum.Parse(typeof(SortBy), base.Section.Settings["SORT_BY"].ToString());
                    this._sortDirection = (SortDirection)Enum.Parse(typeof(SortDirection), base.Section.Settings["SORT_DIRECTION"].ToString());
                }
                catch
                {
                    // Only if the module settings are not in the database yet for some reason.
                    this._sortBy = SortBy.DateOnline;
                    this._sortDirection = SortDirection.DESC;
                }
        }
コード例 #48
0
 /// <summary>
 /// Controls the order of children added to items decorated with this attribute.
 /// </summary>
 public static Builder <IDefinitionRefiner> SortChildren <TModel>(this IContentRegistration <TModel> registration, SortBy sortingOrder, string expression = null)
 {
     return(registration.RegisterRefiner <IDefinitionRefiner>(new AppendAttributeRefiner(new SortChildrenAttribute(sortingOrder)
     {
         SortExpression = expression
     })));
 }
コード例 #49
0
 public static Builder<IDefinitionRefiner> SortChildren(this IContentRegistration registration, SortBy sortingOrder, string expression = null)
 {
     return registration.RegisterRefiner<IDefinitionRefiner>(new AppendAttributeRefiner(new SortChildrenAttribute(sortingOrder) { SortExpression = expression }));
 }
コード例 #50
0
        // <summary>
        /// Deletes the role with the specified id
        /// </summary>
        /// <param name="roleId">Id of the role to delete</param>
        /// <returns>Result of the operation, true if was ok</returns>
        public bool Delete(ObjectId id)
        {
            Parcel parcel = Parcels.FindOneById(id);
            FindAndModifyResult parcelResult = Parcels.FindAndRemove(Query.EQ("_id", id), SortBy.Ascending("_id"));

            return(parcelResult.Ok);
        }
コード例 #51
0
ファイル: SongLibrary.cs プロジェクト: Daspeed/SongRequest
        /// <summary>
        /// Get correct sort string
        /// </summary>
        private string GetSortString(Song song, SortBy sortBy, int level)
        {
            if (sortBy == SortBy.Artist)
            {
                switch (level)
                {
                    case 0:
                        return song.Artist;
                    case 1:
                        return song.Name;
                    case 2:
                        return song.Year;
                }
            }
            else if (sortBy == SortBy.Name)
            {
                switch (level)
                {
                    case 0:
                        return song.Name;
                    case 1:
                        return song.Artist;
                    case 2:
                        return song.TempId;
                }
            }
            else if (sortBy == SortBy.Date)
            {
                switch (level)
                {
                    case 0:
                        return song.DateCreated;
                    case 1:
                        return song.Artist;
                    case 2:
                        return song.Name;
                }
            }
            else if (sortBy == SortBy.PlayDate)
            {
                switch (level)
                {
                    case 0:
                        if (song.LastPlayDateTime.HasValue)
                            return song.LastPlayDateTime.Value.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        return string.Empty;
                    case 1:
                        return song.Artist;
                    case 2:
                        return song.Name;
                }
            }
            else if (sortBy == SortBy.Genre)
            {
                switch (level)
                {
                    case 0:
                        return song.Genre;
                    case 1:
                        return song.Artist;
                    case 2:
                        return song.Name;
                }
            }
            else if (sortBy == SortBy.Year)
            {
                switch (level)
                {
                    case 0:
                        return song.Year;
                    case 1:
                        return song.Artist;
                    case 2:
                        return song.Name;
                }
            }
            else if (sortBy == SortBy.Rating)
            {
                switch (level)
                {
                    case 0:
                        return song.Rating.ToString("00");
                    case 1:
                        return song.Name;
                    case 2:
                        return song.Artist;
                }
            }
            else if (sortBy == SortBy.Album)
            {
                switch (level)
                {
                    case 0:
                        return song.Album;
                    case 1:
                        return song.Name;
                    case 2:
                        return song.Artist;
                }
            }

            return string.Empty;
        }
コード例 #52
0
ファイル: ApiController.cs プロジェクト: radtek/Plato
        public async Task <IActionResult> Get(
            int page        = 1,
            int size        = 10,
            string keywords = "",
            SortBy sort     = SortBy.LastReply,
            OrderBy order   = OrderBy.Desc)
        {
            // Get search settings
            var searchSettings = await _searchSettingsStore.GetAsync();

            // Set default sort column if auto is specified
            if (sort == SortBy.LastReply)
            {
                // Get search settings
                if (searchSettings != null)
                {
                    sort = searchSettings.SearchType == SearchTypes.Tsql
                        ? SortBy.LastReply
                        : SortBy.Rank;
                }
                else
                {
                    sort = SortBy.LastReply;
                }
            }

            // Get results
            var entities = await _searchService
                           .ConfigureDb(o =>
            {
                if (searchSettings != null)
                {
                    o.SearchType = searchSettings.SearchType;
                }
            })
                           .ConfigureQuery(async q =>
            {
                // Hide hidden?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchHidden))
                {
                    q.HidePrivate.True();
                }

                // Hide spam?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchSpam))
                {
                    q.HideSpam.True();
                }

                // Hide deleted?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchDeleted))
                {
                    q.HideDeleted.True();
                }

                // Hide private?
                if (!await _authorizationService.AuthorizeAsync(HttpContext.User,
                                                                Permissions.SearchPrivate))
                {
                    q.HidePrivate.True();
                }
            })
                           .GetResultsAsync(new EntityIndexOptions()
            {
                Search = keywords,
                Sort   = sort,
                Order  = order
            }, new PagerOptions()
            {
                Page = page,
                Size = size
            });

            IPagedResults <SearchApiResult> results = null;

            if (entities != null)
            {
                results = new PagedResults <SearchApiResult>
                {
                    Total = entities.Total
                };

                foreach (var entity in entities.Data)
                {
                    var url = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                    {
                        ["area"]       = entity.ModuleId,
                        ["controller"] = "Home",
                        ["action"]     = "Display",
                        ["opts.id"]    = entity.Id,
                        ["opts.alias"] = entity.Alias
                    });

                    if (string.IsNullOrEmpty(entity.CreatedBy.Avatar.Url))
                    {
                        entity.CreatedBy.Avatar.Url = _contextFacade.GetRouteUrl(entity.CreatedBy.Avatar.DefaultRoute);
                    }

                    if (string.IsNullOrEmpty(entity.ModifiedBy.Avatar.Url))
                    {
                        entity.ModifiedBy.Avatar.Url = _contextFacade.GetRouteUrl(entity.ModifiedBy.Avatar.DefaultRoute);
                    }

                    results.Data.Add(new SearchApiResult()
                    {
                        Id        = entity.Id,
                        CreatedBy = new UserApiResult()
                        {
                            Id          = entity.CreatedBy.Id,
                            DisplayName = entity.CreatedBy.DisplayName,
                            UserName    = entity.CreatedBy.UserName,
                            Avatar      = entity.CreatedBy.Avatar,
                            Url         = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.CreatedBy.Id,
                                ["opts.alias"] = entity.CreatedBy.Alias
                            })
                        },
                        ModifiedBy = new UserApiResult()
                        {
                            Id          = entity.ModifiedBy.Id,
                            DisplayName = entity.ModifiedBy.DisplayName,
                            UserName    = entity.ModifiedBy.UserName,
                            Avatar      = entity.ModifiedBy.Avatar,
                            Url         = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.ModifiedBy.Id,
                                ["opts.alias"] = entity.ModifiedBy.Alias
                            })
                        },
                        LastReplyBy = new UserApiResult()
                        {
                            Id          = entity.LastReplyBy.Id,
                            DisplayName = entity.LastReplyBy.DisplayName,
                            UserName    = entity.LastReplyBy.UserName,
                            Avatar      = entity.LastReplyBy.Avatar,
                            Url         = _contextFacade.GetRouteUrl(new RouteValueDictionary()
                            {
                                ["area"]       = "Plato.Users",
                                ["controller"] = "Home",
                                ["action"]     = "Display",
                                ["opts.id"]    = entity.LastReplyBy.Id,
                                ["opts.alias"] = entity.LastReplyBy.Alias
                            })
                        },
                        Title       = entity.Title,
                        Excerpt     = entity.Abstract,
                        Url         = url,
                        CreatedDate = new FriendlyDate()
                        {
                            Text  = entity.CreatedDate.ToPrettyDate(),
                            Value = entity.CreatedDate
                        },
                        ModifiedDate = new FriendlyDate()
                        {
                            Text  = entity.ModifiedDate.ToPrettyDate(),
                            Value = entity.ModifiedDate
                        },
                        LastReplyDate = new FriendlyDate()
                        {
                            Text  = entity.LastReplyDate.ToPrettyDate(),
                            Value = entity.LastReplyDate
                        },
                        Relevance = entity.Relevance
                    });
                }
            }

            IPagedApiResults <SearchApiResult> output = null;

            if (results != null)
            {
                output = new PagedApiResults <SearchApiResult>()
                {
                    Page       = page,
                    Size       = size,
                    Total      = results.Total,
                    TotalPages = results.Total.ToSafeCeilingDivision(size),
                    Data       = results.Data
                };
            }

            return(output != null
                ? base.Result(output)
                : base.NoResults());
        }
コード例 #53
0
 public SortChildrenAttribute(SortBy orderBy)
 {
     this.OrderBy = orderBy;
 }
コード例 #54
0
        private void load_subject()
        {
            MongoClient   client = new MongoClient("mongodb://localhost");
            MongoServer   server = client.GetServer();
            MongoDatabase db     = server.GetDatabase("NBA");
            //in this subjects are orderd in ascending order as they are added in subject add form
            MongoCursor <Subjects> put = db.GetCollection <Subjects>("Subjects").Find(Query.And(Query.EQ("academic_year", academic_year), Query.EQ("clas", clas), Query.EQ("semester", sem))).SetSortOrder(SortBy.Ascending("srno"));
            //it will count how many subjects are added
            long count = put.Count();

            if (count == 0)
            {
                this.Hide();
                MessageBox.Show("No Subjects Added!");
                return;
            }
            int x = 0;

            foreach (Subjects i in put)
            {
                //subject name and their corresponding marks will be searched in collection
                sub[x++] = i.Subject_Name;
                sub[x++] = i.marks;
            }
            show_sub(Convert.ToInt32(count));
        }
コード例 #55
0
        internal static string GetSortByString(SortBy currentSortBy)
        {
            string strLine = string.Empty;

            switch (currentSortBy.Field)
            {
                case SortingFields.Title:
                    strLine = Translation.Title;
                    break;

                case SortingFields.ReleaseDate:
                    strLine = Translation.ReleaseDate;
                    break;

                case SortingFields.Score:
                    strLine = Translation.Score;
                    break;

                case SortingFields.Votes:
                    strLine = Translation.Votes;
                    break;

                case SortingFields.Runtime:
                    strLine = Translation.Runtime;
                    break;

                case SortingFields.PeopleWatching:
                    strLine = Translation.Watchers;
                    break;

                case SortingFields.WatchListInserted:
                    strLine = Translation.Inserted;
                    break;

                default:
                    strLine = Translation.Title;
                    break;
            }

            return string.Format(Translation.SortBy, strLine);
        }
コード例 #56
0
 public JobHistory GetMostRecent(string jobName)
 {
     return(FindOne <JobHistory>(new OneOptions().WithQuery(Query.EQ(FieldNames.Name, jobName)).WithSort(SortBy.Descending(FieldNames.StartTime))));
 }
コード例 #57
0
 public SortChildrenAttribute(SortBy orderBy)
 {
     this.OrderBy = orderBy;
 }
コード例 #58
0
        public PagedResult <Organization> List(string criteria = null, bool?isPaidPlan = null, bool?isSuspended = null, OrganizationSortBy sortBy = OrganizationSortBy.Newest, int page = 1, int pageSize = 10)
        {
            int skip = (page - 1) * pageSize;

            if (skip < 0)
            {
                skip = 0;
            }

            if (pageSize < 1)
            {
                pageSize = 10;
            }

            var queries = new List <IMongoQuery>();

            if (!String.IsNullOrWhiteSpace(criteria))
            {
                queries.Add(Query.Matches(OrganizationRepository.FieldNames.Name, new BsonRegularExpression(String.Format("/{0}/i", criteria))));
            }

            if (isPaidPlan.HasValue)
            {
                if (isPaidPlan.Value)
                {
                    queries.Add(Query.NE(OrganizationRepository.FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
                else
                {
                    queries.Add(Query.EQ(OrganizationRepository.FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
            }

            if (isSuspended.HasValue)
            {
                if (isSuspended.Value)
                {
                    queries.Add(
                        Query.Or(
                            Query.And(
                                Query.NE(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                                Query.NE(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing))),
                            Query.EQ(OrganizationRepository.FieldNames.IsSuspended, new BsonBoolean(true))));
                }
                else
                {
                    queries.Add(Query.And(
                                    Query.Or(
                                        Query.EQ(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                                        Query.EQ(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing))),
                                    Query.EQ(OrganizationRepository.FieldNames.IsSuspended, new BsonBoolean(false))));
                }
            }

            SortByBuilder sort;

            if (sortBy == OrganizationSortBy.Newest)
            {
                sort = SortBy.Descending(OrganizationRepository.FieldNames.Id);
            }
            else if (sortBy == OrganizationSortBy.MostActive)
            {
                sort = SortBy.Descending(OrganizationRepository.FieldNames.TotalErrorCount);
            }
            else
            {
                sort = SortBy.Ascending(OrganizationRepository.FieldNames.Name);
            }

            MongoCursor <Organization> query   = queries.Count > 0 ? ((OrganizationRepository)_repository).Collection.Find(Query.And(queries)) : ((OrganizationRepository)_repository).Collection.FindAll();
            List <Organization>        results = query.SetSortOrder(sort).SetSkip(skip).SetLimit(pageSize).ToList();

            return(new PagedResult <Organization>(results)
            {
                Page = page,
                PageSize = pageSize,
                TotalCount = query.Count()
            });
        }
コード例 #59
0
        /// <summary>
        /// Standard search
        /// </summary>
        /// <param name="keySearch">String search</param>
        /// <returns></returns>
        public List<SearchDocumentResult> StandardSearch(string keySearch, SortBy sortBy)
        {
            var result = new List<SearchDocumentResult>();

            string strResponse = string.Empty;

            // String search query
            string strQuery = BuildSearchQuery(keySearch);

            // String search option
            string strOption = BuildSearchOption(SearchOptionConst.Or, true);

            // Call Amazon Cloud Search API Service
            AmazonCloudSearcher ObjCloudSearch = new AmazonCloudSearcher();
            strResponse = ObjCloudSearch.SearchRequest(ApiEndpoint, ApiVersion,
                                                        strQuery, strOption,
                                                        "_all_fields,_score", SearchOptionConst.SortByScoreDesc,
                                                        DataFormat.Json);

            result = GetSearchDocumentList(strResponse);
            return result;
        }
コード例 #60
0
        public List <ServiceEntity> GetModelList(ServiceTypeEnum?type, string orderBy, string desc, int page,
                                                 int pageSize, string id, string keyword, string isApproved, string host, out int count)
        {
            count = 0;
            try
            {
                var queryList = new List <IMongoQuery>();
                if (type.HasValue)
                {
                    queryList.Add(Query <ServiceEntity> .EQ(t => t.ServiceType, type.Value));
                }
                if (!string.IsNullOrWhiteSpace(id))
                {
                    var arr = id.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr[0] == "1")
                    {
                        queryList.Add(Query <ServiceEntity> .EQ(t => t.ServiceName, arr[1]));
                    }
                    else if (arr[0] == "2")
                    {
                        var q = Query <ServiceEntity> .EQ(t => t.SecondaryName, arr[1]);

                        queryList.Add(arr.Length > 2
                            ? Query.And(q, Query <ServiceEntity> .EQ(t => t.ServiceName, arr[2]))
                            : q);
                    }
                }
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    queryList.Add(Query.Or(Query <ServiceEntity> .Matches(t => t.ServiceName,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase))),
                                           Query <ServiceEntity> .Matches(t => t.SecondaryName,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase))),
                                           Query <ServiceEntity> .Matches(t => t.Host,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase))),
                                           Query <ServiceEntity> .Matches(t => t.RegContent,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase))),
                                           Query <ServiceEntity> .Matches(t => t.Version,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase))),
                                           Query <ServiceEntity> .Matches(t => t.Remark,
                                                                          new BsonRegularExpression(new Regex(keyword, RegexOptions.IgnoreCase)))));
                }
                if (!string.IsNullOrWhiteSpace(isApproved))
                {
                    int approved;
                    if (int.TryParse(isApproved, out approved))
                    {
                        if (approved > 0)
                        {
                            queryList.Add(Query <ServiceEntity> .EQ(t => t.IsApproved, approved == 1));
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(host))
                {
                    queryList.Add(Query <ServiceEntity> .EQ(t => t.Host, host));
                }
                IMongoSortBy sortBy = SortBy.Ascending(orderBy);
                if (desc.Equals("desc", StringComparison.InvariantCultureIgnoreCase))
                {
                    sortBy = SortBy.Descending(orderBy);
                }
                var query = queryList.Any() ? Query.And(queryList) : null;
                count = (int)DBContext.Mongo.Count(DBContext.DbName, Col, query);
                var res = DBContext.Mongo.GetPageList <ServiceEntity>(DBContext.DbName, Col, query, page, pageSize,
                                                                      sortBy, null);
                return(res);
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }
            return(new List <ServiceEntity>());
        }