Example #1
0
        private void ProcessUpdateEntityReference(IODataRequestMessage requestMessage, IODataResponseMessage responseMessage, ODataPath odataPath)
        {
            // This is for change the reference in single-valued navigation property
            // PUT ~/Person(0)/Parent/$ref
            // {
            //     "@odata.context": "http://host/service/$metadata#$ref",
            //     "@odata.id": "Orders(10643)"
            // }

            if (this.HttpMethod == HttpMethod.PATCH)
            {
                throw Utility.BuildException(HttpStatusCode.MethodNotAllowed, "PATCH on a reference link is not supported.", null);
            }

            // Get the parent first
            var level = this.QueryContext.QueryPath.Count - 2;
            var parent = this.QueryContext.ResolveQuery(this.DataSource, level);

            var navigationPropertyName = ((NavigationPropertyLinkSegment)odataPath.LastSegment).NavigationProperty.Name;

            using (var messageReader = new ODataMessageReader(requestMessage, this.GetReaderSettings(), this.DataSource.Model))
            {
                var referenceLink = messageReader.ReadEntityReferenceLink();
                var queryContext = new QueryContext(this.ServiceRootUri, referenceLink.Url, this.DataSource.Model);
                var target = queryContext.ResolveQuery(this.DataSource);

                this.DataSource.UpdateProvider.UpdateLink(parent, navigationPropertyName, target);
                this.DataSource.UpdateProvider.SaveChanges();
            }

            ResponseWriter.WriteEmptyResponse(responseMessage);
        }
Example #2
0
 public override Resultset Get(QueryContext queryContext, object[] parameters)
 {
     object[] parameterValues = null;
     if (_parameterBindings != null)
     {
         parameterValues = new object[_parameterBindings.Length];
         for (int k = 0; k < _parameterBindings.Length; k++)
             parameterValues[k] = parameters[_parameterBindings[k]];
     }
     if (queryContext != null)
     {
         RowCache cache = queryContext.DataCache.Get(this, parameterValues);
         if (cache == null)
         {
             Resultset rs = base.Get(queryContext, parameters);
             if (queryContext.CacheEnabled && AccessPredicate == null)
                 queryContext.DataCache.Add(this, parameterValues, rs);
             return rs;
         }
         else
             return cache.GetResultset();
     }
     else
         return base.Get(queryContext, parameters);
 }
Example #3
0
        public string BuildRdsn(Type service, QueryContext[] contexts)
        {
            //_stages = stages;
            _contexts = contexts;
            _appClassName = service.Name;

            //BuildInputOutputValueTypes();
            BuildHeaderRdsn(service.Namespace);
            BuildRewrittenTypes();
            _builder.AppendLine("public class " + _appClassName + "Server_impl :" + _appClassName + "Server");
            _builder.BeginBlock();
            BuildServiceClientsRdsn();
            //thrift or protobuf
            BuildServiceCallsRdsn(_appClassName);
            foreach (var c in contexts)
                //never change
                BuildQueryRdsn(c);

            //always thrift
            BuildServer(_appClassName, ServiceContract.GetServiceCalls(service));

            _builder.EndBlock();

            BuildMain();
            BuildFooter();
            return _builder.ToString();
        }
Example #4
0
 /// <summary>
 /// Creates a new instance with some parameters.
 /// </summary>
 /// <param name="child">The child to add.</param>
 /// <param name="query">The associated query context.</param>
 /// <param name="line">The line where the tree expression starts.</param>
 /// <param name="column">The column in the line where the tree exp. starts.</param>
 public TreeExpression(ContainerExpression child, QueryContext query, int line, int column)
     : base(child)
 {
     Query = query;
     StartColumn = column;
     StartLine = line;
 }
Example #5
0
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            if (typename == "*")
                throw new ParserException("Incorrect query format. \'*\' is not supported.");

            if (queryContext.IndexManager == null)
                throw new TypeIndexNotDefined("Index is not defined for '" + typename.ToString() + "'");

            queryContext.TypeName = typename;

            if (queryContext.Index == null) //try to get virtual index
            {
                //in case of DisableException is true, exception will not be thrown, and return new attribute index.
                if (QueryIndexManager.DisableException)
                {
                    queryContext.Index = new AttributeIndex(null, queryContext.Cache.Context.CacheRoot.Name, null);
                    return;
                }

                throw new TypeIndexNotDefined("Index is not defined for '" + typename.ToString() + "'");
            }
            else
            {
                
                //populate the tree for normal queries...
                if (nextPredicate == null && queryContext.PopulateTree)
                {
                    queryContext.Tree.Populate(queryContext.Index.GetEnumerator(typename));
                }
                else
                {
                    nextPredicate.Execute(queryContext, null);
                }
            }
        }
Example #6
0
        public string Build(string className, QueryContext[] contexts)
        {
            //_stages = stages;
            _contexts = contexts;
            _appClassName = className;

            //BuildInputOutputValueTypes();
            BuildRewrittenTypes();

            BuildHeader();

            _builder.AppendLine("public class " + _appClassName + " : ServiceMesh");
            _builder.BeginBlock();

            //BuildConstructor();
            BuildServiceClients();
            BuildServiceCalls();
            foreach (var c in contexts)
                BuildQuery(c);

            _builder.EndBlock();

            BuildFooter();
            return _builder.ToString();
        }
Example #7
0
 public override Resultset Get(QueryContext queryContext, object[] parameters)
 {
     DataTable dt = RowType.CreateSchemaTable();
     DataRow r = dt.NewRow();
     r["ColumnName"] = "Stream";
     r["ColumnOrdinal"] = 0;
     r["DataType"] = typeof(System.Object);
     dt.Rows.Add(r);
     EnumeratorProcessingContext context = null;
     if (FileName.IndexOfAny(new char[] { '?', '*' }) != -1)
         context = new EnumeratorProcessingContext(null);
     Resultset rs = new Resultset(new RowType(dt), context);
     if (context == null)
     {
         Stream stm = new FileStream(FileName, FileMode.Open, FileAccess.Read);
         Row row = rs.NewRow();
         row.SetObject(0, stm);
         rs.Enqueue(row);
     }
     else
     {
         MultiFile = true;
         context.Iterator = SearchLoop(queryContext, rs);
     }
     return rs;
 }
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            bool sortAscending = true;
            bool normalizePredicates = true;

            if (Inverse)
                sortAscending = false;

            SortedList list = new SortedList(new QueryResultComparer(sortAscending));

            for (int i = 0; i < members.Count; i++)
            {
                Predicate predicate = (Predicate)members[i];
                bool isOfTypePredicate = predicate is IsOfTypePredicate;

                if (isOfTypePredicate)
                {
                    predicate.Execute(queryContext, (Predicate)members[++i]);
                    normalizePredicates = false;
                }
                else
                {
                    predicate.ExecuteInternal(queryContext, ref list);
                }
            }

            if (normalizePredicates)
            {
                if (Inverse)
                    queryContext.Tree.RightList = GetUnion(list);
                else
                    queryContext.Tree.RightList = GetIntersection(list);
            }
        }
Example #9
0
        public override Resultset Get(QueryContext queryContext, object[] parameters)
        {
            Resultset rs1 = null;
            Resultset rs2 = null;

            Iterator.Invoke(new Action[] {
                () => rs1 = ChildNodes[0].Get(queryContext, parameters),
                () => rs2 = ChildNodes[1].Get(queryContext, parameters)
            });

            DataTable dt1 = rs1.RowType.GetSchemaTable();
            DataTable dt2 = rs2.RowType.GetSchemaTable();

            foreach (DataRow r2 in dt2.Select())
            {
                DataRow r1 = dt1.NewRow();
                r1.ItemArray = r2.ItemArray;
                dt1.Rows.Add(r1);
            }

            EnumeratorProcessingContext context = new EnumeratorProcessingContext(new Resultset[] { rs1, rs2 });
            Resultset rs = new Resultset(new RowType(dt1), context);
            context.Iterator = DataIterator(rs, rs1, rs2);
            return rs;
        }
Example #10
0
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            if(ChildPredicate!=null)
                ChildPredicate.Execute(queryContext, nextPredicate);

            queryContext.Tree.Reduce();
            CacheEntry entry = null;

            decimal sum = 0;

            if (queryContext.Tree.LeftList.Count > 0)
            {
                foreach (string key in queryContext.Tree.LeftList)
                {
                    object attribValue = queryContext.Index.GetAttributeValue(key, AttributeName);
                    if (attribValue != null)
                    {
                        Type type = attribValue.GetType();
                        if ((type == typeof(bool)) || (type == typeof(DateTime)) || (type == typeof(string)) || (type == typeof(char)))
                            throw new Exception("SUM can only be applied to integral data types.");

                        sum += Convert.ToDecimal(attribValue);
                    }
                }

                base.SetResult(queryContext, AggregateFunctionType.SUM, Decimal.Round(sum, 4));
            }
            else
            {
                base.SetResult(queryContext, AggregateFunctionType.SUM, null);
            }
        }
 public static PlusAssignmentOperator CreateWithContext(QueryContext context)
 {
     return new PlusAssignmentOperator
     {
         Query = context
     };
 }
 /// <summary>
 /// Builds the ExpressionQuery:
 /// - parses Expressions and builds row creator
 /// - checks names unicity
 /// </summary>
 /// <param name="expressions"></param>
 /// <param name="queryContext"></param>
 /// <returns></returns>
 protected virtual ExpressionQuery BuildExpressionQuery(ExpressionChain expressions, QueryContext queryContext)
 {
     var builderContext = new BuilderContext(queryContext);
     BuildExpressionQuery(expressions, builderContext);
     CheckTablesAlias(builderContext);
     CheckParametersAlias(builderContext);
     return builderContext.ExpressionQuery;
 }
 internal void SetResult(QueryContext queryContext, AggregateFunctionType functionType, object result)
 {
     QueryResultSet resultSet = new QueryResultSet();
     resultSet.Type = QueryType.AggregateFunction;
     resultSet.AggregateFunctionType = functionType;
     resultSet.AggregateFunctionResult = new DictionaryEntry(functionType, result);
     queryContext.ResultSet = resultSet;
 }
Example #14
0
        /// <summary>
        /// execute to process the query with query context, and save the query at context.Query
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IContext context)
        {
            var queryContext = context as QueryContext;

            if (queryContext == null || queryContext.Querys == null)
                return;

            var query = new BooleanQuery();

            foreach (var q in queryContext.Querys)  // process all the queries
            {
                if (q == null)
                    continue;

                queryContext.CurrentQuery = q;
                Lucene.Net.Search.Query curQuery = null;

                // recursive process the sub query
                if (queryContext.CurrentQuery.Type == QueryType.Operation)
                {
                    var subContext = new QueryContext
                    {
                        Querys = q.RelationQuerys,
                    };

                    this.Execute(subContext);
                    curQuery = subContext.Query as Lucene.Net.Search.Query;
                }
                else  // process cur query
                {
                    // get the query attr for build opposite query
                    var attr = UtilityLib.Reflection.Attribute.GetAttributes<Common.Attributes.BaseAttribute>((q as QueryNode).FieldValue).FirstOrDefault();
                    if (attr == null)
                    {
                        throw new NotImplementedException("field value has no attr for query");
                    }

                    attr.Execute(queryContext);

                    if (queryContext.CurrentQuery.Type == QueryType.QueryField) // 其他的 Query Type 会将检索表达式放到对应的上下文字段
                    {
                        curQuery = queryContext.CurrentQuery.Query as Lucene.Net.Search.Query;
                    }
                }

                // if curQuery if not null, add it to query with logic
                if (curQuery != null)
                {
                    query = this.QueryOperator(
                            queryContext.CurrentQuery.Logic,
                            curQuery,
                            query);
                }
            }

            // save the final query
            queryContext.Query = query;
        }
Example #15
0
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            if(ChildPredicate!=null)
                ChildPredicate.Execute(queryContext, nextPredicate);

            queryContext.Tree.Reduce();
            decimal count = queryContext.Tree.LeftList.Count;
            base.SetResult(queryContext, AggregateFunctionType.COUNT, count);
        }
Example #16
0
        internal virtual ArrayList ReEvaluate(AttributeIndex index, LocalCacheBase cache, IDictionary attributeValues, string cacheContext)
        {
            QueryContext context = new QueryContext(cache);
            context.AttributeValues = attributeValues;
            context.Index = index;
            context.CacheContext = cacheContext;    

            Execute(context, null);

            context.Tree.Reduce();
            return context.Tree.LeftList;
        }
Example #17
0
 public override Resultset Get(QueryContext queryContext, object[] parameters)
 {
     DataTable dt = RowType.CreateSchemaTable();
     DataRow r = dt.NewRow();
     r["ColumnName"] = "dummy";
     r["ColumnOrdinal"] = 0;
     r["DataType"] = typeof(System.String);
     r["ColumnSize"] = 1;
     dt.Rows.Add(r);
     Resultset rs = new Resultset(new RowType(dt), null);
     Row row = rs.NewRow();
     row.SetString(0, "X");
     rs.Enqueue(row);
     return rs;
 }
Example #18
0
 protected QueryParts(
     IServiceProvider locator,
     QueryContext context,
     IPostgresConverterFactory converterFactory,
     IEnumerable<IQuerySimplification> simplifications,
     IEnumerable<IExpressionMatcher> expressionMatchers,
     IEnumerable<IMemberMatcher> memberMatchers,
     IEnumerable<IProjectionMatcher> projectionMatchers)
 {
     this.Locator = locator;
     this.ConverterFactory = converterFactory;
     this.Simplifications = new List<IQuerySimplification>(simplifications);
     this.ExpressionMatchers = expressionMatchers;
     this.MemberMatchers = memberMatchers;
     this.ProjectionMatchers = projectionMatchers;
     this.Context = context;
 }
Example #19
0
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            if(ChildPredicate!=null)
                ChildPredicate.Execute(queryContext, nextPredicate);

            queryContext.Tree.Reduce();
            CacheEntry entry = null;

            IComparable max = null;
            bool initialized = false;
            Type type = null;
            foreach (string key in queryContext.Tree.LeftList)
            {
                CacheEntry cacheentry = queryContext.Cache.GetEntryInternal(key, false);
                IComparable current = (IComparable)queryContext.Index.GetAttributeValue(key, AttributeName, cacheentry.IndexInfo);

                if (current != null)
                {
                    type = current.GetType();
                    if (type == typeof(bool))
                        throw new Exception("MAX cannot be applied to Boolean data type.");

                    if (!initialized)
                    {
                        max = current;
                        initialized = true;
                    }

                    if (current.CompareTo(max) > 0)
                        max = current;
                }
            }
            if (type != null)
            {

                if ((type != typeof(DateTime)) && (type != typeof(string)) && (type != typeof(char)))
                {
                    if (max != null)
                    {
                        base.SetResult(queryContext, AggregateFunctionType.MAX, Convert.ToDecimal(max));
                        return;
                    }
                }
            }
            base.SetResult(queryContext, AggregateFunctionType.MAX, max);
        }
Example #20
0
        public override Resultset Get(QueryContext queryContext, object[] parameters)
        {
            if (ChildNodes.Count != 1)
                throw new InvalidOperationException();

            Resultset source = ChildNodes[0].Get(queryContext, parameters);

            DataTable dt = RowType.CreateSchemaTable();
            DataRow r = dt.NewRow();
            r["ColumnName"] = _tableName;
            r["ColumnOrdinal"] = 0; 
            r["DataType"] = typeof(Row);
            r["NestedType"] = source.RowType;
            dt.Rows.Add(r);

            CollectorContext context = new CollectorContext(this, source, parameters);
            return new Resultset(new RowType(dt), context);
        }
 protected IList<ISpanningMember> GetMembers(string mdx)
 {
     QueryBuilder qry = new QueryBuilder();
     qry.AddAxis(new IQueryAxisItem[] {
         new QueryBuilderLiteral(mdx)
     });
     qry.Warehouse = "[Epic Warehouse]";
     QueryContext ctx = new QueryContext();
     ICellDataSource eth = qry.ExecuteDataSource(ctx);
     IList<ISpanningMember> members = new List<ISpanningMember>();
     foreach (var row in eth.Columns)
     {
         if (row.Members.Count > 0)
         {
             members.Add(row.Members[0]);
         }
     }
     return members;
 }
		public QueryContext CreateQueryContext()
		{
			using (OpenFileDialog dlg = new OpenFileDialog())
			{
				dlg.Filter = "DataSet Files (*.xml)|*.xml|All Files (*.*)|*.*";

				if (dlg.ShowDialog() != DialogResult.OK)
					return null;

				DataSet dataSet = new DataSet();
				dataSet.ReadXml(dlg.FileName);

				Query query = new Query();
				query.DataContext.AddTablesAndRelations(dataSet);

				QueryContext queryContext = new QueryContext(query, dataSet.DataSetName);
				return queryContext;
			}
		}
        /// <summary>
        /// See attribute-level indexes can't be used in this predicate.
        /// </summary>
        /// <param name="queryContext"></param>
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            ArrayList keyList = null;
            pattern = (string)generator.Evaluate(((MemberFunction)functor).MemberName, queryContext.AttributeValues);
            pattern = pattern.Trim('\'');

            AttributeIndex index = queryContext.Index;
            IIndexStore store = ((MemberFunction)functor).GetStore(index);

            if (store != null)
            {
                if (Inverse)
                    keyList = store.GetData(pattern, ComparisonType.NOT_LIKE);
                else
                    keyList = store.GetData(pattern, ComparisonType.LIKE);

                if (keyList != null && keyList.Count > 0)
                {
                    IEnumerator keyListEnum = keyList.GetEnumerator();

                    if (queryContext.PopulateTree)
                    {
                        queryContext.Tree.RightList = keyList;

                        queryContext.PopulateTree = false;
                    }
                    else
                    {
                        while (keyListEnum.MoveNext())
                        {
                            if (queryContext.Tree.LeftList.Contains(keyListEnum.Current))
                                queryContext.Tree.Shift(keyListEnum.Current);
                        }
                    }
                }
            }
            else
            {
                throw new AttributeIndexNotDefined("Index is not defined for attribute '" + ((MemberFunction)functor).MemberName + "'");
            }
        }
Example #24
0
 protected QueryParts(
     IServiceLocator locator,
     string contextName,
     IOracleConverterFactory factory,
     ParameterAggregator parameters,
     QueryContext context,
     IEnumerable<IQuerySimplification> simplifications,
     IEnumerable<IExpressionMatcher> expressionMatchers,
     IEnumerable<IMemberMatcher> memberMatchers,
     IEnumerable<IProjectionMatcher> projectionMatchers)
 {
     this.Locator = locator;
     this.ConverterFactory = factory;
     this.Parameters = parameters;
     this.Context = context;
     this.Simplifications = new List<IQuerySimplification>(simplifications);
     this.ExpressionMatchers = expressionMatchers;
     this.MemberMatchers = memberMatchers;
     this.ProjectionMatchers = projectionMatchers;
     this.ContextName = contextName;
 }
        internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list)
        {
            AttributeIndex index = queryContext.Index;
            IIndexStore store = ((MemberFunction)functor).GetStore(index);

            if (store != null)
            {
                ArrayList keyList = null;
                if (Inverse)
                    keyList = store.GetData(generator.Evaluate(((MemberFunction)functor).MemberName, queryContext.AttributeValues), ComparisonType.GREATER_THAN_EQUALS);
                else
                    keyList = store.GetData(generator.Evaluate(((MemberFunction)functor).MemberName, queryContext.AttributeValues), ComparisonType.LESS_THAN);

                if (keyList != null)
                    list.Add(keyList.Count, keyList);
            }
            else
            {
                throw new AttributeIndexNotDefined("Index is not defined for attribute '" + ((MemberFunction)functor).MemberName + "'");
            }
        }
Example #26
0
 protected IEnumerator<Row> SearchLoop(QueryContext queryContext, Resultset rs)
 {
     bool found = false;
     string[] pathset = queryContext.DatabaseDictionary.SearchPath.Split(new char[] { ';' });
     foreach (string baseDir in pathset)
     {
         string fileName = Path.Combine(baseDir, FileName);
         string filePath = Path.GetDirectoryName(fileName);
         DirectoryInfo di = new DirectoryInfo(filePath);
         foreach (FileInfo fi in di.GetFiles(Path.GetFileName(FileName)))
         {
             Stream stm = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
             Row row = rs.NewRow();
             row.SetObject(0, stm);
             found = true;
             yield return row;
         }
     }
     if (!found)
         throw new ESQLException(Properties.Resources.NoOneFileWasFound, FileName);
 }
Example #27
0
        internal override void Execute(QueryContext queryContext, Predicate nextPredicate)
        {
            if(ChildPredicate!=null)
                ChildPredicate.Execute(queryContext, nextPredicate);

            queryContext.Tree.Reduce();
            CacheEntry entry = null;

            decimal sum = 0;

            if (queryContext.Tree.LeftList.Count > 0)
            {
                foreach (string key in queryContext.Tree.LeftList)
                {
                    CacheEntry cacheentry = queryContext.Cache.GetEntryInternal(key, false);
                    object attribValue = queryContext.Index.GetAttributeValue(key, AttributeName, cacheentry.IndexInfo);

                    if (attribValue != null)
                    {
                        Type type = attribValue.GetType();
                        if ((type == typeof(bool)) || (type == typeof(DateTime)) || (type == typeof(string)) || (type == typeof(char)))
                            throw new Exception("AVG can only be applied to integral data types.");

                        sum += Convert.ToDecimal(attribValue);
                    }

                }

                AverageResult avgResult = new AverageResult();
                avgResult.Sum = sum;
                avgResult.Count = queryContext.Tree.LeftList.Count;
                //put the count and the sum
                base.SetResult(queryContext, AggregateFunctionType.AVG, avgResult);
            }
            else
            {
                base.SetResult(queryContext, AggregateFunctionType.AVG, null);
            }
        }
Example #28
0
        internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list)
        {
            bool sortAscending = true;
            ArrayList keys = new ArrayList();

            if (Inverse)
                sortAscending = false;

            SortedList tmpList = new SortedList(new QueryResultComparer(sortAscending));

            for (int i = 0; i < members.Count; i++)
            {
                Predicate predicate = (Predicate)members[i];
                predicate.ExecuteInternal(queryContext, ref tmpList);
            }

            if (Inverse)
                keys = GetUnion(tmpList);
            else
                keys = GetIntersection(tmpList);

            if (keys != null)
                list.Add(keys.Count, keys);
        }
        internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list)
        {
            ArrayList keyList = null;
            pattern = (string)generator.Evaluate(((MemberFunction)functor).MemberName, queryContext.AttributeValues);
            pattern = pattern.Trim('\'');

            AttributeIndex index = queryContext.Index;
            IIndexStore store = ((MemberFunction)functor).GetStore(index);
            if (store != null)
            {
                if (Inverse)
                    keyList = store.GetData(pattern, ComparisonType.NOT_LIKE);
                else
                    keyList = store.GetData(pattern, ComparisonType.LIKE);


                if (keyList != null)
                    list.Add(keyList.Count, keyList);
            }
            else
            {
                throw new AttributeIndexNotDefined("Index is not defined for attribute '" + ((MemberFunction)functor).MemberName + "'");
            }
        }
Example #30
0
 internal override void ExecuteInternal(QueryContext queryContext, CollectionOperation mergeType)
 {
 }
Example #31
0
        /// <summary>
        /// Pagings the select asynchronous.
        /// </summary>
        /// <param name="connectionInfo">The connection information.</param>
        /// <param name="filter">The filter.</param>
        /// <returns></returns>
        /// <exception cref="SQLException">SQL Data Access Error;There was an error with the Paging Select SQL Statement for the Application Log Table.</exception>
        public async Task <PagedResult <TrafficLogRequest> > PagingSelectAsync(IConnectionInfo connectionInfo, TrafficLogRequest filter)
        {
            PagedResult <TrafficLogRequest> pagedResult = new PagedResult <TrafficLogRequest>()
            {
                Results = new List <TrafficLogRequest>()
            };
            SqlDataReader reader = null;

            try
            {
                PopulateConnectionInfo(connectionInfo);

                SqlConnection connection = new SqlConnection(connectionInfo.ConnectionString);

                QueryContext queryContext = filter.QueryContext;

                if (queryContext == null)
                {
                    queryContext = new QueryContext();
                }

                pagedResult.PageNumber = queryContext.PageNumber;
                pagedResult.PageSize   = queryContext.PageSize;

                using (connection)
                {
                    List <SqlParameter> sqlParameters = new List <SqlParameter>();

                    string selectQuery = String.Format("SELECT {0} FROM {1} WITH (NOLOCK)", String.Join(", ", EntityHelper.Current.GetAllColumns(filter)), EntityHelper.Current.GetTableName(filter));

                    int skipNo = (queryContext.PageNumber - 1) * queryContext.PageSize;

                    IEnumerable <string> modifiedColumns = filter.GetModifiedColumns();

                    string whereFilter = String.Empty;

                    if (modifiedColumns.Count() > 0)
                    {
                        whereFilter = String.Format(" WHERE {0}", GetEntityFilter <TrafficLogRequest>(filter, modifiedColumns, sqlParameters, connectionInfo));

                        selectQuery += whereFilter;
                    }

                    if (String.IsNullOrEmpty(queryContext.SortBy))
                    {
                        queryContext.SortBy        = EntityHelper.Current.GetPrimaryKeyColumn(filter);
                        queryContext.SortDirection = SortOrder.Ascending;
                    }

                    selectQuery += String.Format(" ORDER BY {0} {1}", queryContext.SortBy, SQLHelper.Current.GetSortDirection(queryContext.SortDirection));

                    selectQuery += String.Format(" OFFSET {0} ROWS", skipNo);

                    selectQuery += String.Format(" FETCH NEXT {0} ROWS ONLY", queryContext.PageSize);

                    SqlCommand command = new SqlCommand(selectQuery, connection);

                    await connection.OpenAsync();

                    command.Parameters.AddRange(sqlParameters.ToArray());

                    reader = await command.ExecuteReaderAsync();

                    if (reader.HasRows)
                    {
                        while (await reader.ReadAsync())
                        {
                            pagedResult.Results.Add(EntityHelper.Current.PopulateFromDataReader <TrafficLogRequest>(reader, connectionInfo));
                        }
                    }

                    command.Parameters.Clear();
                    reader.Close();

                    string selectCountQuery = String.Format("SELECT COUNT({0}) FROM {1}", EntityHelper.Current.GetPrimaryKeyColumn(filter), EntityHelper.Current.GetTableName(filter));

                    selectCountQuery += whereFilter;

                    SqlCommand selectCountCommand = new SqlCommand(selectCountQuery, connection);

                    selectCountCommand.Parameters.AddRange(sqlParameters.ToArray());

                    reader = await selectCountCommand.ExecuteReaderAsync();

                    if (reader.HasRows)
                    {
                        while (await reader.ReadAsync())
                        {
                            pagedResult.TotalResults = (int)reader.GetValue(0);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new SQLException("SQL Data Access Error", "There was an error with the Paging Select SQL Statement for the Traffic Log Request Table.", e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(pagedResult);
        }
Example #32
0
        public async Task ExecuteAsync(QueryContext context)
        {
            _repo.Apply(context.Descriptor, context.Params);

            if (!string.IsNullOrEmpty(context.Params.Id))
            {
                object[] id;
                try
                {
                    id = _repo.ParseId(context.Params.Id);
                }
                catch (Exception ex)
                {
                    throw new QueryException("id format incorrect", QueryErrorCode.BadRequest, ex);
                }

                var found = await _repo.FindAsync(id, context.CancellationToken);

                if (found == null)
                {
                    context.Succeed(null);
                    return;
                }

                if (context.Descriptor.OnlyOwnerCanRead)
                {
                    var authContext = new AuthorizationContext <T>(context);
                    var authorized  = await authContext.AuthorizeAsync(found, context.Descriptor.DeletePolicy);

                    if (authorized)
                    {
                        context.Succeed(found);
                    }
                    else
                    {
                        context.Fail(null, QueryErrorCode.Unauthorized, "unauthorized");
                    }
                }
                else
                {
                    context.Succeed(found);
                }
            }
            else
            {
                var condition = new Condition();
                Utils.Map(context.Descriptor, context.Params, condition);
                var found = await _repo.FindAsync(condition, context.CancellationToken);

                if (context.Descriptor.OnlyOwnerCanRead)
                {
                    var authContext = new AuthorizationContext <T>(context);
                    var authorized  = await authContext.AuthorizeAsync(found, context.Descriptor.DeletePolicy);

                    if (authorized)
                    {
                        context.Succeed(found);
                    }
                    else
                    {
                        context.Fail(null, QueryErrorCode.Unauthorized, "unauthorized");
                    }
                }
                else
                {
                    context.Succeed(found);
                }
            }
        }
Example #33
0
 private static IEnumerable <IValueReader> ProjectionQuery(QueryContext queryContext, IEntityType entityType)
 {
     return(((InMemoryQueryContext)queryContext).Database.GetTable(entityType)
            .Select(t => new ObjectArrayValueReader(t)));
 }
Example #34
0
 public ExceptionInterceptor(
     IEnumerable <T> innerEnumerable, Type contextType, IDiagnosticsLogger <DbLoggerCategory.Query> logger, QueryContext queryContext)
 {
     _innerEnumerable = innerEnumerable;
     _contextType     = contextType;
     _logger          = logger;
     _queryContext    = queryContext;
 }
Example #35
0
 protected PreciseQuery(QueryContext ctx)
 {
     _ctx = ctx;
     Reset();
 }
        public async Task <IActionResult> GetAllAsync([FromQuery, Optional] string name, [FromQuery] QueryContext context, CancellationToken cancellationToken)
        {
            CollectionWrapper <CocktailModel> result;

            if (string.IsNullOrWhiteSpace(name))
            {
                result = await _service.GetAllAsync(context, cancellationToken);
            }
            else
            {
                result = await _service.GetByCocktailNameAsync(name, context, cancellationToken);
            }

            return(Ok(result));
        }
Example #37
0
 /// <summary>
 ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
 ///     directly from your code. This API may change or be removed in future releases.
 /// </summary>
 public virtual ValueBuffer Shape(QueryContext queryContext, in ValueBuffer valueBuffer)
Example #38
0
 /// <summary>
 /// Forgets all uncommitted updates. Used from the Query class
 /// when updates are not allowed (directly added updates are always
 /// immediatly applied, so it is impossible to forget them).
 /// </summary>
 internal static void Forget()
 {
     _queryContext = GetQueryContext();
 }
Example #39
0
 private static IEnumerable <JObject> _Query(
     CosmosClient cosmosClient,
     QueryContext queryContext,
     string collectionId,
     SelectExpression selectExpression)
 => new DocumentEnumerable(cosmosClient, queryContext, collectionId, selectExpression);
Example #40
0
        /// <summary>
        /// Maps data from the CMS value to the .Net property value
        /// </summary>
        /// <param name="mappingContext">The mapping context.</param>
        /// <returns>System.Object.</returns>
        public override object MapToProperty(AbstractDataMappingContext mappingContext)
        {
            var scConfig  = Configuration as SitecoreQueryConfiguration;
            var scContext = mappingContext as SitecoreDataMappingContext;

            string query = ParseQuery(scConfig.Query, scContext.Item);

            if (scConfig.PropertyInfo.PropertyType.IsGenericType)
            {
                Type outerType = Utilities.GetGenericOuter(scConfig.PropertyInfo.PropertyType);

                if (typeof(IEnumerable <>) == outerType)
                {
                    Type genericType = Mapper.Utilities.GetGenericArgument(scConfig.PropertyInfo.PropertyType);

                    Func <IEnumerable <Item> > getItems = null;
                    if (scConfig.IsRelative)
                    {
                        getItems = new Func <IEnumerable <Item> >(() =>
                        {
                            try
                            {
                                return(Utilities.GetLanguageItems(scContext.Item.Axes.SelectItems(query),
                                                                  scContext.Item.Language));
                            }
                            catch (Exception ex)
                            {
                                throw new MapperException("Failed to perform query {0}".Formatted(query), ex);
                            }
                        });
                    }
                    else
                    {
                        getItems = new Func <IEnumerable <Item> >(() =>
                        {
                            if (scConfig.UseQueryContext)
                            {
                                Query conQuery            = new Query(query);
                                QueryContext queryContext = new QueryContext(scContext.Item.Database.DataManager);

                                object obj = conQuery.Execute(queryContext);
                                QueryContext[] contextArray = obj as QueryContext[];
                                QueryContext context        = obj as QueryContext;

                                if (contextArray == null)
                                {
                                    contextArray = new QueryContext[] { context }
                                }
                                ;

                                return(Utilities.GetLanguageItems(contextArray.Select(x => scContext.Item.Database.GetItem(x.ID)), scContext.Item.Language));
                            }
                            else
                            {
                                return(Utilities.GetLanguageItems(scContext.Item.Database.SelectItems(query), scContext.Item.Language));
                            }
                        });
                    }

                    var result = Utilities.CreateGenericType(typeof(LazyItemEnumerable <>), new [] { genericType }, getItems, scConfig.IsLazy,
                                                             scConfig.InferType, scContext.Service);
                    return(result);

                    //return scContext.Service.CreateTypes(scConfig.IsLazy, scConfig.InferType, genericType, getItems);
                }
                else
                {
                    throw new NotSupportedException("Generic type not supported {0}. Must be IEnumerable<>.".Formatted(outerType.FullName));
                }
            }
            else
            {
                Item result = null;
                if (scConfig.IsRelative)
                {
                    result = Utilities.GetLanguageItem(scContext.Item.Axes.SelectSingleItem(query), scContext.Item.Language);
                }
                else
                {
                    result = Utilities.GetLanguageItem(scContext.Item.Database.SelectSingleItem(query), scContext.Item.Language);
                }
                return(scContext.Service.CreateType(scConfig.PropertyInfo.PropertyType, result, scConfig.IsLazy, scConfig.InferType, null));
            }
        }
#pragma warning disable IDE0052 // Remove unread private members
        private static T GetParameterValue <T>(QueryContext queryContext, string parameterName)
#pragma warning restore IDE0052 // Remove unread private members
        => (T)queryContext.ParameterValues[parameterName];
Example #42
0
        public override object Evaluate([NotNull] Query query, [NotNull] QueryContext contextNode)
        {
            Assert.ArgumentNotNull(query, nameof(query));
            Assert.ArgumentNotNull(contextNode, nameof(contextNode));

            TemplateItem templateItem = null;
            Item         path         = null;
            string       itemName     = null;

            for (var index = Columns.Count - 1; index >= 0; index--)
            {
                var column = Columns[index];
                var value  = Values[index];

                if (column == "@templateitem")
                {
                    var templateContextNode = new QueryContext(contextNode.Queryable, contextNode.GetQueryContextItem().Database.GetRootItem().ID);

                    templateItem = query.GetItem(templateContextNode, value);

                    if (templateItem == null)
                    {
                        throw new QueryException("@@templateitem column does not evaluate to a single item");
                    }

                    Columns.Remove(column);
                    Values.Remove(value);

                    continue;
                }

                if (column == "@itemname")
                {
                    itemName = query.GetString(contextNode, value);
                    if (itemName == null)
                    {
                        throw new QueryException("@@itemname column does not evaluate to a string");
                    }

                    Columns.Remove(column);
                    Values.Remove(value);

                    continue;
                }

                if (column == "@path")
                {
                    var pathContextNode = new QueryContext(contextNode.Queryable, contextNode.GetQueryContextItem().Database.GetRootItem().ID);

                    path = query.GetItem(pathContextNode, value);

                    if (path == null)
                    {
                        throw new QueryException("@@path column does not evaluate to a single item");
                    }

                    Columns.Remove(column);
                    Values.Remove(value);
                }
            }

            if (templateItem == null)
            {
                throw new QueryException("@@templateitem column missing");
            }

            if (itemName == null)
            {
                throw new QueryException("@@itemname column missing");
            }

            if (path == null)
            {
                throw new QueryException("@@path column missing");
            }

            InsertItem(query, templateItem, itemName, path);

            return(query.FormatItemsAffected(1));
        }
Example #43
0
    public Source(QueryContext queryContext)
    {
        Expression = Expression.Constant(this);

        QueryContext = queryContext;
    }
 public override TEntity Shape(QueryContext queryContext, ValueBuffer valueBuffer)
 => base.Shape(queryContext, valueBuffer.WithOffset(ValueBufferOffset));
Example #45
0
        /// <summary>
        /// Build a result package from the TrackerResults
        /// </summary>
        /// <param name="context"></param>
        public void BuildPackage(QueryContext context)
        {
            // Clear up the result

            context.Results = new Package
            {
                Claims = new List <Claim>(context.TrackerResults.Count)
            };

            foreach (var tracker in context.TrackerResults.Values)
            {
                foreach (var ts in tracker.Subjects.Values)
                {
                    if (ts.Claims == null || ts.Claims.Count() == 0)
                    {
                        var claim = new Claim
                        {
                            Issuer = new IssuerIdentity {
                                Id = tracker.Issuer.Id
                            },
                            Subject = new SubjectIdentity {
                                Id = ts.TargetIssuer.Id
                            }
                        };

                        claim.Type  = PackageBuilder.BINARY_CLAIM_DTP1;
                        claim.Value = PackageBuilder.CreateBinaryTrustAttributes(true);

                        context.Results.Claims.Add(claim);
                    }
                    else
                    {
                        foreach (var claimEntry in ts.Claims)
                        {
                            var claim = new Claim
                            {
                                Issuer = new IssuerIdentity {
                                    Id = tracker.Issuer.Id
                                },
                                Subject = new SubjectIdentity {
                                    Id = ts.TargetIssuer.Id
                                }
                            };

                            var claimIndex   = claimEntry.Value;
                            var trackerClaim = Graph.Claims[claimIndex];

                            if (Graph.ClaimType.TryGetValue(trackerClaim.Type, out string type))
                            {
                                claim.Type = type;
                            }

                            if (Graph.ClaimAttributes.TryGetValue(trackerClaim.Attributes, out string attributes))
                            {
                                claim.Value = attributes;
                            }

                            if (Graph.Scopes.TryGetValue(trackerClaim.Scope, out string scope))
                            {
                                claim.Scope = scope;
                            }

                            claim.Expire   = 0;
                            claim.Activate = 0;

                            context.Results.Claims.Add(claim);
                        }
                    }
                }
            }
        }
Example #46
0
 public static void Execute(ActionExecutingContext context, IDictionary <string, StringValues> qs,
                            QueryContext qc)
 {
     Execute <RestFieldsFilter>(context, filter => filter.Options.FieldsOperator, c => c.Fields, qs, qc);
 }
            private static void IncludeCollection <TEntity, TIncludedEntity>(
                QueryContext queryContext,
                DbDataReader dbDataReader,
                TEntity entity,
                Func <QueryContext, DbDataReader, object[]> outerKeySelector,
                Func <QueryContext, DbDataReader, object[]> innerKeySelector,
                Func <QueryContext, DbDataReader, ResultCoordinator, TIncludedEntity> innerShaper,
                INavigation navigation,
                INavigation inverseNavigation,
                Action <TEntity, TIncludedEntity> fixup,
                bool trackingQuery,
                ResultCoordinator resultCoordinator)
            {
                if (entity is null)
                {
                    return;
                }

                if (trackingQuery)
                {
                    queryContext.StateManager.TryGetEntry(entity).SetIsLoaded(navigation);
                }
                else
                {
                    SetIsLoadedNoTracking(entity, navigation);
                }

                var innerKey      = innerKeySelector(queryContext, dbDataReader);
                var outerKey      = outerKeySelector(queryContext, dbDataReader);
                var relatedEntity = innerShaper(queryContext, dbDataReader, resultCoordinator);

                if (ReferenceEquals(relatedEntity, null))
                {
                    navigation.GetCollectionAccessor().GetOrCreate(entity);
                    return;
                }

                if (!trackingQuery)
                {
                    fixup(entity, relatedEntity);
                    if (inverseNavigation != null && !inverseNavigation.IsCollection())
                    {
                        SetIsLoadedNoTracking(relatedEntity, inverseNavigation);
                    }
                }

                var hasNext = resultCoordinator.HasNext ?? dbDataReader.Read();

                while (hasNext)
                {
                    resultCoordinator.HasNext = null;
                    var currentOuterKey = outerKeySelector(queryContext, dbDataReader);
                    if (!StructuralComparisons.StructuralEqualityComparer.Equals(outerKey, currentOuterKey))
                    {
                        resultCoordinator.HasNext = true;
                        break;
                    }

                    var currentInnerKey = innerKeySelector(queryContext, dbDataReader);
                    if (StructuralComparisons.StructuralEqualityComparer.Equals(innerKey, currentInnerKey))
                    {
                        continue;
                    }

                    relatedEntity = innerShaper(queryContext, dbDataReader, resultCoordinator);
                    if (!trackingQuery)
                    {
                        fixup(entity, relatedEntity);
                        if (inverseNavigation != null && !inverseNavigation.IsCollection())
                        {
                            SetIsLoadedNoTracking(relatedEntity, inverseNavigation);
                        }
                    }

                    hasNext = resultCoordinator.HasNext ?? dbDataReader.Read();
                }

                resultCoordinator.HasNext = hasNext;
            }
Example #48
0
 /// <summary>
 /// Executa o predicado.
 /// </summary>
 /// <param name="queryContext"></param>
 /// <param name="list"></param>
 internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list)
 {
 }
Example #49
0
 public override Node VisitQueryContext(QueryContext context)
 {
     this.hasContextReference = true;
     return(this.Compose(context, this.contextComposer));
 }
Example #50
0
 private void Adapter_ErrorProcessed(Exception ex, QueryContext queryContext)
 {
 }
Example #51
0
        public bool TryMatch(Expression expression, StringBuilder queryBuilder, Action <Expression> visitExpression, QueryContext context, IPostgresConverterFactory converter)
        {
            var mce = expression as MethodCallExpression;

            if (mce == null)
            {
                return(false);
            }

            MethodCallDelegate mcd;
            var dt = mce.Method.DeclaringType;

            if (dt.IsGenericType && dt.GetGenericTypeDefinition() == typeof(HashSet <>) && SupportedMethods.TryGetValue(mce.Method.Name, out mcd))
            {
                mcd(mce, queryBuilder, visitExpression);
                return(true);
            }
            return(false);
        }
Example #52
0
        public virtual async Task <CollectionWrapper <TModel> > GetAllAsync(QueryContext context, CancellationToken cancellationToken)
        {
            var result = await Repository.GetAsync(x => IncludeFunction(x).Paginate(context, y => y.ModifiedDate), cancellationToken);

            return(WrapCollection(Mapper.Map <TModel[]>(result), context));
        }
 public override string GetPropertyName(QueryContext <IPipeline> args)
 {
     return(GetPipelineProperties.Processors);
 }
Example #54
0
        public bool TryMatch(MemberExpression expression, StringBuilder queryBuilder, Action <Expression> visitExpression, QueryContext context)
        {
            MemberCallDelegate mcd;

            if (SupportedMembers.TryGetValue(expression.Member, out mcd))
            {
                mcd(expression, queryBuilder, visitExpression);
                return(true);
            }
            return(false);
        }
Example #55
0
 public virtual Node VisitQueryContext(QueryContext context, QueryContext changes, QueryContext deletions, QueryContext insertions){
   this.UpdateSourceContext(context, changes);
   if (context == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return context;
 }
 public override async Task <TranslationsChangedEvent[]?> HandleAsync(GetLatestTranslationsQuery query, QueryContext context, CancellationToken cancellationToken)
 {
     return(await _translationsSource.GetLatestVersionAsync(cancellationToken).ConfigureAwait(false));
 }
Example #57
0
 private void Adapter_Error(Exception ex, QueryContext queryContext)
 {
     testrResult = queryContext.Query;
 }
Example #58
0
 public override bool IsCached(QueryContext context)
 {
     return(Filter?.Invoke((TQuery)context.Query) ?? true);
 }
 private static T GetParameterValue <T>(QueryContext queryContext, string parameterName)
 => (T)queryContext.ParameterValues[parameterName];
Example #60
0
 private QueryContext Context()
 {
     return(QueryContext.Create(App, User));
 }