private MultiFacetRequest BuildRequest(int maxResults)
        {
            var request = new MultiFacetRequest
            {
                Query      = Query,
                Sort       = SortFields.ToList(),
                MaxResults = maxResults,
                Config     = FacetSearcherConfiguration.Default(),
                Facets     = new List <FacetFieldInfo>()
            };

            foreach (var field in Fields)
            {
                if (field.MinHits > 0)
                {
                    request.Config.MinimumCountInTotalDatasetForFacet = field.MinHits;
                }

                var fieldInfo = new FacetFieldInfo
                {
                    FieldName = field.Name,
                    MaxToFetchExcludingSelections = field.MaxCount
                };

                if (field.Values != null)
                {
                    fieldInfo.Selections = field.Values.ToList();
                }

                request.Facets.Add(fieldInfo);
            }

            return(request);
        }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Makes the specified field the first, or primary, field on which to sort.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public bool SetPrimarySortField(PaField field, bool changeDirection, bool ascending)
        {
            if (field == null)
            {
                return(ascending);
            }

            var sortInfo = SortFields.SingleOrDefault(si => si.Field.Name == field.Name);
            int index    = (sortInfo == null ? -1 : SortFields.IndexOf(sortInfo));

            // If the sort information list already contains an item for the specified field,
            // we need to remove it before reinserting it at the beginning of the list.
            if (index > -1)
            {
                if (changeDirection)
                {
                    ascending = SortFields[index].Ascending;
                }
                SortFields.RemoveAt(index);
            }

            if (changeDirection)
            {
                ascending = !ascending;
            }

            // Now insert an item at the beginning of the list since the specified field
            // has now become the first (i.e. primary) field on which to sort.
            SortFields.Insert(0, new SortField(field, ascending));

            return(ascending);
        }
Esempio n. 3
0
 protected void SortByField()
 {
     if (SortFields != null && SortFields.Any())
     {
         Operations = OrderByFields(SortFields);
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Add a field into the sorting of result
        /// </summary>
        /// <returns>FindRequest with new sorting option</returns>
        /// <param name="field">The sort field</param>
        /// <param name="ascending">True if direction of sort is Asceding use false for Descending(Default is True)</param>
        public FindRequest <T> Sort(Expression <Func <T, object> > field, bool ascending = true)
        {
            var fieldName = Metadata.GetMemberInfo(field).Member.Name;

            SortFields.Add(new Sorting(fieldName, ascending));
            return(this);
        }
Esempio n. 5
0
        public override ISearchResults Execute(int maxResults = 500)
        {
            _request.BrowseRequest.Count = maxResults;
            _request.BrowseRequest.Sort  = SortFields.ToArray();

            return(new BoboFacetSearchResults(_searchContext, _request));
        }
Esempio n. 6
0
 public void AddSortField(SortField sortField)
 {
     if (string.IsNullOrWhiteSpace(sortField.Label))
     {
         sortField.Label = TextService.Title(sortField.Name);
     }
     SortFields.Add(sortField);
 }
Esempio n. 7
0
 private string GetUniqueCode()
 {
     //Return code specific for this list for assembly cache
     return(string.Format("f[{0}]s[{1}]",
                          ShouldFilter() ? FilterBy : string.Empty,
                          ShouldSort() ? string.Join(",", SortFields.ToArray()) : string.Empty
                          ).ToLowerInvariant());
 }
Esempio n. 8
0
        internal static async Task <VehicleOverviews> MapToVehicleOverviews(
            VehicleOverviewsRequest request,
            IQueryable <VehicleEntity> vehicles,
            IQueryable <MakerEntity> makers,
            IQueryable <ModelEntity> models,
            IQueryable <OwnerEntity> owners)
        {
            // Build SQL query
            var query1 = from v in vehicles.GetByMakers(request.Makers)
                         .GetByModels(request.Models)
                         .GetByFeatures(request.Features)
                         .GetByContactName(request.ContactName)
                         join m in models on v.ModelId equals m.Id
                         join mk in makers on m.MakerId equals mk.Id
                         join o in owners on v.OwnerId equals o.Id
                         select new
            {
                VehicleId = v.Id,
                Maker     = mk,
                Model     = m,
                Owner     = o
            };

            var query = from q1 in query1
                        select new VehicleOverviewQuery
            {
                VehicleId    = q1.VehicleId,
                Maker        = q1.Maker,
                Model        = q1.Model,
                Owner        = q1.Owner,
                RecordsCount = query1.Count()
            };

            var sortBy = new SortFields <VehicleOverviewQuery>
            {
                { "maker", e => e.Maker.Name },
                { "model", e => e.Model.Name },
                { "contact", e => e.Owner.LastName, e => e.Owner.FirstName }
            };

            query = query
                    .SortBy(request, sortBy)
                    .GetPage(request);

            // Run SQL query
            var entities = await query.ToArrayAsync();

            // Map entities to models
            var overviews = entities.Select(e => new VehicleOverview(e.VehicleId,
                                                                     e.Maker.Name,
                                                                     e.Model.Name,
                                                                     $"{e.Owner.FirstName} {e.Owner.LastName}"));

            return(new VehicleOverviews(
                       request,
                       entities.Any() ? entities.First().RecordsCount : 0,
                       overviews));
        }
Esempio n. 9
0
        public string Build(SortFields sortFields = SortFields.ByInsertionOrder)
        {
            var sb = new StringBuilder();

            Sort(sortFields);
            ExportHeader(sb);
            ExportRows(sb);
            return(sb.ToString());
        }
Esempio n. 10
0
 private static void ProcessSortFields(SortFields sfs, XmlWriter xmlw)
 {
     xmlw.WriteStartElement("SortFields");
     xmlw.WriteAttributeString("Count", sfs.Count.ToStringSafe());
     foreach (SortField sf in sfs)
     {
         ProcessSortField(sf, xmlw);
     }
     xmlw.WriteEndElement();
 }
Esempio n. 11
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Returns a deep copy of the sort options.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public SortOptions Copy()
        {
            var copy = new SortOptions(false, _project);

            copy.SortType = SortType;
            copy.SaveManuallySetSortOptions = SaveManuallySetSortOptions;
            copy.AdvancedEnabled            = AdvancedEnabled;
            Array.Copy(AdvSortOrder, copy.AdvSortOrder, AdvSortOrder.Length);
            Array.Copy(AdvRlOptions, copy.AdvRlOptions, AdvRlOptions.Length);
            copy.SortFields = SortFields.Select(sf => sf.Copy()).ToList();

            return(copy);
        }
Esempio n. 12
0
        public SearchDescriptor <T> GetSearchDescriptor()
        {
            var res = new SearchDescriptor <T>()
                      .Index(Indices)
                      .Skip(Skip ?? 0)
                      .Take(Take ?? 10)
                      .Aggregations(a => BucketFields.GetBucketAggreagationDescriptor <T>())
                      .Sort(x => SortFields.GetSortDescriptor <T>())
                      .Query(x => x.QueryString(q => q.Query(Text)));


            return(res);
        }
Esempio n. 13
0
        public SearchDescriptor <T> GetSearchDescriptor()
        {
            var s = new SearchDescriptor <T>()
                    .Index(Indices)
                    .Skip(Skip ?? 0)
                    .Take(Take ?? 10)
                    .Aggregations(a => BucketFields.GetBucketAggreagationDescriptor <T>())
                    .Query(q => FilterFields.GetQueryDesctiptor <T>())
                    .Source(t => ReturnFields.GetSourceFilterDescriptor <T>())
                    .Sort(s => SortFields.GetSortDescriptor <T>());

            return(s);
        }
Esempio n. 14
0
        private void Sort(SortFields sortFields)
        {
            switch (sortFields)
            {
            case SortFields.ByName:
                _fields.Sort();
                break;

            case SortFields.ByNameLeaveFirst:
                var first = _fields[0];
                _fields.RemoveAt(0);
                _fields.Sort();
                _fields.Insert(0, first);
                break;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// OrderBy extension
        /// </summary>
        /// <typeparam name="T">Entity type</typeparam>
        /// <param name="source">Source collection</param>
        /// <param name="sortField">Sorting field by</param>
        /// <param name="orderRule">Order rule</param>
        /// <returns>Sorted iqueryable</returns>
        public static IQueryable <T> OrderBy <T>(this IQueryable <T> source, SortFields sortField, OrderRule orderRule)
        {
            var type           = typeof(T);
            var property       = type.GetProperty(sortField.ToString());
            var parameter      = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp     = Expression.Lambda(propertyAccess, parameter);
            var resultExp      = Expression.Call(
                typeof(Queryable),
                orderRule == OrderRule.Asc ? "OrderBy" : "OrderByDescending",
                new[] { type, property.PropertyType },
                source.Expression,
                Expression.Quote(orderByExp));

            return(source.Provider.CreateQuery <T>(resultExp));
        }
Esempio n. 16
0
        public static GetLoanRequest MapSsnToGetRequest(string ssn, int maxEntities)
        {
            _log.Debug("START MapSsnToGetRequest");
            GetLoanRequest request = new GetLoanRequest();

            CriteriaLoan_Ssn c = new CriteriaLoan_Ssn();

            c.MaxEntities = maxEntities;

            c.CriterionSSN                    = new ASA.Web.Services.LoanService.Proxy.LoanManagement.CriterionSSNType();
            c.CriterionSSN.SSN                = ssn;
            c.CriterionSSN.LogicalOperator    = ASA.Web.Services.LoanService.Proxy.LoanManagement.LogicalOperatorType.AND;
            c.CriterionSSN.RelationalOperator = ASA.Web.Services.LoanService.Proxy.LoanManagement.RelationalOperatorType.EQUALS;

            c.CriterionRoleId                    = new ASA.Web.Services.LoanService.Proxy.LoanManagement.CriterionRoleIdType();
            c.CriterionRoleId.RoleId             = "BORR";
            c.CriterionRoleId.LogicalOperator    = ASA.Web.Services.LoanService.Proxy.LoanManagement.LogicalOperatorType.AND;
            c.CriterionRoleId.RelationalOperator = ASA.Web.Services.LoanService.Proxy.LoanManagement.RelationalOperatorType.EQUALS;

            c.CriterionIsArchived                    = new ASA.Web.Services.LoanService.Proxy.LoanManagement.CriterionIsArchivedType();
            c.CriterionIsArchived.IsArchived         = ASA.Web.Services.LoanService.Proxy.LoanManagement.YNFlagType.N;
            c.CriterionIsArchived.LogicalOperator    = ASA.Web.Services.LoanService.Proxy.LoanManagement.LogicalOperatorType.AND;
            c.CriterionIsArchived.RelationalOperator = ASA.Web.Services.LoanService.Proxy.LoanManagement.RelationalOperatorType.EQUALS;

            c.CriterionInputSourceId = new ASA.Web.Services.LoanService.Proxy.LoanManagement.CriterionInputSourceIDType();
            c.CriterionInputSourceId.InputSourceId      = "DER";
            c.CriterionInputSourceId.LogicalOperator    = ASA.Web.Services.LoanService.Proxy.LoanManagement.LogicalOperatorType.AND;
            c.CriterionInputSourceId.RelationalOperator = ASA.Web.Services.LoanService.Proxy.LoanManagement.RelationalOperatorType.CONTAINS;

            c.ListReturnTypes = new ASA.Web.Services.LoanService.Proxy.LoanManagement.ReturnListType();
            c.ListReturnTypes.LoanTier2Type = ASA.Web.Services.LoanService.Proxy.LoanManagement.YNFlagType.Y;
            c.ListReturnTypes.LoanTier2OrganizationArray = ASA.Web.Services.LoanService.Proxy.LoanManagement.YNFlagType.Y;
            c.ListReturnTypes.LoanTier2PersonArray       = ASA.Web.Services.LoanService.Proxy.LoanManagement.YNFlagType.Y;

            //set sort values.  This will help (but not gaurantee) that the newer IsArchived=N, InputSourceId %DER%
            // are more likely to be in the list of loans returned.
            SortFields sortFields = new SortFields();

            sortFields.IsArchived    = SortOperatorType.DESC;
            sortFields.InputSourceId = SortOperatorType.ASC;
            c.SortFields             = sortFields;

            request.Criteria = c as LoanServiceCriteriaType;
            _log.Debug("END MapSsnToGetRequest");
            return(request);
        }
Esempio n. 17
0
        public void Sort(SortFields sortField, bool isAscending)
        {
            switch (sortField)
            {
            case SortFields.Name:
                base.Sort(new NameComparer());
                break;

            case SortFields.TTL:
                base.Sort(new TTLComparer());
                break;
            }

            if (!isAscending)
            {
                base.Reverse();
            }
        }
Esempio n. 18
0
        ///// ------------------------------------------------------------------------------------
        ///// <summary>
        ///// Compares the contents of this SortOptions object with the one specified.
        ///// TODO: Write some tests for this method. It could be used to fix PA-830.
        ///// </summary>
        ///// ------------------------------------------------------------------------------------
        //public bool AreEqual(SortOptions otherOptions)
        //{
        //    if (otherOptions == null)
        //        return false;

        //    if (m_sortType != otherOptions.m_sortType ||
        //        m_advancedEnabled != otherOptions.m_advancedEnabled ||
        //        m_saveManuallySetSortOptions != otherOptions.m_saveManuallySetSortOptions)
        //    {
        //        return false;
        //    }

        //    for (int i = 0; i < m_advSortOptions.Length; i++)
        //    {
        //        if (m_advSortOptions[i] != otherOptions.m_advSortOptions[i])
        //            return false;
        //    }

        //    for (int i = 0; i < m_advRlOptions.Length; i++)
        //    {
        //        if (m_advRlOptions[i] != otherOptions.m_advRlOptions[i])
        //            return false;
        //    }

        //    if (m_sortInfoList == null && otherOptions.m_sortInfoList != null ||
        //        m_sortInfoList != null && otherOptions.m_sortInfoList == null ||
        //        m_sortInfoList.Count != otherOptions.m_sortInfoList.Count)
        //    {
        //        return false;
        //    }

        //    for (int i = 0; i < m_sortInfoList.Count; i++)
        //    {
        //        if (m_sortInfoList[i].ascending != otherOptions.m_sortInfoList[i].ascending ||
        //            m_sortInfoList[i].FieldInfo.FieldName !=
        //            otherOptions.m_sortInfoList[i].FieldInfo.FieldName)
        //        {
        //            return false;
        //        }
        //    }

        //    return true;
        //}

        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Deserializing a project brings in only the field names for the sort options's
        /// SortFields property. We actually want each SortFields entry to contain a pointer
        /// to a project's field. This will make sure each one points to a real PaField.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void PostDeserializeInitialization(PaProject project)
        {
            _project = project;

            foreach (var sf in SortFields)
            {
                sf.Field       = project.Fields.SingleOrDefault(f => f.Name == sf.PaFieldName);
                sf.PaFieldName = null;
            }

            // Toss out any fields that couldn't be mapped, although that should probably never happen.
            SortFields = SortFields.Where(sf => sf.Field != null).ToList();

            // We have to have at least one sort field.
            if (SortFields.Count == 0)
            {
                SetPrimarySortField(project.Fields.SingleOrDefault(f =>
                                                                   f.Type == FieldType.Phonetic), false, true);
            }
        }
Esempio n. 19
0
        SortEdgeTable
        (
            ListObject oEdgeTable,
            Range oRangeToSortOn
        )
        {
            Debug.Assert(oEdgeTable != null);
            Debug.Assert(oRangeToSortOn != null);
            AssertValid();

            Sort       oSort       = oEdgeTable.Sort;
            SortFields oSortFields = oSort.SortFields;

            oSortFields.Clear();

            oSortFields.Add(oRangeToSortOn, XlSortOn.xlSortOnValues,
                            XlSortOrder.xlAscending, Missing.Value,
                            XlSortDataOption.xlSortNormal);

            oSort.Apply();
            oSortFields.Clear();
        }
Esempio n. 20
0
        /// <summary>
        /// Add sort field. Use + prefix for asc sorting, or use - prefix for desc sorting.
        /// </summary>
        public IndexQuery AddOrderBy(string field)
        {
            var reverse = false;

            if (field[0] == '+' || field[0] == '-')
            {
                reverse = field[0] == '-';
                field   = field.Substring(1);
            }

            var sortType = Lucene.Net.Search.SortField.STRING;

            var property = ModelType.GetProperty(field, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            if (property != null)
            {
                sortType = LuceneUtility.GetSortType(property.PropertyType);
            }

            SortFields.Add(new SortField(field, sortType, reverse));

            return(this);
        }
Esempio n. 21
0
        private BoboFacetRequest BuildRequest(int maxResults)
        {
            var request = new BoboFacetRequest
            {
                BrowseRequest = new BrowseRequest
                {
                    Query             = Query,
                    Sort              = SortFields.ToArray(),
                    Count             = maxResults,
                    FetchStoredFields = true
                },
                FacetHandlers = new List <IFacetHandler>()
            };

            foreach (var field in Fields)
            {
                var spec = new FacetSpec()
                {
                    MinHitCount = field.MinHits,
                    MaxCount    = field.MaxCount
                };

                request.BrowseRequest.SetFacetSpec(field.Name, spec);

                if (field.Values != null)
                {
                    request.BrowseRequest.AddSelection(new BrowseSelection(field.Name)
                    {
                        Values = field.Values
                    });
                }

                request.FacetHandlers.Add(new MultiValueFacetHandler(field.Name));
            }

            return(request);
        }
Esempio n. 22
0
 private bool ShouldSort()
 {
     return(SortFields != null && SortFields.Any());
 }
Esempio n. 23
0
 /// <summary>
 /// Sorts the contents based on the sort field specified
 /// </summary>
 /// <param name="bAscending">ascending or descending</param>
 /// <param name="sortField">one of the sort fields above</param>
 /// <returns>true on success</returns>
 public bool SortContents(bool bAscending, SortFields sortField)
 {
     return(MAPISortContents(pMAPI, bAscending, (int)sortField));
 }
Esempio n. 24
0
        public async Task <ActionResult <HdTicketsOutputDto> > GetHdTickets(
            [FromQuery] string assignee,
            string software,
            string referredTo,
            string department,
            string location,
            string excludedStatuses,
            string sort,
            int page    = 1,
            int perPage = 20)
        {
            IQueryable <HdTicketsDto> query = _context.HdTicket
                                              .Where(t => t.HdQueueId == 1)
                                              .Select(t => new HdTicketsDto
            {
                Ticket     = t.Id,
                Title      = t.Title,
                Priority   = t.Priority.Name,
                Owner      = t.Owner.FullName,
                Submitter  = t.Submitter.FullName,
                Asset      = t.Asset.Name,
                Status     = t.Status.Name,
                ReferredTo = t.CustomFieldValue5,
                UserName   = t.Owner.UserName,
                Dept       = t.CustomFieldValue1,
                Location   = t.CustomFieldValue2,
                PriOrd     = t.Priority.Ordinal,
                StatOrd    = t.Status.Ordinal,
                Created    = t.Created
            });

            if (excludedStatuses != null)
            {
                string[] excludedList = excludedStatuses.Split(',');

                query = excludedList
                        .Aggregate(query, (current, status) => current.Where(t => t.Status != status));
            }

            if (assignee != null)
            {
                query = query.Where(t => t.UserName == assignee);
            }
            if (software != null)
            {
                query = query.Where(t => t.Asset == software);
            }
            if (referredTo != null)
            {
                query = query.Where(t => t.ReferredTo == referredTo);
            }
            if (department != null)
            {
                query = query.Where(t => t.Dept == department);
            }
            if (location != null)
            {
                query = query.Where(t => t.Location == location);
            }

            IOrderedQueryable <HdTicketsDto> orderedQuery = query.OrderBy(t => 0);

            var sortFields = new SortFields(sort);

            orderedQuery = sortFields.Fields?.Aggregate(orderedQuery, (current, sortField) =>
                                                        sortField.Field switch
            {
                "ticket" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Ticket)
                                       : current.ThenBy(t => t.Ticket)),
                "title" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Title)
                                       : current.ThenBy(t => t.Title)),
                "priority" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.PriOrd)
                                       : current.ThenBy(t => t.PriOrd)),
                "status" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.StatOrd)
                                       : current.ThenBy(t => t.StatOrd)),
                "owner" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Owner)
                                       : current.ThenBy(t => t.Owner)),
                "submitter" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Submitter)
                                       : current.ThenBy(t => t.Submitter)),
                "asset" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Asset)
                                       : current.ThenBy(t => t.Asset)),
                "referredto" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.ReferredTo)
                                       : current.ThenBy(t => t.ReferredTo)),
                "dept" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Dept)
                                       : current.ThenBy(t => t.Dept)),
                "location" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Location)
                                       : current.ThenBy(t => t.Location)),
                "created" => (sortField.SortDesc
                                       ? current.ThenByDescending(t => t.Created)
                                       : current.ThenBy(t => t.Created)),
                _ => current
            }
Esempio n. 25
0
 public void AddField(SortField <T> field)
 {
     SortFields.Add(field);
 }
Esempio n. 26
0
 /// <summary>
 /// Sorts the contents based on the sort field specified
 /// </summary>
 /// <param name="bAscending">ascending or descending</param>
 /// <param name="sortField">one of the sort fields above</param>
 /// <returns>true on success</returns>
 public bool SortContents(bool bAscending, SortFields sortField)
 {
     return MAPISortContents(pMAPI, bAscending, (int)sortField);
 }
Esempio n. 27
0
        /// <summary>
        /// Internal operation for adding the ordered results
        /// </summary>
        /// <param name="descending">if set to <c>true</c> [descending].</param>
        /// <param name="fields">The field names.</param>
        /// <returns>A new <see cref="IBooleanOperation"/> with the clause appended</returns>
        private LuceneBooleanOperation OrderByInternal(bool descending, params SortableField[] fields)
        {
            if (fields == null)
            {
                throw new ArgumentNullException(nameof(fields));
            }

            foreach (var f in fields)
            {
                var fieldName = f.FieldName;

                var defaultSort = SortField.STRING;

                switch (f.SortType)
                {
                case SortType.Score:
                    defaultSort = SortField.SCORE;
                    break;

                case SortType.DocumentOrder:
                    defaultSort = SortField.DOC;
                    break;

                case SortType.String:
                    defaultSort = SortField.STRING;
                    break;

                case SortType.Int:
                    defaultSort = SortField.INT;
                    break;

                case SortType.Float:
                    defaultSort = SortField.FLOAT;
                    break;

                case SortType.Long:
                    defaultSort = SortField.LONG;
                    break;

                case SortType.Double:
                    defaultSort = SortField.DOUBLE;
                    break;

                case SortType.Short:
                    defaultSort = SortField.SHORT;
                    break;

                case SortType.Byte:
                    defaultSort = SortField.BYTE;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                //get the sortable field name if this field type has one
                var valType = _searchContext.GetFieldValueType(fieldName);
                if (valType?.SortableFieldName != null)
                {
                    fieldName = valType.SortableFieldName;
                }

                SortFields.Add(new SortField(fieldName, defaultSort, descending));
            }

            return(new LuceneBooleanOperation(this));
        }
Esempio n. 28
0
 public FindRequest <T> Sort(string fieldName, bool ascending = true)
 {
     SortFields.Add(new Sorting(fieldName, ascending));
     return(this);
 }
Esempio n. 29
0
 public bool HasSortFields()
 {
     return(SortFields != null && SortFields.Any());
 }
Esempio n. 30
0
        internal static async Task <ScheduleOverviews> MapToScheduleOverviews(
            ScheduleOverviewsRequest request,
            IQueryable <ScheduleEntity> schedules,
            IQueryable <CompanyEntity> companies,
            IQueryable <WellEntity> wells)
        {
            // Build SQL query
            var query1 = from s in schedules.GetByRegions(request.Regions)
                         .GetByOperators(request.Operators)
                         .GetByStartNextDays(request.StartNextDays)
                         join c in companies on s.CompanyId equals c.Id
                         join w in wells on s.WellId equals w.Id
                         select new
            {
                Schedule = s,
                Company  = c,
                Well     = w
            };

            var query = from q1 in query1
                        select new ScheduleOverviewQuery
            {
                Schedule = q1.Schedule,
                Company  = q1.Company,
                Well     = q1.Well
            };

            var sortBy = new SortFields <ScheduleOverviewQuery>
            {
                { "wellName", e => e.Well.Name },
                { "operator", e => e.Company.Name },
                { "fracStartDate", e => e.Schedule.FracStartDate }
            };

            query = query
                    .SortBy(request, sortBy)
                    .GetPage(request);

            // Run SQL query
            var entities = await query.ToArrayAsync();

            var totalCount = await query1.CountAsync();

            // Map entities to models
            var overviews = entities.Select(e => new ScheduleOverview(
                                                e.Schedule.Id,
                                                e.Well.Name,
                                                e.Company.Name,
                                                e.Schedule.FracStartDate,
                                                e.Schedule.FracEndDate,
                                                (e.Schedule.FracEndDate - e.Schedule.FracStartDate).Days,
                                                e.Well.Api,
                                                e.Well.SurfaceLat,
                                                e.Well.SurfaceLong,
                                                e.Well.BottomholeLat,
                                                e.Well.BottomholeLong,
                                                e.Well.Tvd,
                                                e.Schedule.FracStartDate.GetStartInDays(),
                                                e.Schedule.FracStartDate.GetScheduleStatus()));

            var os      = overviews as ScheduleOverview[] ?? overviews.ToArray();
            var summary = new ScheduleSummary(
                os.Count(o => o.Status == ScheduleStatus.Operating),
                os.Count(o => o.Status == ScheduleStatus.Next7Days),
                os.Count(o => o.Status == ScheduleStatus.Next830Days),
                os.Count(o => o.Status == ScheduleStatus.Next3160Days),
                os.Count(o => o.Status == ScheduleStatus.Next60PlusDays));

            return(new ScheduleOverviews(
                       request,
                       totalCount,
                       os,
                       summary));
        }
Esempio n. 31
0
 /// <summary>
 /// Sorts the contents based on the sort field specified
 /// </summary>
 /// <param name="bAscending">ascending or descending</param>
 /// <param name="sortField">one of the sort fields defined in NetMAPI</param>
 /// <returns>true on success</returns>
 public bool SortContents(bool bAscending, SortFields sortField)
 {
     return FolderSortContents(pObject, bAscending, (int)sortField);
 }
Esempio n. 32
0
        private ListFilter <T> Compile()
        {
            var            uniqueCode = GetUniqueCode();
            ListFilter <T> resultFilter;

            if (!FiltersCache.TryGetValue(uniqueCode, out resultFilter))
            {
                var includeAssemblies = new HashSet <string>();

                var provider = new CSharpCodeProvider(new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v3.5" }
                });

                var name = "Filter";
                if (FilterBy != null)
                {
                    name += "_" + Regex.Replace(FilterBy, @"\W", "");
                }
                if (SortFields != null)
                {
                    name += "_Sort_" + Regex.Replace(SortFields.Aggregate((y, x) => y), @"\W", "");
                }
                var typeName = provider.CreateValidIdentifier(name);


                var targetTypeName = typeof(T).FullName.Replace('+', '.');
                var code           = new StringBuilder();
                code.AppendLine("using System;");
                code.AppendLine("using System.Collections;");
                code.AppendLine("using System.Collections.Generic;");
                code.AppendLine("using System.Linq;");
                code.AppendLine("using ASC.Api.Collections;");
                code.AppendLine("using System.Globalization;");

                code.AppendFormat("public class {1} : ListFilter<{0}> {{\r\n", targetTypeName, typeName);
                code.AppendFormat(
                    "    public override IEnumerable<{0}> FilterList(IEnumerable<{0}> items, bool sortDescending, FilterOperation operation, string[] filterValues){{\r\n",
                    targetTypeName);
                //Do a needed operations

                //TODO: Do a null checks!
                if (ShouldFilter())
                {
                    try
                    {
                        var filters      = FilterBy.Split(',');
                        var filterChecks = new List <string>();
                        foreach (var filter in filters)
                        {
                            var propInfo = GetPropertyInfo(filter).Where(x => x != null).ToList();
                            foreach (var propertyInfo in propInfo)
                            {
                                includeAssemblies.Add(propertyInfo.PropertyType.Assembly.Location);
                            }

                            var byProperty = GetPropertyPath(propInfo);

                            var nullCheck = GetNullCheck("item", propInfo);


                            filterChecks.Add(string.Format("({1}Satisfy(operation, filterValues, item.{0}{2}))",
                                                           byProperty,
                                                           string.IsNullOrEmpty(nullCheck) ? "" : (nullCheck + " && "),
                                                           GetPropertyToString(propInfo.Last())));
                        }
                        code.AppendFormat(
                            "items = items.Where(item =>{0});\r\n", string.Join(" || ", filterChecks.ToArray()));
                    }
                    catch (Exception)
                    {
                    }
                }
                if (ShouldSort())
                {
                    var propInfo = SortFields.Select(x => GetPropertyInfo(x)).Where(x => x != null).ToList();
                    //Add where
                    if (propInfo.Any())
                    {
                        foreach (var info in propInfo)
                        {
                            foreach (var propertyInfo in info)
                            {
                                includeAssemblies.Add(propertyInfo.PropertyType.Assembly.Location);
                            }

                            var nullCheck = GetNullCheck("item", info);
                            if (!string.IsNullOrEmpty(nullCheck))
                            {
                                code.AppendFormat("items=items.Where(item=>{0});", nullCheck);
                                code.AppendLine();
                            }
                        }

                        var byProperties = propInfo.Select(x => GetPropertyPath(x)).ToList();
                        code.AppendLine("items = sortDescending");
                        code.AppendFormat("?items.OrderByDescending(item => item.{0})", byProperties.First());
                        foreach (var byProperty in byProperties.Skip(1))
                        {
                            code.AppendFormat(".ThenByDescending(item => item.{0})", byProperty);
                        }

                        code.AppendFormat(": items.OrderBy(item => item.{0})", byProperties.First());
                        foreach (var byProperty in byProperties.Skip(1))
                        {
                            code.AppendFormat(".ThenBy(item => item.{0})", byProperty);
                        }
                        code.AppendLine(";");
                    }
                }

                code.AppendFormat("return items;\r\n");
                code.AppendLine("} }");

                var assemblyName = "filter" + Guid.NewGuid().ToString("N");
                var cp           = new CompilerParameters
                {
                    GenerateExecutable      = false,
                    OutputAssembly          = assemblyName,
                    GenerateInMemory        = true,
                    TreatWarningsAsErrors   = false,
                    CompilerOptions         = "/optimize /t:library",
                    IncludeDebugInformation = false,
                };

                cp.ReferencedAssemblies.Add("mscorlib.dll");
                cp.ReferencedAssemblies.Add("system.dll");
                cp.ReferencedAssemblies.Add("System.Core.dll");
                cp.ReferencedAssemblies.Add(GetType().Assembly.Location);
                cp.ReferencedAssemblies.Add(typeof(T).Assembly.Location);
                foreach (var includeAssembly in includeAssemblies)
                {
                    cp.ReferencedAssemblies.Add(includeAssembly);
                }

                var cr = provider.CompileAssemblyFromSource(cp, code.ToString());
                if (!cr.Errors.HasErrors)
                {
                    var assembly      = cr.CompiledAssembly;
                    var evaluatorType = assembly.GetType(typeName);
                    var evaluator     = Activator.CreateInstance(evaluatorType);
                    resultFilter = evaluator as ListFilter <T>;
                }
                //Add anyway!!!
                FiltersCache.Add(uniqueCode, resultFilter);
            }
            return(resultFilter);
        }