Example #1
0
        public async Task <IActionResult> Index(string search, int limit = 20)
        {
            limit = Math.Abs(limit);
            var users = new List <UserEntity>();

            if (!string.IsNullOrWhiteSpace(search))
            {
                var pe = new PredicateExpression();
                pe.AddWithOr(new FieldLikePredicate(UserFields.Email, null, null, search)
                {
                    CaseSensitiveCollation = true
                });
                pe.AddWithOr(new FieldLikePredicate(UserFields.FirstName, null, null, search)
                {
                    CaseSensitiveCollation = true
                });
                pe.AddWithOr(new FieldLikePredicate(UserFields.LastName, null, null, search)
                {
                    CaseSensitiveCollation = true
                });
                pe.AddWithOr(new FieldLikePredicate(UserFields.Nickname, null, null, search)
                {
                    CaseSensitiveCollation = true
                });
                users = await _tenantContext.DbContext.AppDb.UserRepository.FindUserAsync(pe, limit + 1, CancellationToken.None);
            }
            ViewData.Add("Limit", limit);
            return(View(ViewNames.Area.Admin.Impersonation.Index, users));
        }
Example #2
0
        public AdminSitesCollection GetAdminSites(int siteUserGuid)
        {
            MCB.MasterPiece.Data.CollectionClasses.AdminSitesCollection adminSites = new AdminSitesCollection();

            IRelationCollection relations = new RelationCollection();

            relations.Add(AdminSitesEntity.Relations.AdminSiteModuleEntityUsingSiteGuid);
            relations.Add(AdminSiteModuleEntity.Relations.AdminUserAccessEntityUsingSiteModuleGuid);
            relations.Add(AdminUserAccessEntity.Relations.AdminUserEntityUsingUserGuid);

            IPredicateExpression filter = new PredicateExpression();

            filter.Add(AdminUserAccessFields.UserGuid == siteUserGuid);
            filter.AddWithAnd(AdminSitesFields.AccountingMarkAsInactive != 1);

            IPredicateExpression sensitiveDataFilter = new PredicateExpression();

            sensitiveDataFilter.Add(AdminUserFields.HasAccessToSitesWithSensitiveData == 1);
            sensitiveDataFilter.AddWithOr(AdminSitesFields.SiteContainsSensitiveData == 0);
            filter.AddWithAnd(sensitiveDataFilter);

            ISortExpression sort = new SortExpression();

            sort.Add(AdminSitesFields.CostumerFullname | SortOperator.Ascending);

            adminSites.GetMulti(filter, 0, sort, relations);

            return(adminSites);
        }
Example #3
0
        static private bool DeletePolicyFromLib(int id)
        {
            PredicateExpression pe   = new PredicateExpression(PolicyLinkFields.PolicyId == id);
            PredicateExpression peOr = new PredicateExpression(new FieldCompareSetPredicate(PolicyLinkFields.Id, PolicyDocumentFields.PolicyLinkId, SetOperator.In, null));

            peOr.AddWithOr(PolicyLinkFields.ParentId != DBNull.Value);
            pe.Add(peOr);

            PolicyLinkCollection plcoll = new PolicyLinkCollection();

            if (plcoll.GetMulti(pe) && plcoll.Count == 0)
            {
                // Policy isn't referenced in any policy document.
                PolicyEntity delPolicy = new PolicyEntity(id);
                delPolicy.PolicyLink.DeleteMulti();

                DeletePolicy(delPolicy);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #4
0
        public virtual EntityCollection <ExcludeMatchDateEntity> GetExcludedDates(DateTime queryDate, long?tournamentId,
                                                                                  long?roundId, long?teamId)
        {
            var filter = new RelationPredicateBucket();

            var scopeFilter = new PredicateExpression();

            // Condition 1: excluded on tournament level
            if (tournamentId != null)
            {
                scopeFilter.AddWithOr(ExcludeMatchDateFields.TournamentId == tournamentId);
            }

            // Condition 2: OR excluded on round level
            if (roundId != null)
            {
                scopeFilter.AddWithOr(ExcludeMatchDateFields.RoundId == roundId);
            }

            // Condition 3: OR excluded on team level
            if (teamId != null)
            {
                scopeFilter.AddWithOr(ExcludeMatchDateFields.TeamId == teamId);
            }

            filter.PredicateExpression.Add(scopeFilter);

            // Condition 4: AND date between from/to dates (including limiting dates)
            var dateFilter = new PredicateExpression();

            dateFilter.AddWithAnd(ExcludeMatchDateFields.DateFrom <= queryDate.Date);
            dateFilter.AddWithAnd(ExcludeMatchDateFields.DateTo >= queryDate.Date);
            filter.PredicateExpression.Add(dateFilter);

            var excluded = new EntityCollection <ExcludeMatchDateEntity>(new ExcludeMatchDateEntityFactory());

            using (var da = _appDb.DbContext.GetNewAdapter())
            {
                da.FetchEntityCollection(excluded, filter);
                da.CloseConnection();
            }

            //(return adapter.GetDbCount(new ExcludeMatchDateEntityFactory().CreateFields(), filter) == 0);

            return(excluded);
        }
Example #5
0
        private static IPredicate BuildPredicateTree(Func <string, IEntityField2> fieldGetter, Func <string, List <IEntityRelation>, IEntityField2> relatedFieldGetter, FilterNode filterNode, List <IEntityRelation> inferredRelationsList)
        {
            if (filterNode.NodeCount > 0)
            {
                if (filterNode.NodeType == FilterNodeType.Root && filterNode.Nodes.Count > 0)
                {
                    if (filterNode.NodeCount == 1)
                    {
                        return(BuildPredicateTree(fieldGetter, relatedFieldGetter, filterNode.Nodes[0], inferredRelationsList));
                    }

                    var predicate = new PredicateExpression();
                    foreach (var childNode in filterNode.Nodes)
                    {
                        var newPredicate = BuildPredicateTree(fieldGetter, relatedFieldGetter, childNode, inferredRelationsList);
                        if (newPredicate != null)
                        {
                            predicate.AddWithAnd(newPredicate);
                        }
                    }
                    return(predicate);
                }
                else if (filterNode.NodeType == FilterNodeType.AndExpression ||
                         filterNode.NodeType == FilterNodeType.OrExpression)
                {
                    var predicate = new PredicateExpression();
                    foreach (var childNode in filterNode.Nodes)
                    {
                        var newPredicate = BuildPredicateTree(fieldGetter, relatedFieldGetter, childNode, inferredRelationsList);
                        if (newPredicate != null)
                        {
                            if (filterNode.NodeType == FilterNodeType.OrExpression)
                            {
                                predicate.AddWithOr(newPredicate);
                            }
                            else
                            {
                                predicate.AddWithAnd(newPredicate);
                            }
                        }
                    }
                    return(predicate);
                }
            }
            else if (filterNode.ElementCount > 0)
            {
                // convert elements to IPredicate
                var nodePredicate = BuildPredicateFromClauseNode(fieldGetter, relatedFieldGetter, filterNode, inferredRelationsList);
                if (nodePredicate != null)
                {
                    return(nodePredicate);
                }
            }
            return(null);
        }
Example #6
0
        /// <summary>
        /// Creates the thread filter. Filters on the threads viewable by the passed in userid, which is the caller of the method.
        /// If a forum isn't in the list of forumsWithThreadsFromOthers, only the sticky threads and the threads started by userid should
        /// be counted / taken into account.
        /// </summary>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userID">The user ID.</param>
        /// <returns>ready to use thread filter.</returns>
        internal static IPredicateExpression CreateThreadFilter(List <int> forumsWithThreadsFromOthers, int userID)
        {
            var threadFilter = new PredicateExpression();

            if ((forumsWithThreadsFromOthers != null) && (forumsWithThreadsFromOthers.Count > 0))
            {
                PredicateExpression onlyOwnThreadsFilter = new PredicateExpression();

                // accept only those threads who aren't in the forumsWithThreadsFromOthers list and which are either started by userID or sticky.
                // the filter on the threads not in the forums listed in the forumsWithThreadsFromOthers
                if (forumsWithThreadsFromOthers.Count == 1)
                {
                    // optimization, specify the only value instead of the range, so we won't get a WHERE Field IN (@param) query which is slow on some
                    // databases, but we'll get a WHERE Field == @param
                    // accept all threads which are in a forum located in the forumsWithThreadsFromOthers list
                    threadFilter.Add((ThreadFields.ForumID == forumsWithThreadsFromOthers[0]));
                    onlyOwnThreadsFilter.Add(ThreadFields.ForumID != forumsWithThreadsFromOthers[0]);
                }
                else
                {
                    // accept all threads which are in a forum located in the forumsWithThreadsFromOthers list
                    threadFilter.Add((ThreadFields.ForumID == forumsWithThreadsFromOthers));
                    onlyOwnThreadsFilter.Add(ThreadFields.ForumID != forumsWithThreadsFromOthers);
                }
                // the filter on either sticky or threads started by the calling user
                onlyOwnThreadsFilter.AddWithAnd((ThreadFields.IsSticky == true).Or(ThreadFields.StartedByUserID == userID));
                threadFilter.AddWithOr(onlyOwnThreadsFilter);
            }
            else
            {
                // there are no forums enlisted in which the user has the right to view threads from others. So just filter on
                // sticky threads or threads started by the calling user.
                threadFilter.Add((ThreadFields.IsSticky == true).Or(ThreadFields.StartedByUserID == userID));
            }
            return(threadFilter);
        }
Example #7
0
        /// <summary>
        /// Gets the first entry from a list of dates that are excluded as match dates, or <see langword="null"/> if no date is found.
        /// Excluded dates may be related to a tournament, OR a round OR the home team OR the guest team.
        /// If the excluded table row contains a RoundId or a TeamId, it is NOT excluded for the tournament,
        /// but only for the team or round.
        /// </summary>
        /// <remarks>
        /// Same behavior as with <see cref="TournamentManager.Plan.AvailableMatchDates.IsExcludedDate"/>.
        /// </remarks>
        /// <param name="match">The <see cref="MatchEntity"/> where RoundId and TeamId are taken.</param>
        /// <param name="tournamentId">The TournamentId to filter the result.</param>
        /// <param name="cancellationToken"></param>
        /// <returns>Returns the first <see cref="ExcludeMatchDateEntity"/> which matches the criteria, else <see langword="null"/>.</returns>
        public virtual async Task <ExcludeMatchDateEntity?> GetExcludedMatchDateAsync(MatchEntity match,
                                                                                      long tournamentId, CancellationToken cancellationToken)
        {
            if (!(match.PlannedStart.HasValue && match.PlannedEnd.HasValue))
            {
                return(null);
            }

            using var da = _dbContext.GetNewAdapter();
            var tournamentFilter = new PredicateExpression(
                ExcludeMatchDateFields.TournamentId == tournamentId)
                                   .AddWithAnd(ExcludeMatchDateFields.RoundId.IsNull())
                                   .AddWithAnd(ExcludeMatchDateFields.TeamId.IsNull())
                                   // dates overlap
                                   .AddWithAnd(ExcludeMatchDateFields.DateFrom.LesserEqual(match.PlannedEnd))
                                   .AddWithAnd(ExcludeMatchDateFields.DateTo.GreaterEqual(match.PlannedStart));

            var roundFilter = new PredicateExpression(
                ExcludeMatchDateFields.TournamentId == tournamentId)
                              .AddWithAnd(ExcludeMatchDateFields.RoundId == match.RoundId)
                              // dates overlap
                              .AddWithAnd(ExcludeMatchDateFields.DateFrom.LesserEqual(match.PlannedEnd))
                              .AddWithAnd(ExcludeMatchDateFields.DateTo.GreaterEqual(match.PlannedStart));

            var teamFilter = new PredicateExpression(
                ExcludeMatchDateFields.TournamentId == tournamentId)
                             .AddWithAnd(ExcludeMatchDateFields.TeamId == match.HomeTeamId | ExcludeMatchDateFields.TeamId == match.GuestTeamId)
                             // dates overlap
                             .AddWithAnd(ExcludeMatchDateFields.DateFrom.LesserEqual(match.PlannedEnd))
                             .AddWithAnd(ExcludeMatchDateFields.DateTo.GreaterEqual(match.PlannedStart));

            return((await da.FetchQueryAsync(
                        new QueryFactory().ExcludeMatchDate.Where(tournamentFilter
                                                                  .AddWithOr(roundFilter).AddWithOr(teamFilter)).Limit(1),
                        cancellationToken)).Cast <ExcludeMatchDateEntity>().FirstOrDefault());
        }
        /// <summary>
        /// Za svaki član this.rules kolekcije kreira jedan Predicate.
        /// Ako je rules.Count == 0 vraća NULL
        /// </summary>
        /// <returns>PredicateExpression</returns>
        /// <param name="entityFieldsType">Ako se filtrira artikl onda typeof(ArtiklFields)</param>
		/// <param name="getEntityFieldTypeFunction">Funkcija prima string (EntityFields type name) a vraća tip. Ako se desi da se filtrira po entitetu vezanom na glavni entitet (RacunGlava.Partner) tada se koristi ova funkcija za dohvat EntityFieldsType preko refleksije.</param>
		public PredicateExpression KreirajPredicate(Type entityFieldsType, 
                                            Func<string, Type> getEntityFieldTypeFunction)
        {
            PredicateExpression toReturn = null;

            if (rules.Count() > 0)
            {
                toReturn = new PredicateExpression();

                foreach (JqGridFilterItem item in rules)
                {
                    Predicate predicateToAdd = JqGridFilter.KreirajPredikatIzJqGridFilterItem(entityFieldsType, item, getEntityFieldTypeFunction);
                    
                    if (predicateToAdd != null)
                    {
                        if (groupOp.ToUpper() == "AND")
                        {
                            toReturn.AddWithAnd(predicateToAdd);
                        }
                        else if (groupOp.ToUpper() == "OR")
                        {
                            toReturn.AddWithOr(predicateToAdd);
                        }
                    }
                }
            }

            return toReturn;
        }
Example #9
0
        /// <summary>
        /// Does the search using MS Full text search
        /// </summary>
        /// <param name="searchString">Search string.</param>
        /// <param name="forumIDs">Forum Ids of forums to search into.</param>
        /// <param name="orderFirstElement">Order first element setting.</param>
        /// <param name="orderSecondElement">Order second element setting.</param>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userID">The userid of the calling user.</param>
        /// <param name="targetToSearch">The target to search.</param>
        /// <returns>
        /// TypedList filled with threads matching the query.
        /// </returns>
        public static SearchResultTypedList DoSearch(string searchString, List <int> forumIDs, SearchResultsOrderSetting orderFirstElement,
                                                     SearchResultsOrderSetting orderSecondElement, List <int> forumsWithThreadsFromOthers, int userID, SearchTarget targetToSearch)
        {
            // the search utilizes full text search. It performs a CONTAINS upon the MessageText field of the Message entity.
            string searchTerms       = PrepareSearchTerms(searchString);
            bool   searchMessageText = (targetToSearch == SearchTarget.MessageText) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            bool   searchSubject     = (targetToSearch == SearchTarget.ThreadSubject) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);

            if (!(searchSubject || searchMessageText))
            {
                // no target specified, select message
                searchMessageText = true;
            }

            PredicateExpression searchTermFilter = new PredicateExpression();

            if (searchMessageText)
            {
                // Message contents filter
                searchTermFilter.Add(new FieldCompareSetPredicate(ThreadFields.ThreadID, MessageFields.ThreadID,
                                                                  SetOperator.In, new FieldFullTextSearchPredicate(MessageFields.MessageText, FullTextSearchOperator.Contains, searchTerms)));
            }
            if (searchSubject)
            {
                // Thread subject filter
                if (searchMessageText)
                {
                    searchTermFilter.AddWithOr(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
                else
                {
                    searchTermFilter.Add(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
            }
            IPredicateExpression mainFilter = searchTermFilter
                                              .And(ForumFields.ForumID == forumIDs)
                                              .And(ThreadGuiHelper.CreateThreadFilter(forumsWithThreadsFromOthers, userID));

            ISortExpression sorter = new SortExpression();

            // add first element
            sorter.Add(CreateSearchSortClause(orderFirstElement));
            if (orderSecondElement != orderFirstElement)
            {
                sorter.Add(CreateSearchSortClause(orderSecondElement));
            }

            SearchResultTypedList results = new SearchResultTypedList(false);

            try
            {
                // get the data from the db.
                results.Fill(500, sorter, false, mainFilter);
            }
            catch
            {
                // probably an error with the search words / user error. Swallow for now, which will result in an empty resultset.
            }

            return(results);
        }
        private static IPredicate BuildPredicateTree(Func<string, IEntityField2> fieldGetter, Func<string, List<IEntityRelation>, IEntityField2> relatedFieldGetter, FilterNode filterNode, List<IEntityRelation> inferredRelationsList)
        {
            if (filterNode.NodeCount > 0)
            {
                if (filterNode.NodeType == FilterNodeType.Root && filterNode.Nodes.Count > 0)
                {
                    if (filterNode.NodeCount == 1)
                        return BuildPredicateTree(fieldGetter, relatedFieldGetter, filterNode.Nodes[0], inferredRelationsList);

                    var predicate = new PredicateExpression();
                    foreach (var childNode in filterNode.Nodes)
                    {
                        var newPredicate = BuildPredicateTree(fieldGetter, relatedFieldGetter, childNode, inferredRelationsList);
                        if (newPredicate != null)
                            predicate.AddWithAnd(newPredicate);
                    }
                    return predicate;
                }
                else if (filterNode.NodeType == FilterNodeType.AndExpression ||
                    filterNode.NodeType == FilterNodeType.OrExpression)
                {
                    var predicate = new PredicateExpression();
                    foreach (var childNode in filterNode.Nodes)
                    {
                        var newPredicate = BuildPredicateTree(fieldGetter, relatedFieldGetter, childNode, inferredRelationsList);
                        if (newPredicate != null)
                        {
                            if (filterNode.NodeType == FilterNodeType.OrExpression)
                                predicate.AddWithOr(newPredicate);
                            else
                                predicate.AddWithAnd(newPredicate);
                        }
                    }
                    return predicate;
                }
            }
            else if (filterNode.ElementCount > 0)
            {
                // convert elements to IPredicate
                var nodePredicate = BuildPredicateFromClauseNode(fieldGetter, relatedFieldGetter, filterNode, inferredRelationsList);
                if (nodePredicate != null)
                    return nodePredicate;
            }
            return null;
        }
Example #11
0
		/// <summary>
		/// Creates the thread filter. Filters on the threads viewable by the passed in userid, which is the caller of the method. 
		/// If a forum isn't in the list of forumsWithThreadsFromOthers, only the sticky threads and the threads started by userid should 
		/// be counted / taken into account. 
		/// </summary>
		/// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
		/// <param name="userID">The user ID.</param>
		/// <returns>ready to use thread filter.</returns>
		internal static IPredicateExpression CreateThreadFilter(List<int> forumsWithThreadsFromOthers, int userID)
		{
			var threadFilter = new PredicateExpression();
			if((forumsWithThreadsFromOthers != null) && (forumsWithThreadsFromOthers.Count > 0))
			{
				PredicateExpression onlyOwnThreadsFilter = new PredicateExpression();

				// accept only those threads who aren't in the forumsWithThreadsFromOthers list and which are either started by userID or sticky.
				// the filter on the threads not in the forums listed in the forumsWithThreadsFromOthers
				if(forumsWithThreadsFromOthers.Count == 1)
				{
					// optimization, specify the only value instead of the range, so we won't get a WHERE Field IN (@param) query which is slow on some
					// databases, but we'll get a WHERE Field == @param
					// accept all threads which are in a forum located in the forumsWithThreadsFromOthers list 
					threadFilter.Add((ThreadFields.ForumID == forumsWithThreadsFromOthers[0]));
					onlyOwnThreadsFilter.Add(ThreadFields.ForumID != forumsWithThreadsFromOthers[0]);
				}
				else
				{
					// accept all threads which are in a forum located in the forumsWithThreadsFromOthers list 
					threadFilter.Add((ThreadFields.ForumID == forumsWithThreadsFromOthers));
					onlyOwnThreadsFilter.Add(ThreadFields.ForumID != forumsWithThreadsFromOthers);
				}
				// the filter on either sticky or threads started by the calling user
				onlyOwnThreadsFilter.AddWithAnd((ThreadFields.IsSticky == true).Or(ThreadFields.StartedByUserID == userID));
				threadFilter.AddWithOr(onlyOwnThreadsFilter);
			}
			else
			{
				// there are no forums enlisted in which the user has the right to view threads from others. So just filter on
				// sticky threads or threads started by the calling user.
				threadFilter.Add((ThreadFields.IsSticky == true).Or(ThreadFields.StartedByUserID == userID));
			}
			return threadFilter;
		}
Example #12
0
        /// <summary>
        /// Does the search using MS Full text search
        /// </summary>
        /// <param name="searchString">Search string.</param>
        /// <param name="forumIds">Forum Ids of forums to search into.</param>
        /// <param name="orderFirstElement">Order first element setting.</param>
        /// <param name="orderSecondElement">Order second element setting.</param>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userId">The userid of the calling user.</param>
        /// <param name="targetToSearch">The target to search.</param>
        /// <returns>
        /// TypedList filled with threads matching the query.
        /// </returns>
        public static async Task <List <SearchResultRow> > DoSearchAsync(string searchString, List <int> forumIds, SearchResultsOrderSetting orderFirstElement,
                                                                         SearchResultsOrderSetting orderSecondElement, List <int> forumsWithThreadsFromOthers, int userId,
                                                                         SearchTarget targetToSearch)
        {
            // the search utilizes full text search. It performs a CONTAINS upon the MessageText field of the Message entity.
            var searchTerms       = PrepareSearchTerms(searchString);
            var searchMessageText = (targetToSearch == SearchTarget.MessageText) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            var searchSubject     = (targetToSearch == SearchTarget.ThreadSubject) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);

            if (!(searchSubject || searchMessageText))
            {
                // no target specified, select message
                searchMessageText = true;
            }

            var qf = new QueryFactory();
            var searchTermFilter = new PredicateExpression();

            if (searchMessageText)
            {
                // Message contents filter
                searchTermFilter.Add(ThreadFields.ThreadID.In(qf.Create()
                                                              .Select(MessageFields.ThreadID)
                                                              .Where(new FieldFullTextSearchPredicate(MessageFields.MessageText, null, FullTextSearchOperator.Contains,
                                                                                                      searchTerms))));
            }

            if (searchSubject)
            {
                // Thread subject filter
                if (searchMessageText)
                {
                    searchTermFilter.AddWithOr(new FieldFullTextSearchPredicate(ThreadFields.Subject, null, FullTextSearchOperator.Contains, searchTerms));
                }
                else
                {
                    searchTermFilter.Add(new FieldFullTextSearchPredicate(ThreadFields.Subject, null, FullTextSearchOperator.Contains, searchTerms));
                }
            }

            var q = qf.GetSearchResultTypedList()
                    .Where(searchTermFilter
                           .And(ForumFields.ForumID.In(forumIds))
                           .And(ThreadGuiHelper.CreateThreadFilter(forumsWithThreadsFromOthers, userId)))
                    .Limit(500)
                    .OrderBy(CreateSearchSortClause(orderFirstElement))
                    .Distinct();

            if (orderSecondElement != orderFirstElement)
            {
                // simply call OrderBy again, it will append the sortclause to the existing one.
                q.OrderBy(CreateSearchSortClause(orderSecondElement));
            }

            List <SearchResultRow> toReturn;

            try
            {
                // get the data from the db.
                using (var adapter = new DataAccessAdapter())
                {
                    toReturn = await adapter.FetchQueryAsync(q).ConfigureAwait(false);
                }
            }
            catch
            {
                // probably an error with the search words / user error. Swallow for now, which will result in an empty resultset.
                toReturn = new List <SearchResultRow>();
            }

            return(toReturn);
        }
Example #13
0
        /// <summary>
        /// Does the search using MS Full text search
        /// </summary>
        /// <param name="searchString">Search string.</param>
        /// <param name="forumIDs">Forum Ids of forums to search into.</param>
        /// <param name="orderFirstElement">Order first element setting.</param>
        /// <param name="orderSecondElement">Order second element setting.</param>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userID">The userid of the calling user.</param>
        /// <param name="targetToSearch">The target to search.</param>
        /// <returns>
        /// TypedList filled with threads matching the query.
        /// </returns>
        public static SearchResultTypedList DoSearch(string searchString, List<int> forumIDs, SearchResultsOrderSetting orderFirstElement,
            SearchResultsOrderSetting orderSecondElement, List<int> forumsWithThreadsFromOthers, int userID, SearchTarget targetToSearch)
        {
            // the search utilizes full text search. It performs a CONTAINS upon the MessageText field of the Message entity.
            string searchTerms = PrepareSearchTerms(searchString);
            bool searchMessageText = (targetToSearch == SearchTarget.MessageText) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            bool searchSubject = (targetToSearch == SearchTarget.ThreadSubject) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            if(!(searchSubject || searchMessageText))
            {
                // no target specified, select message
                searchMessageText = true;
            }

            PredicateExpression searchTermFilter = new PredicateExpression();
            if(searchMessageText)
            {
                // Message contents filter
                searchTermFilter.Add(new FieldCompareSetPredicate(ThreadFields.ThreadID, MessageFields.ThreadID,
                                    SetOperator.In, new FieldFullTextSearchPredicate(MessageFields.MessageText, FullTextSearchOperator.Contains, searchTerms)));
            }
            if(searchSubject)
            {
                // Thread subject filter
                if(searchMessageText)
                {
                    searchTermFilter.AddWithOr(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
                else
                {
                    searchTermFilter.Add(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
            }
            IPredicateExpression mainFilter = searchTermFilter
                                                    .And(ForumFields.ForumID == forumIDs)
                                                    .And(ThreadGuiHelper.CreateThreadFilter(forumsWithThreadsFromOthers, userID));

            ISortExpression sorter = new SortExpression();
            // add first element
            sorter.Add(CreateSearchSortClause(orderFirstElement));
            if(orderSecondElement != orderFirstElement)
            {
                sorter.Add(CreateSearchSortClause(orderSecondElement));
            }

            SearchResultTypedList results = new SearchResultTypedList(false);

            try
            {
                // get the data from the db.
                results.Fill(500, sorter, false, mainFilter);
            }
            catch
            {
                // probably an error with the search words / user error. Swallow for now, which will result in an empty resultset.
            }

            return results;
        }
        private static bool DeletePolicyFromLib(int id)
        {
            PredicateExpression pe = new PredicateExpression(PolicyLinkFields.PolicyId == id);
            PredicateExpression peOr = new PredicateExpression(new FieldCompareSetPredicate(PolicyLinkFields.Id, PolicyDocumentFields.PolicyLinkId, SetOperator.In, null));
            peOr.AddWithOr(PolicyLinkFields.ParentId != DBNull.Value);
            pe.Add(peOr);

            PolicyLinkCollection plcoll = new PolicyLinkCollection();
            if (plcoll.GetMulti(pe) && plcoll.Count == 0)
            {
                // Policy isn't referenced in any policy document.
                PolicyEntity delPolicy = new PolicyEntity(id);
                delPolicy.PolicyLink.DeleteMulti();

                DeletePolicy(delPolicy);

                return true;
            }
            else
                return false;
        }