Example #1
0
        public void Parse(SelectContext ctx)
        {
            //var result = new SelectContext();

            //if (ctx == null)
            //{
            //    result.ContextType = ContextType.Program;
            //}

            //SelectAtomContext.Context_Stack.Push(result);

            foreach (var atom in Select_atoms)
            {
                var a = new SelectAtomContext();
                ctx.Unions.Add(new UnionContext() { Context = a });
                atom.Parse(a);
            }

            for (var index = 0; index < this.Union_types.Count; index++)
            {
                ctx.Unions[index].UnionType = Union_types[index].Parse();
            }

            //result.ParentContext = ctx;
            //SelectAtomContext.Context_Stack.Pop();

            //return result;
        }
Example #2
0
            DependencyProperty.Register("ExclusiveItems", typeof(Collection <object>), typeof(EnumTypeSelector), new UIPropertyMetadata(null)); // NOXLATE

        #endregion


        protected override void UpdateContexts(IEnumerable <DynamicValue> validValueItemHint)
        {
            if (this.Contexts.Count > 0)
            {
                return;
            }
            SelectContext context = CreateContext(this.EnumType, RuleEditingContext, this, this.SelectContextName, ExclusiveItems);

            this.Contexts.Add(context);
        }
Example #3
0
 public ReWriteResult(IQueryable <T> originalQueryable, IQueryable <T> reWriteQueryable, int?skip, int?take, IEnumerable <PropertyOrder> orders, SelectContext selectContext, GroupByContext groupByContext)
 {
     OriginalQueryable = originalQueryable;
     ReWriteQueryable  = reWriteQueryable;
     Skip           = skip;
     Take           = take;
     Orders         = orders;
     SelectContext  = selectContext;
     GroupByContext = groupByContext;
 }
        public async Task ProcessAsync_SelectedAttributeExplicitlySet_IgnoresModelExpression()
        {
            // Arrange
            var modelValue    = "bar";
            var modelExplorer = new EmptyModelMetadataProvider().GetModelExplorerForType(typeof(Model), new Model()
            {
                SimpleProperty = modelValue
            })
                                .GetExplorerForProperty(nameof(Model.SimpleProperty));
            var viewContext     = new ViewContext();
            var modelExpression = nameof(Model.SimpleProperty);

            var modelHelper = new Mock <IModelHelper>();

            modelHelper.Setup(mock => mock.GetModelValue(viewContext, modelExplorer, modelExpression)).Returns(modelValue);

            var selectContext = new SelectContext(aspFor: new ModelExpression(modelExpression, modelExplorer));

            var context = new TagHelperContext(
                tagName: "govuk-select-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(SelectContext), selectContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-select-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Item text"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new SelectItemTagHelper(modelHelper.Object)
            {
                Selected    = false,
                Value       = modelValue,
                ViewContext = viewContext
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Collection(
                selectContext.Items,
                item =>
            {
                Assert.False(item.Selected);
            });
        }
        /// <summary>
        /// Generate a drop down list.
        /// </summary>
        /// <typeparam name="TProperty">The type of the property.</typeparam>
        /// <param name="property">The property.</param>
        /// <param name="items">The items.</param>
        /// <param name="selectedItem">The selected item.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public virtual MvcHtmlString DropdownFor <TProperty>(Expression <Func <TModel, TProperty> > property,
                                                             IEnumerable <SelectListItem> items,
                                                             object selectedItem = null, object htmlAttributes = null)
        {
            var ctx           = CreateInputContext(property, htmlAttributes);
            var context       = new SelectContext(ctx, null, items);
            var builder       = _tagBuilderFactory.Create("select");
            var generatedTags = builder.Generate(context);

            return(InvokeFormItemAdapters(context.Metadata, generatedTags).ToMvcString());
        }
        /*
         *      public virtual MvcHtmlString DropdownFor<TProperty>(Expression<Func<TModel, TProperty>> property,
         *                                                                      IEnumerable<TProperty> items,
         *                                                                      object selectedItem = null,
         *                                                                      object htmlAttributes = null)
         *          where TFormatter : ISelectItemFormatter, new()
         *      {
         *          var ctx = CreateInputContext(property, htmlAttributes);
         *          var context = new SelectContext(ctx, new TFormatter(), items);
         *          var generatedTags = _selectGenerator.Generate(context);
         *          return InvokeFormItemAdapters(context.Metadata, generatedTags).ToMvcString();
         *
         *      }*/

        /// <summary>
        /// Dropdowns for.
        /// </summary>
        /// <typeparam name="TProperty">The type of the property.</typeparam>
        /// <param name="property">The property.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public virtual MvcHtmlString DropdownFor <TProperty>(Expression <Func <TModel, TProperty> > property,
                                                             object htmlAttributes = null)
            where TProperty : struct, IConvertible, IFormattable, IComparable
        {
            var ctx           = CreateInputContext(property, htmlAttributes);
            var context       = new SelectContext(ctx, null, null);
            var builder       = _tagBuilderFactory.Create("select");
            var generatedTags = builder.Generate(context);

            return(InvokeFormItemAdapters(context.Metadata, generatedTags).ToMvcString());
        }
Example #7
0
        private IExpression GetExpression(SelectContext context, AssociationClassCallExp association)
        {
            switch (association.Source)
            {
            case VariableExp variableRef:
                var variable       = variableRef.ReferredVariable.Name;
                var associationEnd = association.ReferredAssociationEnds;
                var alias          = variable + "_" + associationEnd.Association;
                context.Body.Joins.Add(new Join
                {
                    Left      = false,
                    RightItem = new Table
                    {
                        Name  = associationEnd.Association,
                        Alias = new Alias {
                            Name = alias
                        }
                    },
                    OnExp = new EqualsToExpression
                    {
                        LeftExp = new Column
                        {
                            Table = new Table
                            {
                                Name  = context.Variables[variable],
                                Alias = new Alias {
                                    Name = variable
                                }
                            },
                            Name = context.Variables[variable] + "_id",
                        },
                        RightExp = new Column
                        {
                            Table = new Table
                            {
                                Name  = associationEnd.Association,
                                Alias = new Alias {
                                    Name = alias
                                }
                            },
                            Name = associationEnd.Opp.Name,
                        }
                    }
                });
                context.LastJoin = Tuple.Create(variable, associationEnd);
                return(null);

            default:
                throw new NotSupportedException();
            }
        }
Example #8
0
        public SelectResult Merge(SelectResult[] partitionResults)
        {
            SelectContext localContext = SafeGetContext(null);

            if (localContext.Pass1Results != null)
            {
                if (localContext.Pass1Results.Details.Succeeded == false || localContext.Pass1Results.CountReturned == 0)
                {
                    return(localContext.Pass1Results);
                }
            }

            return(localContext.Merge(partitionResults));
        }
Example #9
0
        public SelectResult Compute(Partition p)
        {
            SelectContext localContext = SafeGetContext(p);

            if (localContext.Pass1Results != null)
            {
                if (localContext.Pass1Results.Details.Succeeded == false || localContext.Pass1Results.CountReturned == 0)
                {
                    return(localContext.Pass1Results);
                }
            }

            return(localContext.Compute(p));
        }
Example #10
0
        private IExpression GetExpression(SelectContext context, IteratorExp iterator)
        {
            GetExpression(context, (dynamic)iterator.Source);
            var alias = iterator.Iterator[0].Name;

            if (iterator.Source is OperationCallExp operationCall && operationCall.ReferredOperation == Operator.AllInstances)
            {
                var table = context.Body.FromItem as Table;
                table.Alias = new Alias
                {
                    Name = alias
                };
                context.Variables.Add(alias, table.Name);
            }
Example #11
0
 private IExpression GetExpression(SelectContext context, BooleanLiteralExp booleanLiteral)
 {
     return(new EqualsToExpression
     {
         LeftExp = new LongValue
         {
             Value = 1
         },
         RightExp = new LongValue
         {
             Value = booleanLiteral.BooleanValue.GetValueOrDefault() ? 1 : 0
         }
     });
 }
Example #12
0
            private static ushort[] GetLIDsToReturnSparse(Partition p, SelectContext context, SelectResult result, ShortSet whereSet)
            {
                // Get the set of matching IDs
                ushort[] lids = whereSet.Values;

                // Lame - store the total to return here so we don't have to compute again
                result.Total = (uint)(lids.Length);

                // Compute the count to return - the count or the number left after skipping
                int countToReturn = Math.Min(context.Count, (int)(lids.Length));

                // Get the values for all matches in the Order By column and IDs by the order by values
                Array orderByValues = p.Columns[context.OrderByColumn].GetValues(lids);

                Array.Sort(orderByValues, lids);

                // Walk in ascending or descending order and return the matches
                int count = 0;

                ushort[] lidsToReturn = new ushort[countToReturn];
                if (countToReturn == 0)
                {
                    return(lidsToReturn);
                }

                int index, end, step;

                if (context.OrderByDescending)
                {
                    index = (int)(lids.Length - 1);
                    end   = index - countToReturn;
                    step  = -1;
                }
                else
                {
                    index = 0;
                    end   = index + countToReturn;
                    step  = 1;
                }

                for (; index != end; index += step)
                {
                    lidsToReturn[count] = lids[index];
                    count++;
                }

                return(lidsToReturn);
            }
        public void SetLabel_AlreadyGotItem_ThrowsInvalidOperationException()
        {
            // Arrange
            var context = new SelectContext(aspFor: null);

            context.AddItem(new SelectItem()
            {
                Content = new HtmlString("Option")
            });

            // Act
            var ex = Record.Exception(() => context.SetLabel(false, null, new HtmlString("Error")));

            // Assert
            Assert.IsType <InvalidOperationException>(ex);
            Assert.Equal("<govuk-select-label> must be specified before <govuk-select-item>.", ex.Message);
        }
Example #14
0
        private SelectContext SafeGetContext(Partition p)
        {
            SelectContext ctx = _context;

            if (ctx == null)
            {
                // This case should only happen for unit tests
                ctx = new SelectContext(this);
                if (p != null && string.IsNullOrEmpty(this.OrderByColumn))
                {
                    ctx.OrderByColumn     = p.IDColumn.Name;
                    ctx.OrderByDescending = true;
                }
            }

            return(ctx);
        }
        public async Task ProcessAsync_AddItemsToContext()
        {
            // Arrange
            var selectContext = new SelectContext(aspFor: null);

            var context = new TagHelperContext(
                tagName: "govuk-select-item",
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object>()
            {
                { typeof(SelectContext), selectContext }
            },
                uniqueId: "test");

            var output = new TagHelperOutput(
                "govuk-select-item",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.AppendHtml(new HtmlString("Item text"));
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            var tagHelper = new SelectItemTagHelper()
            {
                Disabled = true,
                Selected = true,
                Value    = "value"
            };

            // Act
            await tagHelper.ProcessAsync(context, output);

            // Assert
            Assert.Collection(
                selectContext.Items,
                item =>
            {
                Assert.Equal("Item text", item.Content.RenderToString());
                Assert.True(item.Disabled);
                Assert.True(item.Selected);
                Assert.Equal("value", item.Value);
            });
        }
Example #16
0
        public static bool TryVisitSelect(this MethodCallExpression node, SelectExpressionsCollection options, MemberContext context, out MemberContext newContext)
        {
            newContext = null;
            bool result = node.Method.DeclaringType == typeof(Queryable) && node.Method.Name == Select;

            if (result)
            {
                Expression arg = node.Arguments[1];

                if (arg.NodeType == ExpressionType.Quote)
                {
                    LambdaExpression lambda = (LambdaExpression)node.Arguments[1].StripQuotes();

                    if (lambda.Body is NewExpression selectMember)
                    {
                        newContext = new SelectContext(selectMember, context);
                    }

                    if (lambda.Body is MemberInitExpression memberInit)
                    {
                        newContext = new SelectContext(memberInit, context);
                    }

                    if (lambda.Body is ParameterExpression)
                    {
                        newContext = context;
                        return(result);
                    }

                    if (newContext != null)
                    {
                        options.Fields.Clear();
                        SelectFieldsVisitor visitor = new SelectFieldsVisitor(context, options);
                        visitor.Visit(lambda.Body);

                        return(result);
                    }
                }

                throw new InvalidOperationException($"Unable to translate '{Select}' method.");
            }

            return(result);
        }
Example #17
0
            private static ushort[] GetLIDsToReturnDense(Partition p, SelectContext context, SelectResult result, ShortSet whereSet)
            {
                // Get the sorted IDs, *if available*
                IList <ushort>   sortedLIDs;
                int              sortedLIDsCount;
                IColumn <object> orderByColumn = p.Columns[context.OrderByColumn];

                if (!orderByColumn.TryGetSortedIndexes(out sortedLIDs, out sortedLIDsCount))
                {
                    return(GetLIDsToReturnSparse(p, context, result, whereSet));
                }

                // Determine how many to return. Stop if none.
                int countToReturn = Math.Min(context.Count, (int)(result.Total));

                ushort[] lidsToReturn = new ushort[countToReturn];
                if (countToReturn == 0)
                {
                    return(lidsToReturn);
                }

                // Enumerate matches in OrderBy order and return the requested columns for them
                ushort countAdded  = 0;
                int    sortedIndex = (context.OrderByDescending ? orderByColumn.Count - 1 : 0);
                int    lastIndex   = (context.OrderByDescending ? -1 : orderByColumn.Count);
                int    step        = (context.OrderByDescending ? -1 : 1);

                // Return the next 'count' matches
                for (; sortedIndex != lastIndex; sortedIndex += step)
                {
                    ushort lid = sortedLIDs[sortedIndex];
                    if (whereSet.Contains(lid))
                    {
                        lidsToReturn[countAdded] = lid;
                        if (++countAdded == countToReturn)
                        {
                            break;
                        }
                    }
                }

                return(lidsToReturn);
            }
Example #18
0
        private IExpression GetAllInstances(SelectContext context, IEntity referredType)
        {
            var table = new Table
            {
                Name = referredType.Name,
            };

            if (context.Body.FromItem == null)
            {
                context.Body.FromItem = table;
            }
            else
            {
                context.Body.Joins.Add(new Join
                {
                    RightItem = table
                });
            }
            return(null);
        }
Example #19
0
        public SelectStatement ToSql(IOclExpression expression)
        {
            var context = new SelectContext {
                Body = new PlainSelect()
            };
            var result = GetExpression(context, (dynamic)expression);
            var body   = context.Body;

            body.SelItems.Add(new SelectItem
            {
                Exp   = result,
                Alias = new Alias
                {
                    Name = "res"
                }
            });
            Complete(body, context);
            return(new SelectStatement
            {
                SelectBody = body
            });
        }
Example #20
0
        public SelectResult Merge(SelectResult[] partitionResults)
        {
            SelectContext localContext = SafeGetContext(null);

            if (localContext.Pass1Results != null)
            {
                if (localContext.Pass1Results.Details.Succeeded == false || localContext.Pass1Results.CountReturned == 0)
                {
                    return(localContext.Pass1Results);
                }
            }

            SelectResult result = localContext.Merge(partitionResults);

            if (localContext.Pass1Results != null)
            {
                // If this isn't the first pass, use the total from the first pass
                result.Total = localContext.Pass1Results.Total;
            }

            return(result);
        }
Example #21
0
        private IExpression GetExpression(SelectContext context, PropertyCallExp propertyCall)
        {
            switch (propertyCall.Source)
            {
            case VariableExp variableRef:
                var table = context.Variables[variableRef.ReferredVariable.Name];
                return(new Column
                {
                    Table = new Table
                    {
                        Name = table,
                        Alias = new Alias
                        {
                            Name = variableRef.ReferredVariable.Name
                        }
                    },
                    Name = propertyCall.ReferredProperty.Name
                });

            default:
                throw new NotSupportedException();
            }
        }
 private static async Task _enumerate(AsyncEnumerator <TResult> .Yield yield, SelectContext <TSource, TResult> context)
 {
     try
     {
         while (await context.Source.MoveNextAsync(yield.CancellationToken).ConfigureAwait(false))
         {
             await yield.ReturnAsync(context.Selector(context.Source.Current)).ConfigureAwait(false);
         }
     }
     finally
     {
         if (context.DisposeSource)
         {
             context.Source.Dispose();
         }
     }
 }
 private void SetSelect(SelectContext select, string name, string varName)
 {
     if (select != null)
     {
         var                    dq              = new DataCube(name, DataStatement.SELECT, varName);
         FieldsContext          fields          = select.fields();
         FilterconditionContext Filtercondition = select.filtercondition();
         SortstatementContext   sortStatement   = select.sortstatement();
         if (fields != null)
         {
             StringltrContext[] fieldStrings = fields.stringltr();
             if (fieldStrings != null)
             {
                 foreach (StringltrContext sc in fieldStrings)
                 {
                     if (sc.strings() != null)
                     {
                         var ss = sc.strings().GetText();
                         if (ss.IndexOf(":") > 0)
                         {
                             var sf = ss.Split(':');
                             dq.SelectStatement.AddField(new State.Field.StringField(sf[0], sf[1]));
                         }
                         else
                         {
                             dq.SelectStatement.AddField(new State.Field.StringField(ss, ss));
                         }
                     }
                     else if (sc.datefunction() != null)
                     {
                         DatefunctionContext df = sc.datefunction();
                         dq.SelectStatement.AddField(new State.Field.DateField(df.WORD().GetText(), sc.WORD().GetText())
                         {
                             Function = getDateFunction(df.DATEFUNCTION().GetText())
                         });
                     }
                     else if (sc.dateadvancefunction() != null)
                     {
                         DateadvancefunctionContext df = sc.dateadvancefunction();
                         var dfield = GetDateField(df);
                         dfield.AliasName = sc.WORD().GetText();
                         dq.SelectStatement.AddField(dfield);
                     }
                     else if (sc.numberfunction() != null)
                     {
                         NumberfunctionContext nf = sc.numberfunction();
                         State.Field.NumberField.FunctionType nft = getNumFunction(nf.NUMBERUDF().GetText());
                         string fm = "";
                         if (nft == State.Field.NumberField.FunctionType.NUMBERFORMAT || nft == State.Field.NumberField.FunctionType.ROUND)
                         {
                             //  fm = nf.dataformat().INT().GetText().ToString();
                         }
                         dq.SelectStatement.AddField(new State.Field.NumberField(nf.WORD().GetText(), sc.WORD().GetText())
                         {
                             Function = getNumFunction(nf.NUMBERUDF().GetText()), Format = fm
                         });
                     }
                     else if (sc.numberformat() != null)
                     {
                         NumberformatContext nf = sc.numberformat();
                         State.Field.NumberField.FunctionType nft = getNumFunction(nf.NUMBERUDF().GetText());
                         string fm = "";
                         if (nft == State.Field.NumberField.FunctionType.NUMBERFORMAT || nft == State.Field.NumberField.FunctionType.ROUND)
                         {
                             fm = nf.INT().GetText().ToString();
                         }
                         dq.SelectStatement.AddField(new State.Field.NumberField(nf.WORD().GetText(), sc.WORD().GetText())
                         {
                             Function = getNumFunction(nf.NUMBERUDF().GetText()), Format = fm
                         });
                     }
                     else if (sc.stringfunction() != null)
                     {
                         StringfunctionContext df = sc.stringfunction();
                         State.Field.StringField.FunctionType nft = getStringFunction(df.STRINGUDF().GetText());
                         //string fm = "";
                         //if (nft == State.Field.StringField.FunctionType.FORMAT)
                         //{
                         //    fm = df.dataformat().INT().GetText().ToString();
                         //}
                         dq.SelectStatement.AddField(new State.Field.StringField(df.WORD().GetText(), sc.WORD().GetText())
                         {
                             Function = getStringFunction(df.STRINGUDF().GetText()), Format = ""
                         });
                     }
                     else if (sc.stringformat() != null)
                     {
                         StringformatContext df = sc.stringformat();
                         State.Field.StringField.FunctionType nft = State.Field.StringField.FunctionType.FORMAT;
                         string fm = "";
                         if (nft == State.Field.StringField.FunctionType.FORMAT)
                         {
                             fm = df.TEXT().GetText();
                         }
                         dq.SelectStatement.AddField(new State.Field.StringField(df.WORD().GetText(), sc.WORD().GetText())
                         {
                             Function = nft, Format = fm
                         });
                     }
                 }
             }
         }
         if (Filtercondition != null)
         {
             ConditionContext condition = Filtercondition.condition();
             var search = new State.Search(condition.children[0].GetText(), condition.children[1].GetText(), condition.children[2].GetText());
             dq.SelectStatement.AddCondition(search);
         }
         if (sortStatement != null)
         {
             OrderContext order = sortStatement.order();
             dq.SelectStatement.AddOrder(new State.SortBy(order.ORDERBY()[0].GetText(), order.fields()[0].GetText()));
         }
         DataCubes.Add(dq);
     }
 }
Example #24
0
 private IExpression GetExpression(SelectContext context, VariableExp variableExp)
 {
     return(CreateColumn(context.Variables[variableExp.ReferredVariable.Name], variableExp.ReferredVariable.Name));
 }
Example #25
0
 public QueryAstBuilder()
 {
     _selectContext = new SelectContext(this);
     _returnContext = new ReturnContext(this);
 }
 public QuerySelectDiscoverVisitor(SelectContext selectContext)
 {
     _selectContext = selectContext;
 }
 private static async Task _enumerate(AsyncEnumerator <TResult> .Yield yield, SelectContext <TSource, TResult> context)
 {
     using (var enumerator = await context.Source.GetAsyncEnumeratorAsync(yield.CancellationToken).ConfigureAwait(false))
     {
         while (await enumerator.MoveNextAsync(yield.CancellationToken).ConfigureAwait(false))
         {
             await yield.ReturnAsync(context.Selector(enumerator.Current)).ConfigureAwait(false);
         }
     }
 }