Example #1
0
        /// <summary>
        /// apply runtime sort on Main View.
        /// </summary>
        /// <param name="sortCollection"></param>
        /// <returns>bool</returns>
        public bool ApplySort(SortCollection sortCollection)
        {
            bool sortKeySet = false;

            if (sortCollection != null && sortCollection.getSize() > 0)
            {
                // Build SortKey
                SortKeyBuilder sortKeyBuilder = new SortKeyBuilder(this, sortCollection);
                DBKey          sortKey        = sortKeyBuilder.Build();

                //Set it on LocalDataviewHeader of main source
                if (sortKey != null)
                {
                    //Get the dataviewHeader of Main Source.
                    ((LocalDataviewHeader)this.DataSourceViewDefinition).SortKey = sortKey;
                    sortKeySet = true;
                }
            }
            else
            {
                ((LocalDataviewHeader)this.DataSourceViewDefinition).SortKey = null;
            }

            return(sortKeySet);
        }
Example #2
0
        public void OnGet()
        {
            Result =
                Database
                .OrderBy(Sort, out var sorting)
                .ToList();

            Sorting = sorting;
        }
Example #3
0
        /// <summary>
        /// apply runtime sort on Main View.
        /// </summary>
        /// <param name="sortCollection"></param>
        /// <returns>bool</returns>
        public bool ApplySort(SortCollection sortCollection)
        {
            bool sortKeySet = false;

            if (ViewMain != null)
            {
                sortKeySet = ViewMain.ApplySort(sortCollection);
            }
            return(sortKeySet);
        }
Example #4
0
        public void With_Existing_Flips_Property()
        {
            var value = $"{nameof(Thing.Id)}";
            var sort  = new SortCollection <Thing>(value);

            var actual = sort.AddOrUpdate("Id");

            output.WriteLine(actual);

            Assert.Equal("-Id", actual);
        }
Example #5
0
        public void With_NotExisting_Appends_Property()
        {
            var value = $"{nameof(Thing.Id)}";
            var sort  = new SortCollection <Thing>(value);

            var actual = sort.AddOrUpdate("CreatedAt");

            output.WriteLine(actual);

            Assert.Equal("Id,CreatedAt", actual);
        }
Example #6
0
        public void ToString_Returns_String()
        {
            var value = $"{nameof(Thing.Id)},{nameof(Thing.CreatedAt)}";
            var sort  = new SortCollection <Thing>(value);

            var actual = sort.ToString();

            output.WriteLine(actual);

            Assert.Equal(value, actual);
        }
Example #7
0
        public void Remove_Property()
        {
            var value = $"{nameof(Thing.Id)},{nameof(Thing.CreatedAt)}";
            var sort  = new SortCollection <Thing>(value);

            var actual = sort.Remove("CreatedAt");

            output.WriteLine(actual);

            Assert.Equal("Id", actual);
        }
Example #8
0
        public LocalDataViewCommandSort(ColumnSortEventCommand command)
            : base(command)
        {
            //Prepare Sort collection.
            Sorts = new SortCollection();
            Sort sort = new Sort();

            sort.fldIdx = command.FldId;
            sort.dir    = (command.Direction == 0) ? true : false;
            Sorts.add(sort);

            RefreshEventCommand refreshCommand = CommandFactory.CreateRealRefreshCommand(command.TaskTag, InternalInterface.MG_ACT_RT_REFRESH_VIEW, 0, null, command.ClientRecId);

            localDataViewCommandViewRefresh              = new LocalDataViewCommandViewRefresh(refreshCommand);
            localDataViewCommandViewRefresh.RefreshMode  = ViewRefreshMode.CurrentLocation;
            localDataViewCommandViewRefresh.KeepUserSort = true;
        }
Example #9
0
        private void FillSort(DataSourceBase dataSource, bool reset)
        {
            SortCollection sort = FBand.Sort;

            for (int i = 0; i < ComboArray.Length; i++)
            {
                ComboArray[i].Report     = Report;
                ComboArray[i].DataSource = dataSource;

                if (i >= sort.Count || reset)
                {
                    ComboArray[i].Text   = "";
                    AscArray[i].Checked  = true;
                    DescArray[i].Checked = false;
                }
                else
                {
                    ComboArray[i].Text   = sort[i].Expression;
                    AscArray[i].Checked  = !sort[i].Descending;
                    DescArray[i].Checked = sort[i].Descending;
                }
            }
        }
Example #10
0
        /// <summary>
        /// open cursors
        /// </summary>
        /// <param name="reverse"> direction reverse</param>
        /// <param name="startPosition"> start position</param>
        /// <returns></returns>

        internal GatewayResult OpenCursors(bool reverse, DbPos startPosition)
        {
            ///vew_crsr_open
            ///

            GatewayResult result = new GatewayResult();

            if (ViewMain != null)
            {
                SortCollection userSortCollection = GetPrimaryView().LocalDataviewManager.UserSorts;

                //user sorts may have added in task prefix. So, apply them and use the sort key.
                if (userSortCollection != null && userSortCollection.getSize() > 0)
                {
                    ApplySort(userSortCollection);
                    ViewMain.CurrentCursor.CursorDefinition.Key = ViewMain.DataSourceViewDefinition.DbKey;
                }

                result = ViewMain.OpenCursor(reverse, startPosition, BoudariesFlags.Range);
            }

            return(result);
        }
Example #11
0
        internal void Init(Relation relation, string filter, SortCollection sort, bool useAllParentRows)
        {
            if (FShowAccessDataMessage)
            {
                Config.ReportSettings.OnProgress(Report, Res.Get("Messages,AccessingData"));
            }

            // InitSchema may fail sometimes (for example, when using OracleConnection with nested select).
            try
            {
                InitSchema();
            }
            catch
            {
            }
            LoadData();

            // fill rows, emulate relation
            rows.Clear();
            if (relation != null && relation.Enabled)
            {
                if (useAllParentRows)
                {
                    DataSourceBase parentData = relation.ParentDataSource;
                    // parentData must be initialized prior to calling this method!
                    parentData.First();
                    while (parentData.HasMoreRows)
                    {
                        GetChildRows(relation);
                        parentData.Next();
                    }
                }
                else
                {
                    GetChildRows(relation);
                }
            }
            else
            {
                foreach (object row in InternalRows)
                {
                    rows.Add(row);
                }
            }

            // filter data rows
            if (FShowAccessDataMessage && rows.Count > 10000)
            {
                Config.ReportSettings.OnProgress(Report, Res.Get("Messages,PreparingData"));
            }

            if (filter != null && filter.Trim() != "")
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    CurrentRowNo = i;
                    object match = Report.Calc(filter);
                    if (match is bool && !(bool)match)
                    {
                        rows.RemoveAt(i);
                        i--;
                    }
                }
            }

            // additional filter
            if (AdditionalFilter.Count > 0)
            {
                ApplyAdditionalFilter();
            }

            // sort data rows
            if (sort != null && sort.Count > 0)
            {
                string[] expressions = new string[sort.Count];
                bool[]   descending  = new bool[sort.Count];
                for (int i = 0; i < sort.Count; i++)
                {
                    expressions[i] = sort[i].Expression;
                    descending[i]  = sort[i].Descending;
                }
                rows.Sort(new RowComparer(Report, this, expressions, descending));
            }

            FShowAccessDataMessage = false;
            First();
        }
Example #12
0
        internal void Init(DataSourceBase parentData, string filter, SortCollection sort, bool useAllParentRows)
        {
            Relation relation = parentData != null?DataHelper.FindRelation(Report.Dictionary, parentData, this) : null;

            Init(relation, filter, sort, useAllParentRows);
        }
Example #13
0
 /// <summary>
 /// Initializes this datasource and filters data rows according to the master-detail relation.
 /// Also applies the specified filter and sorts the rows.
 /// </summary>
 /// <param name="relation">The master-detail relation.</param>
 /// <param name="filter">The filter expression.</param>
 /// <param name="sort">The collection of sort descriptors.</param>
 /// <remarks>
 /// To use master-detail relation, you must define the <see cref="Relation"/> object that describes
 /// the relation, and add it to the <b>Report.Dictionary.Relations</b> collection.
 /// </remarks>
 public void Init(Relation relation, string filter, SortCollection sort)
 {
     Init(relation, filter, sort, false);
 }
Example #14
0
 /// <summary>
 /// Initializes this datasource and filters data rows according to the master-detail relation between
 /// this datasource and <b>parentData</b>. Also applies the specified filter and sorts the rows.
 /// </summary>
 /// <param name="parentData">Parent datasource.</param>
 /// <param name="filter">The filter expression.</param>
 /// <param name="sort">The collection of sort descriptors.</param>
 /// <remarks>
 /// To use master-detail relation, you must define the <see cref="Relation"/> object that describes
 /// the relation, and add it to the <b>Report.Dictionary.Relations</b> collection.
 /// </remarks>
 public void Init(DataSourceBase parentData, string filter, SortCollection sort)
 {
     Init(parentData, filter, sort, false);
 }
Example #15
0
        /// <summary>
        /// Initializes this datasource, applies the specified filter and sorts the rows.
        /// </summary>
        /// <param name="filter">The filter expression.</param>
        /// <param name="sort">The collection of sort descriptors.</param>
        public void Init(string filter, SortCollection sort)
        {
            DataSourceBase parentData = null;

            Init(parentData, filter, sort);
        }
Example #16
0
        /// <summary>
        /// Ensure a result source
        /// </summary>
        /// <param name="contextSite">The context SPSite object</param>
        /// <param name="resultSourceInfo">The result source configuration object</param>
        /// <returns>The name of the result source</returns>
        public Source EnsureResultSource(SPSite contextSite, ResultSourceInfo resultSourceInfo)
        {
            Source resultSource = null;
            var updateMode = resultSourceInfo.UpdateMode;

            var sortCollection = new SortCollection();

            if (resultSourceInfo.SortSettings != null)
            {            
                foreach (var sortSetting in resultSourceInfo.SortSettings)
                {
                    sortCollection.Add(sortSetting.Key, sortSetting.Value);
                }
            }

            var queryProperties = new QueryTransformProperties();
            queryProperties["SortList"] = sortCollection;

            // If the SortCollection contains "Rank" as one of its keys, specifiy the ranking model to be used. If a ranking model is
            // specified but sorting by Rank is not in the sort setting, throw an exception.
            if (resultSourceInfo.RankingModelId != Guid.Empty)
            {
                if ((resultSourceInfo.SortSettings != null && !resultSourceInfo.SortSettings.ContainsKey(BuiltInManagedProperties.Rank.Name)) || resultSourceInfo.SortSettings == null)
                {
                    throw new ArgumentException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "You can't specify a ranking model id ({0}) if you are not sorting by rank. Make sure to include Rank as the first Sorting Key in the sort settings if you want to use a ranking model.",
                            resultSourceInfo.RankingModelId));
                }

                queryProperties["RankingModelId"] = resultSourceInfo.RankingModelId.ToString();
            }
            else if (resultSourceInfo.SortSettings != null && resultSourceInfo.SortSettings.ContainsKey(BuiltInManagedProperties.Rank.Name))
            {
                queryProperties["RankingModelId"] = BuiltInRankingModels.DefaultSearchModelId.ToString();
            }

            // Get the search service application for the current site
            var searchServiceApplication = this.GetDefaultSearchServiceApplication(contextSite);
            if (searchServiceApplication != null)
            {
                if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteResultSource))
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication, 
                        resultSourceInfo.Name, 
                        resultSourceInfo.Level, 
                        resultSourceInfo.SearchProvider, 
                        contextSite.RootWeb, 
                        resultSourceInfo.Query,
                        queryProperties, 
                        true, 
                        resultSourceInfo.IsDefaultResultSourceForOwner);
                }
                else
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication, 
                        resultSourceInfo.Name, 
                        resultSourceInfo.Level, 
                        resultSourceInfo.SearchProvider, 
                        contextSite.RootWeb, 
                        resultSourceInfo.Query,
                        queryProperties, 
                        false, 
                        resultSourceInfo.IsDefaultResultSourceForOwner);

                    var searchQuery = string.Empty;
                    if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteQuery))
                    {
                        searchQuery = resultSourceInfo.Query;
                    }
                    else if (updateMode.Equals(ResultSourceUpdateBehavior.AppendToQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            // Check if appended query is already found on the current result source query template
                            // Note: remain case sensitive because the revert query option is also case sensitive.
                            if (!resultSource.QueryTransform.QueryTemplate.Contains(resultSourceInfo.Query))
                            {
                                searchQuery = resultSource.QueryTransform.QueryTemplate + " " + resultSourceInfo.Query;
                            }
                        }
                        else
                        {
                            searchQuery = resultSourceInfo.Query;
                        }
                    }
                    else if (updateMode.Equals(ResultSourceUpdateBehavior.RevertQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            searchQuery = resultSource.QueryTransform.QueryTemplate.Replace(resultSourceInfo.Query, string.Empty).Trim();
                        }
                    }

                    resultSource.CreateQueryTransform(queryProperties, searchQuery);
                    resultSource.Commit();
                }
            }

            return resultSource;
        }
        /// <summary>
        /// Creates an order by method call expression to be invoked on an expression e.g. (parameter, member, method call) of type IQueryable<T>.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="expression"></param>
        /// <param name="sorts"></param>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        public static MethodCallExpression GetOrderBy <TSource>(this Expression expression, SortCollection sorts)
        {
            MethodCallExpression resultExp = sorts.SortDescriptions.Aggregate(null, (MethodCallExpression mce, SortDescription description) =>
            {
                LambdaExpression selectorExpression = description.PropertyName.GetTypedSelector <TSource>();
                MemberInfo orderByPropertyInfo      = typeof(TSource).GetMemberInfoFromFullName(description.PropertyName);
                Type[] genericArgumentsForMethod    = new Type[] { typeof(TSource), orderByPropertyInfo.GetMemberType() };

                if (mce == null)
                {//OrderBy and OrderByDescending espressions take two arguments each.  The parameter (object being extended by the helper method) and the lambda expression for the property selector
                    mce = description.SortDirection == ListSortDirection.Ascending
                        ? Expression.Call(typeof(Queryable), "OrderBy", genericArgumentsForMethod, expression, selectorExpression)
                        : Expression.Call(typeof(Queryable), "OrderByDescending", genericArgumentsForMethod, expression, selectorExpression);
                }
                else
                {//ThenBy and ThenByDescending espressions take two arguments each.  The resulting method call expression from OrderBy or OrderByDescending and the lambda expression for the property selector
                    mce = description.SortDirection == ListSortDirection.Ascending
                        ? Expression.Call(typeof(Queryable), "ThenBy", genericArgumentsForMethod, mce, selectorExpression)
                        : Expression.Call(typeof(Queryable), "ThenByDescending", genericArgumentsForMethod, mce, selectorExpression);
                }
                return(mce);
            });

            resultExp = Expression.Call(typeof(Queryable), "Skip", new[] { typeof(TSource) }, resultExp, Expression.Constant(sorts.Skip));
            resultExp = Expression.Call(typeof(Queryable), "Take", new[] { typeof(TSource) }, resultExp, Expression.Constant(sorts.Take));

            return(resultExp);
        }
        /// <summary>
        /// Creates an OrderBy expression from a SortCollection
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sortCollection"></param>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        public static Expression <Func <IQueryable <T>, IQueryable <T> > > BuildOrderByExpression <T>(this SortCollection sortCollection) where T : class
        {
            if (sortCollection == null)
            {
                return(null);
            }

            ParameterExpression  param = Expression.Parameter(typeof(IQueryable <T>), "q");
            MethodCallExpression mce   = param.GetOrderBy <T>(sortCollection);

            return(Expression.Lambda <Func <IQueryable <T>, IQueryable <T> > >(mce, param));
        }
Example #19
0
        /// <summary>
        /// Ensure a result source
        /// </summary>
        /// <param name="contextSite">The context SPSite object</param>
        /// <param name="resultSourceInfo">The result source configuration object</param>
        /// <returns>The name of the result source</returns>
        public Source EnsureResultSource(SPSite contextSite, ResultSourceInfo resultSourceInfo)
        {
            Source resultSource = null;
            var    updateMode   = resultSourceInfo.UpdateMode;

            var sortCollection = new SortCollection();

            if (resultSourceInfo.SortSettings != null)
            {
                foreach (var sortSetting in resultSourceInfo.SortSettings)
                {
                    sortCollection.Add(sortSetting.Key, sortSetting.Value);
                }
            }

            var queryProperties = new QueryTransformProperties();

            queryProperties["SortList"] = sortCollection;

            // If the SortCollection contains "Rank" as one of its keys, specifiy the ranking model to be used. If a ranking model is
            // specified but sorting by Rank is not in the sort setting, throw an exception.
            if (resultSourceInfo.RankingModelId != Guid.Empty)
            {
                if ((resultSourceInfo.SortSettings != null && !resultSourceInfo.SortSettings.ContainsKey(BuiltInManagedProperties.Rank.Name)) || resultSourceInfo.SortSettings == null)
                {
                    throw new ArgumentException(
                              string.Format(
                                  CultureInfo.InvariantCulture,
                                  "You can't specify a ranking model id ({0}) if you are not sorting by rank. Make sure to include Rank as the first Sorting Key in the sort settings if you want to use a ranking model.",
                                  resultSourceInfo.RankingModelId));
                }

                queryProperties["RankingModelId"] = resultSourceInfo.RankingModelId.ToString();
            }
            else if (resultSourceInfo.SortSettings != null && resultSourceInfo.SortSettings.ContainsKey(BuiltInManagedProperties.Rank.Name))
            {
                queryProperties["RankingModelId"] = BuiltInRankingModels.DefaultSearchModelId.ToString();
            }

            // Get the search service application for the current site
            var searchServiceApplication = this.GetDefaultSearchServiceApplication(contextSite);

            if (searchServiceApplication != null)
            {
                if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteResultSource))
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        true,
                        resultSourceInfo.IsDefaultResultSourceForOwner);
                }
                else
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        false,
                        resultSourceInfo.IsDefaultResultSourceForOwner);

                    var searchQuery = string.Empty;
                    if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteQuery))
                    {
                        searchQuery = resultSourceInfo.Query;
                    }
                    else if (updateMode.Equals(ResultSourceUpdateBehavior.AppendToQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            // Check if appended query is already found on the current result source query template
                            // Note: remain case sensitive because the revert query option is also case sensitive.
                            if (!resultSource.QueryTransform.QueryTemplate.Contains(resultSourceInfo.Query))
                            {
                                searchQuery = resultSource.QueryTransform.QueryTemplate + " " + resultSourceInfo.Query;
                            }
                        }
                        else
                        {
                            searchQuery = resultSourceInfo.Query;
                        }
                    }
                    else if (updateMode.Equals(ResultSourceUpdateBehavior.RevertQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            searchQuery = resultSource.QueryTransform.QueryTemplate.Replace(resultSourceInfo.Query, string.Empty).Trim();
                        }
                    }

                    resultSource.CreateQueryTransform(queryProperties, searchQuery);
                    resultSource.Commit();
                }
            }

            return(resultSource);
        }
Example #20
0
        /// <summary>
        /// Ensure a result source
        /// </summary>
        /// <param name="contextSite">The context SPSite object</param>
        /// <param name="resultSourceInfo">The result source configuration object</param>
        /// <returns>The name of the result source</returns>
        public Source EnsureResultSource(SPSite contextSite, ResultSourceInfo resultSourceInfo)
        {
            Source resultSource = null;
            var updateMode = resultSourceInfo.UpdateMode;

            var sortCollection = new SortCollection();

            if (resultSourceInfo.SortSettings != null)
            {
                foreach (KeyValuePair<string, SortDirection> sortSetting in resultSourceInfo.SortSettings)
                {
                    sortCollection.Add(sortSetting.Key, sortSetting.Value);
                }
            }

            var queryProperties = new QueryTransformProperties();
            queryProperties["SortList"] = sortCollection;

            // Get the search service application for the current site
            var searchServiceApplication = this.GetDefaultSearchServiceApplication(contextSite);
            if (searchServiceApplication != null)
            {
                if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteResultSource))
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        true,
                        resultSourceInfo.IsDefaultResultSourceForOwner);
                }
                else
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        false,
                        resultSourceInfo.IsDefaultResultSourceForOwner);

                    string searchQuery = string.Empty;

                    if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteQuery))
                    {
                        searchQuery = resultSourceInfo.Query;
                    }

                    if (updateMode.Equals(ResultSourceUpdateBehavior.AppendToQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            var rgx = new Regex(resultSourceInfo.Query);
                            if (!rgx.IsMatch(resultSource.QueryTransform.QueryTemplate))
                            {
                                searchQuery = resultSource.QueryTransform.QueryTemplate + " " + resultSourceInfo.Query;
                            }
                        }
                        else
                        {
                            searchQuery = resultSourceInfo.Query;
                        }
                    }

                    if (updateMode.Equals(ResultSourceUpdateBehavior.RevertQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            var rgx = new Regex(resultSourceInfo.Query);
                            searchQuery = rgx.Replace(resultSource.QueryTransform.QueryTemplate, string.Empty);
                        }
                    }

                    resultSource.CreateQueryTransform(queryProperties, searchQuery);
                    resultSource.Commit();
                }
            }

            return resultSource;
        }
Example #21
0
 /// <summary>
 /// CTOR
 /// </summary>
 /// <param name="view">mainView</param>
 /// <param name="runtimeSorts">sorts collection</param>
 public SortKeyBuilder(RuntimeRealView view, SortCollection runtimeSorts)
 {
     this.mainView     = view;
     this.RuntimeSorts = runtimeSorts;
 }
Example #22
0
        public void Can_create_null()
        {
            var sort = new SortCollection <Thing>();

            Assert.NotNull(sort);
        }
 /// <summary>
 /// Creates an order by method call expression to be invoked on an expression e.g. (parameter, member, method call) of type IQueryable<T>.
 /// </summary>
 /// <typeparam name="TSource"></typeparam>
 /// <param name="expression"></param>
 /// <param name="sorts"></param>
 /// <returns></returns>
 public static MethodCallExpression GetOrderBy <TSource>(this Expression expression, SortCollection sorts)
 => expression.GetOrderBy(typeof(TSource), sorts);
Example #24
0
        /// <summary>
        /// Ensure a result source
        /// </summary>
        /// <param name="contextSite">The context SPSite object</param>
        /// <param name="resultSourceInfo">The result source configuration object</param>
        /// <returns>The name of the result source</returns>
        public Source EnsureResultSource(SPSite contextSite, ResultSourceInfo resultSourceInfo)
        {
            Source resultSource = null;
            var    updateMode   = resultSourceInfo.UpdateMode;

            var sortCollection = new SortCollection();

            if (resultSourceInfo.SortSettings != null)
            {
                foreach (KeyValuePair <string, SortDirection> sortSetting in resultSourceInfo.SortSettings)
                {
                    sortCollection.Add(sortSetting.Key, sortSetting.Value);
                }
            }

            var queryProperties = new QueryTransformProperties();

            queryProperties["SortList"] = sortCollection;

            // Get the search service application for the current site
            var searchServiceApplication = this.GetDefaultSearchServiceApplication(contextSite);

            if (searchServiceApplication != null)
            {
                if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteResultSource))
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        true,
                        resultSourceInfo.IsDefaultResultSourceForOwner);
                }
                else
                {
                    resultSource = InnerEnsureResultSource(
                        searchServiceApplication,
                        resultSourceInfo.Name,
                        resultSourceInfo.Level,
                        resultSourceInfo.SearchProvider,
                        contextSite.RootWeb,
                        resultSourceInfo.Query,
                        queryProperties,
                        false,
                        resultSourceInfo.IsDefaultResultSourceForOwner);

                    string searchQuery = string.Empty;

                    if (updateMode.Equals(ResultSourceUpdateBehavior.OverwriteQuery))
                    {
                        searchQuery = resultSourceInfo.Query;
                    }

                    if (updateMode.Equals(ResultSourceUpdateBehavior.AppendToQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            var rgx = new Regex(resultSourceInfo.Query);
                            if (!rgx.IsMatch(resultSource.QueryTransform.QueryTemplate))
                            {
                                searchQuery = resultSource.QueryTransform.QueryTemplate + " " + resultSourceInfo.Query;
                            }
                        }
                        else
                        {
                            searchQuery = resultSourceInfo.Query;
                        }
                    }

                    if (updateMode.Equals(ResultSourceUpdateBehavior.RevertQuery))
                    {
                        if (resultSource.QueryTransform != null)
                        {
                            var rgx = new Regex(resultSourceInfo.Query);
                            searchQuery = rgx.Replace(resultSource.QueryTransform.QueryTemplate, string.Empty);
                        }
                    }

                    resultSource.CreateQueryTransform(queryProperties, searchQuery);
                    resultSource.Commit();
                }
            }

            return(resultSource);
        }