public void OutputOrderByField(OrderByField valueSet) { OutputStatusMessage(string.Format("Values in {0}", valueSet.GetType())); foreach (var value in Enum.GetValues(typeof(OrderByField))) { OutputStatusMessage(value.ToString()); } }
/// <summary> /// 排序 /// </summary> /// <returns></returns> public override OrderByField[] GetOrder() { var list = new List <OrderByField>() { OrderByField.Create <DictDO>(nameof(DictDO.SortNo), FieldSortType.Asc) }; return(list.ToArray()); }
/// <summary> /// 排序 /// </summary> /// <returns></returns> public override OrderByField[] GetOrder() { var list = new List <OrderByField>() { OrderByField.Create <XsTaskBaseDO>(nameof(XsTaskBaseDO.CreateDate), FieldSortType.Desc) }; return(list.ToArray()); }
public OrderByField[] GetOrder() { var list = new List <OrderByField>() { OrderByField.Create(nameof(UserEntity.AddTime), FieldSortType.Asc) }; return(list.ToArray()); }
/// <summary> /// 排序 /// </summary> /// <returns></returns> public override OrderByField[] GetOrder() { var list = new List <OrderByField>() { OrderByField.Create <ScheduleTaskDO>(nameof(ScheduleTaskDO.LineCode), FieldSortType.Asc) }; return(list.ToArray()); }
public static IOrderedQueryable <TEntity> ThenBy <TEntity>(this IOrderedQueryable <TEntity> source, OrderByField orderByField) where TEntity : class { if (orderByField.PropertyExpression != null) { if (orderByField.IsAscending) { return(Queryable.ThenBy(source, (dynamic)orderByField.PropertyExpression)); } return(Queryable.ThenByDescending(source, (dynamic)orderByField.PropertyExpression)); } return(source.ThenBy(orderByField.PropertyName, orderByField.IsAscending)); }
/// <summary> /// 組合Order By所需條件 /// </summary> /// <param name="OrderByList">傳入Orderby所需內容</param> /// <returns>回傳Order By所需SQL</returns> private static string GetOrderBy(OrderByField[] OrderByList) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < OrderByList.Length; i++) { switch (OrderByList[i].FileOrderByType) { case OrderByType.Asc: if (i == 0) { sb.Append("Order By "); sb.AppendFormat("{0}", OrderByList[i].FieldName); } else { sb.AppendFormat(",{0}", OrderByList[i].FieldName); } break; case OrderByType.Desc: if (i == 0) { sb.Append("Order By "); sb.AppendFormat("{0} Desc", OrderByList[i].FieldName); } else { sb.AppendFormat(",{0} Desc", OrderByList[i].FieldName); } break; } } return sb.ToString(); }
private async Task <bool> Search() { _searchTokenSource?.Dispose(); _searchTokenSource = new CancellationTokenSource(); return(await Task.Run(async() => { try { SearchResult = null; var db = new DatabaseInteraction(); var types = ObjectTypes.Where((x) => x.Selected).Select((x) => x.Name).ToList(); var searchParams = new DatabaseInteraction.DeepSkyObjectSearchParams(); searchParams.Constellation = SelectedConstellation; searchParams.DsoTypes = types; searchParams.ObjectName = SearchObjectName; searchParams.RightAscension.From = SelectedRAFrom; searchParams.RightAscension.Thru = SelectedRAThrough; searchParams.Declination.From = Nullable.Compare(SelectedDecFrom, SelectedDecThrough) > 0 ? SelectedDecThrough : SelectedDecFrom; searchParams.Declination.Thru = Nullable.Compare(SelectedDecFrom, SelectedDecThrough) > 0 ? SelectedDecFrom : SelectedDecThrough; searchParams.Brightness.From = SelectedBrightnessFrom; searchParams.Brightness.Thru = SelectedBrightnessThrough; searchParams.Magnitude.From = SelectedMagnitudeFrom; searchParams.Magnitude.Thru = SelectedMagnitudeThrough; searchParams.Size.From = SelectedSizeFrom; searchParams.Size.Thru = SelectedSizeThrough; searchParams.SearchOrder.Field = OrderByField.ToString().ToLower(); searchParams.SearchOrder.Direction = OrderByDirection.ToString(); var result = await db.GetDeepSkyObjects( profileService.ActiveProfile.ApplicationSettings.SkyAtlasImageRepository, searchParams, _searchTokenSource.Token ); var longitude = profileService.ActiveProfile.AstrometrySettings.Longitude; var latitude = profileService.ActiveProfile.AstrometrySettings.Latitude; ResetRiseAndSetTimes(); DateTime d = GetReferenceDate(SelectedDate); Parallel.ForEach(result, (obj) => { var cloneDate = d; obj.SetDateAndPosition(cloneDate, latitude, longitude); _searchTokenSource.Token.ThrowIfCancellationRequested(); }); /* Check if Altitude Filter is not default */ if (!(SelectedAltitudeTimeFrom == DateTime.MinValue && SelectedAltitudeTimeThrough == DateTime.MaxValue && SelectedMinimumAltitudeDegrees == 0)) { var filteredList = result.Where((x) => { return x.Altitudes.Where((y) => { return (y.X > DateTimeAxis.ToDouble(SelectedAltitudeTimeFrom) && y.X < DateTimeAxis.ToDouble(SelectedAltitudeTimeThrough)); }).All((z) => { return z.Y > SelectedMinimumAltitudeDegrees; }); }); var count = filteredList.Count(); /* Apply Altitude Filter */ SearchResult = new PagedList <DeepSkyObject>(PageSize, filteredList); } else { SearchResult = new PagedList <DeepSkyObject>(PageSize, result); } } catch (OperationCanceledException) { } return true; })); }
/// <summary> /// Validação e processamento da querystring /// Neste método está toda a inteligencia necessária para separar e preparar /// a querystring para execução do controller /// </summary> /// <returns> Erros a retornar pela API</returns> public ApiStatusResponse ValidateQryString() { QueryStringPairs = null; QueryStringPairs = Controller.Request.GetQueryNameValuePairs(); // tem querystring mas é inválida if (QueryStringPairs == null) { // retorna erro ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } // se não têm querystring if (QueryStringPairs.Count() <= 0) { // não há nada a validar return(null); } // agora vamos ver se temos campos na querystring // exemplo: cmoeda (os campos não têm prefixo. só os comandos) var QueryFields = from itemCommand in QueryStringPairs where !itemCommand.Key.ToLowerInvariant().StartsWith("@") select itemCommand; if ((QueryFields != null) && (QueryFields.Count <KeyValuePair <string, string> >() == 0)) { QueryFields = null; } // limpar MatchedFields = null; // temos campos, vamos ver se são da lista de campos // válidos if (!QueryFields.IsNullOrEmpty()) { var tempMatchedFields = (from itemField in QueryFields where FieldsAllowedForQuery.Find(itemField.Key.ToLowerInvariant()) != null select itemField).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); MatchedFields = new Dictionary <string, AutorizedField>(); foreach (var match in tempMatchedFields) { var foundField = FieldsAllowedForQuery.Find(match.Key.ToLowerInvariant()); if ((match.Value.ToString().IndexOf('§') >= 0)) { foundField.Value = match.Value.Replace('§', '%'); } else { foundField.Value = match.Value; } MatchedFields.Add(match.Key, foundField); } } if ((MatchedFields != null) && (MatchedFields.Count <KeyValuePair <string, AutorizedField> >() == 0)) { MatchedFields = null; } // agora vamos ver se temos comandos na querystring // os comandos são identificados pelo perfixo @ // exemplo: @page var QueryCommands = from itemCommand in QueryStringPairs where itemCommand.Key.ToLowerInvariant().StartsWith("@") select itemCommand; if ((QueryCommands != null) && (QueryCommands.Count <KeyValuePair <string, string> >() == 0)) { QueryCommands = null; } // limpar MatchedCommands = null; // temos comandos, vamos ver se pertencem à lista de comandos válidos if (!QueryCommands.IsNullOrEmpty()) { MatchedCommands = (from itemCommand in QueryCommands where CommandsAllowedForQuery.Contains(itemCommand.Key.ToLowerInvariant()) select itemCommand).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); } if ((MatchedCommands != null) && (MatchedCommands.Count <KeyValuePair <string, string> >() == 0)) { MatchedCommands = null; } // se não tem campos e comandos var hasValidFields = !MatchedFields.IsNullOrEmpty(); var hasValidCommands = !MatchedCommands.IsNullOrEmpty(); if (!hasValidFields && !hasValidCommands) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida. Tem de indicar campos e/ou comandos válidos.", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } // tem comandos na qyerystring? if (!QueryCommands.IsNullOrEmpty()) { // mas não são válidos ou tem a mais if (!hasValidCommands | (MatchedCommands.Count() != QueryCommands.Count())) { MatchedCommands.Clear(); ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando comandos não suportados", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } else { // comandos válidos encontrados, vamos validar os comandos standard os restantes não são validados // @limit // @page // @order foreach (var item in MatchedCommands) { string command = item.Key.ToLowerInvariant(); switch (command) { case "@order": { if ((FieldsAllowedForOrder == null) || (FieldsAllowedForOrder.Count <= 0)) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando campos para ordenação não suportados", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } OrderByFields = null; OrderByFields = new Dictionary <string, OrderByField>(); string[] fields = item.Value.Split(','); foreach (string s in fields) { OrderByField field = new OrderByField() { FieldName = s }; OrderByFields.Add(field.FieldName, field); } if (!OrderByFields.IsNullOrEmpty()) { MatchedOrderFields = (from itemCommand in OrderByFields where FieldsAllowedForOrder.Find(itemCommand.Key.ToLowerInvariant()) != null select itemCommand).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); } if ((MatchedOrderFields != null) && (MatchedOrderFields.Count <KeyValuePair <string, OrderByField> >() == 0)) { MatchedOrderFields = null; } var hasValidOrderFields = !MatchedOrderFields.IsNullOrEmpty(); if (!hasValidOrderFields || (MatchedOrderFields.Count() != OrderByFields.Count())) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando campos para ordenação não suportados", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } break; } // comandos de paginação case "@limit": case "@page": { HasPagingCommand = true; if (command == "@limit") { try { PageSize = Convert.ToInt32(item.Value); if (PageSize <= 0) { throw new ArgumentException(); } } catch (Exception) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando um valor invalido para o comando @limit", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } } if (command == "@page") { try { PageNumber = Convert.ToInt32(item.Value); if (PageNumber <= 0) { throw new ArgumentException(); } } catch (Exception) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando um valor invalido para o comando @page", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } } break; } default: { if (!item.Value.IsNaturalNumber()) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = $"Está a tentar executar uma querystring inválida, com valores dos comandos @limit, @offset e @pagenumber invlálidos. Valor: {item.Value}", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } break; } } } } } // tem campos os na query string? if (!QueryFields.IsNullOrEmpty()) { // erro se não têm campos válidos ou se além de válidos tem outros não reconhecidos if (!hasValidFields || (MatchedFields.Count() != QueryFields.Count())) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = "Está a tentar executar uma querystring inválida, utilizando campos não suportados", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } // temos campos, mas só vamos permitir MaxNumberFieldsOnQueryString // se este for maior que 0 if ((MaxNumberFieldsOnQueryString > 0) && (MatchedFieldsCount > MaxNumberFieldsOnQueryString)) { ApiStatusResponse errorResponse = new ApiStatusResponse() { Code = "100", Detail = $"Não é possivel executar porque a querystring. Só pode filtrar por {MaxNumberFieldsOnQueryString} campo(s) de cada vez.", Title = "Querystring inválida", Type = "error" }; return(errorResponse); } } return(null); }