Exemplo n.º 1
0
        public IEnumerable <object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var cursor = _this.FindAs(documentType, query);

            if (modes != QueryFlags.None)
            {
                cursor.SetFlags(modes);
            }

            if (skip > 0)
            {
                cursor.SetSkip(skip);
            }

            if (first > 0)
            {
                cursor.SetLimit(first);
            }

            if (sortBy != null)
            {
                cursor.SetSortOrder(sortBy);
            }

            if (fields != null)
            {
                cursor.SetFields(fields);
            }

            foreach (var it in cursor)
            {
                yield return(it);
            }
        }
Exemplo n.º 2
0
        private QueryFlags GetFlags(ProtocolVersion protocolVersion)
        {
            QueryFlags flags = 0;

            if (Values != null && Values.Length > 0)
            {
                flags |= QueryFlags.Values;
            }
            if (_skipMetadata)
            {
                flags |= QueryFlags.SkipMetadata;
            }
            if (PageSize != int.MaxValue && PageSize >= 0)
            {
                flags |= QueryFlags.PageSize;
            }
            if (PagingState != null)
            {
                flags |= QueryFlags.WithPagingState;
            }
            if (SerialConsistency != ConsistencyLevel.Any)
            {
                flags |= QueryFlags.WithSerialConsistency;
            }
            if (protocolVersion.SupportsTimestamp() && RawTimestamp != null)
            {
                flags |= QueryFlags.WithDefaultTimestamp;
            }
            if (ValueNames != null && ValueNames.Count > 0)
            {
                flags |= QueryFlags.WithNameForValues;
            }
            return(flags);
        }
Exemplo n.º 3
0
        public QueryOperation(
            string databaseName,
            string collectionName,
            BsonBinaryReaderSettings readerSettings,
            BsonBinaryWriterSettings writerSettings,
            int batchSize,
            IMongoFields fields,
            QueryFlags flags,
            int limit,
            BsonDocument options,
            IMongoQuery query,
            ReadPreference readPreference,
            IBsonSerializationOptions serializationOptions,
            IBsonSerializer serializer,
            int skip)
            : base(databaseName, collectionName, readerSettings, writerSettings)
        {
            _batchSize            = batchSize;
            _fields               = fields;
            _flags                = flags;
            _limit                = limit;
            _options              = options;
            _query                = query;
            _readPreference       = readPreference;
            _serializationOptions = serializationOptions;
            _serializer           = serializer;
            _skip = skip;

            // since we're going to block anyway when a tailable cursor is temporarily out of data
            // we might as well do it as efficiently as possible
            if ((_flags & QueryFlags.TailableCursor) != 0)
            {
                _flags |= QueryFlags.AwaitData;
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Sets the query flags.
 /// </summary>
 /// <param name="flags">The query flags.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor SetFlags(QueryFlags flags)
 {
     if (_isFrozen)
     {
         ThrowFrozen();
     }
     _flags = flags;
     return(this);
 }
Exemplo n.º 5
0
 public QueryCategory(
     QueryFlags flags, ITypeSymbol?itemType, NullableAnnotation itemNullability,
     ListStrategy listStrategy, ITypeSymbol listType)
 {
     Flags           = flags;
     ItemType        = itemType;
     ItemNullability = itemNullability;
     ListStrategy    = listStrategy;
     ListType        = listType;
 }
 internal MongoQueryMessage(BsonBuffer buffer, BsonBinaryWriterSettings writerSettings, string collectionFullName, QueryFlags flags, int numberToSkip, int numberToReturn, IMongoQuery query, IMongoFields fields)
     : base(MessageOpcode.Query, buffer, writerSettings)
 {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.numberToSkip = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query = query;
     this.fields = fields;
 }
Exemplo n.º 7
0
 internal MongoQueryMessage(BsonBuffer buffer, BsonBinaryWriterSettings writerSettings, string collectionFullName, QueryFlags flags, int numberToSkip, int numberToReturn, IMongoQuery query, IMongoFields fields)
     : base(MessageOpcode.Query, buffer, writerSettings)
 {
     this.collectionFullName = collectionFullName;
     this.flags          = flags;
     this.numberToSkip   = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query          = query;
     this.fields         = fields;
 }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : this(null, writerSettings, collectionFullName, flags, numberToSkip, numberToReturn, query, fields)
 {
 }
Exemplo n.º 9
0
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : this(null, writerSettings, collectionFullName, flags, numberToSkip, numberToReturn, query, fields)
 {
 }
Exemplo n.º 10
0
 /// <summary>
 /// Sets the query flags.
 /// </summary>
 /// <param name="flags">The query flags.</param>
 /// <returns>The cursor (so you can chain method calls to it).</returns>
 public virtual MongoCursor <TDocument> SetFlags(
     QueryFlags flags
     )
 {
     if (isFrozen)
     {
         ThrowFrozen();
     }
     this.flags = flags;
     return(this);
 }
 internal MongoQueryMessage(
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     object query,
     BsonDocumentWrapper fields
 )
     : this(collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null)
 {
 }
Exemplo n.º 12
0
 internal MongoQueryMessage(
     MongoServer server,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields
 ) :
     this(server, collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null) {
 }
Exemplo n.º 13
0
 internal MongoQueryMessage(
     MongoConnection connection,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields
     ) :
     this(connection, collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null)
 {
 }
Exemplo n.º 14
0
        protected override bool ParseCommand(string cmd)
        {
            if (cmd[0] == '?')
            {
                IsQueryRequest = true;
            }
            else
            {
                QueryFlags = (QueryFlags)int.Parse(cmd.Substring(2));
            }

            return(true);
        }
Exemplo n.º 15
0
        public IEnumerable <object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var iter = QueryCompiler.Query(Documents, Documents2, query, sortBy, skip, first);

            if (fields == null)
            {
                return(iter.Select(x => BsonSerializer.Deserialize(x, documentType)));
            }

            var project = FieldCompiler.GetFunction(fields);

            return(iter.Select(project).Select(x => BsonSerializer.Deserialize(x, documentType)));
        }
Exemplo n.º 16
0
 protected GremlinQueryBase(
     IImmutableStack <Step> steps,
     IGremlinQueryEnvironment environment,
     QuerySemantics semantics,
     IImmutableDictionary <StepLabel, QuerySemantics> stepLabelSemantics,
     QueryFlags flags)
 {
     Steps              = steps;
     Semantics          = semantics;
     Environment        = environment;
     Flags              = flags;
     StepLabelSemantics = stepLabelSemantics;
 }
Exemplo n.º 17
0
        public static List <MyEntity> GetAllEntitiesInBox(ref BoundingBox box, QueryFlags flags)
        {
            var result = new List <MyEntity>();

            if ((flags & QueryFlags.Waypoints) != 0)
            {
                m_waypoints.OverlapAllBoundingBox(ref box, result, 0, false);
            }
            if ((flags & QueryFlags.Others) != 0)
            {
                m_others.OverlapAllBoundingBox(ref box, result, 0, false);
            }

            return(result);
        }
Exemplo n.º 18
0
            /// <summary>
            /// Search for query in cache and of found, try to move it to better position in cache.
            /// </summary>
            public Query <T>?Find(IDataContext dataContext, Expression expr, QueryFlags flags)
            {
                QueryCacheEntry[] cache;
                int[]             indexes;
                int version;

                lock (_syncCache)
                {
                    cache   = _cache;
                    version = _version;
                    indexes = _indexes;
                }

                var allowReordering = Monitor.TryEnter(_syncPriority);

                try
                {
                    for (var i = 0; i < cache.Length; i++)
                    {
                        // if we have reordering lock, we can enumerate queries in priority order
                        var idx = allowReordering ? indexes[i] : i;

                        if (cache[idx].Compare(dataContext, expr, flags))
                        {
                            // do reorder only if it is not blocked and cache wasn't replaced by new one
                            if (i > 0 && version == _version && allowReordering)
                            {
                                var index = indexes[i];
                                indexes[i]     = indexes[i - 1];
                                indexes[i - 1] = index;
                            }

                            return(cache[idx].Query);
                        }
                    }
                }
                finally
                {
                    if (allowReordering)
                    {
                        Monitor.Exit(_syncPriority);
                    }
                }

                Interlocked.Increment(ref CacheMissCount);

                return(null);
            }
Exemplo n.º 19
0
        // this is a low level method that doesn't require a MongoServer
        // so it can be used while connecting to a MongoServer
        internal CommandResult RunCommand(
            string collectionName,
            QueryFlags queryFlags,
            CommandDocument command
            )
        {
            var commandName = command.GetElement(0).Name;

            var writerSettings = new BsonBinaryWriterSettings {
                GuidRepresentation = GuidRepresentation.Unspecified,
                MaxDocumentSize    = serverInstance.MaxDocumentSize
            };

            using (
                var message = new MongoQueryMessage(
                    writerSettings,
                    collectionName,
                    queryFlags,
                    0,   // numberToSkip
                    1,   // numberToReturn (must be 1 or -1 for commands)
                    command,
                    null // fields
                    )
                ) {
                SendMessage(message, SafeMode.False);
            }

            var readerSettings = new BsonBinaryReaderSettings {
                GuidRepresentation = GuidRepresentation.Unspecified,
                MaxDocumentSize    = serverInstance.MaxDocumentSize
            };
            var reply = ReceiveMessage <BsonDocument>(readerSettings, null);

            if (reply.NumberReturned == 0)
            {
                var message = string.Format("Command '{0}' failed. No response returned.", commandName);
                throw new MongoCommandException(message);
            }

            var commandResult = new CommandResult(command, reply.Documents[0]);

            if (!commandResult.Ok)
            {
                throw new MongoCommandException(commandResult);
            }

            return(commandResult);
        }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : base(MessageOpcode.Query, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _flags          = flags;
     _numberToSkip   = numberToSkip;
     _numberToReturn = numberToReturn;
     _query          = query;
     _fields         = fields;
 }
Exemplo n.º 21
0
 public CommandOperation(
     string databaseName,
     BsonBinaryReaderSettings readerSettings,
     BsonBinaryWriterSettings writerSettings,
     IMongoCommand command,
     QueryFlags flags,
     BsonDocument options,
     ReadPreference readPreference,
     IBsonSerializer <TCommandResult> serializer)
     : base(databaseName, "$cmd", readerSettings, writerSettings)
 {
     _command        = command;
     _flags          = flags;
     _options        = options;
     _readPreference = readPreference;
     _serializer     = serializer;
 }
 // constructors
 internal MongoQueryMessage(
     BsonBinaryWriterSettings writerSettings,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields)
     : base(MessageOpcode.Query, writerSettings)
 {
     _collectionFullName = collectionFullName;
     _flags = flags;
     _numberToSkip = numberToSkip;
     _numberToReturn = numberToReturn;
     _query = query;
     _fields = fields;
 }
 internal MongoQueryMessage(
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     object query,
     BsonDocumentWrapper fields,
     BsonBuffer buffer
 )
     : base(MessageOpcode.Query, buffer)
 {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.numberToSkip = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query = query;
     this.fields = fields;
 }
Exemplo n.º 24
0
 internal MongoQueryMessage(
     MongoServer server,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields,
     BsonBuffer buffer
 ) :
     base(server, MessageOpcode.Query, buffer) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.numberToSkip = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query = query;
     this.fields = fields;
 }
Exemplo n.º 25
0
        public QueryContext(IGraphClaimService graphService, QueryRequest query) : this()
        {
            GraphTrustService = graphService;

            SetupIssuers(query);
            SetupSubjects(query);
            SetupQueryClaim(query);
            SetupIndexs();

            if (query.Level > 0 && query.Level < MaxLevel)
            {
                MaxLevel = query.Level;
            }

            Flags = query.Flags;

            Visited = new BitArrayFast(GraphTrustService.Graph.Issuers.Count + 1024, false); // 1024 is buffer for new Issuers when searching
        }
Exemplo n.º 26
0
 internal MongoQueryMessage(
     MongoConnection connection,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields,
     BsonBuffer buffer
     ) :
     base(connection, MessageOpcode.Query, buffer)
 {
     this.collectionFullName = collectionFullName;
     this.flags          = flags;
     this.numberToSkip   = numberToSkip;
     this.numberToReturn = numberToReturn;
     this.query          = query;
     this.fields         = fields;
 }
Exemplo n.º 27
0
        // constructors
        /// <summary>
        /// Initializes a new instance of the MongoCursorEnumerator class.
        /// </summary>
        /// <param name="cursor">The cursor to be enumerated.</param>
        public MongoCursorEnumerator(MongoCursor <TDocument> cursor)
        {
            _cursor         = cursor;
            _positiveLimit  = cursor.Limit >= 0 ? cursor.Limit : -cursor.Limit;
            _readPreference = _cursor.ReadPreference;
            _queryFlags     = _cursor.Flags;

            if (_readPreference.ReadPreferenceMode != ReadPreferenceMode.Primary && _cursor.Collection.Name == "$cmd")
            {
                if (cursor.Server.ProxyType == MongoServerProxyType.ReplicaSet && !CanCommandBeSentToSecondary.Delegate(_cursor.Query.ToBsonDocument()))
                {
                    // if the command can't be sent to a secondary, then we use primary here
                    // regardless of the user's choice.
                    _readPreference = ReadPreference.Primary;
                    // remove the slaveOk bit from the flags
                    _queryFlags &= ~QueryFlags.SlaveOk;
                }
            }
        }
Exemplo n.º 28
0
        private QueryFlags GetFlags(ProtocolVersion protocolVersion, bool isPrepared)
        {
            QueryFlags flags = 0;

            if (Values != null && Values.Length > 0)
            {
                flags |= QueryFlags.Values;
            }
            if (_skipMetadata)
            {
                flags |= QueryFlags.SkipMetadata;
            }
            if (PageSize != int.MaxValue && PageSize >= 0)
            {
                flags |= QueryFlags.PageSize;
            }
            if (PagingState != null)
            {
                flags |= QueryFlags.WithPagingState;
            }
            if (SerialConsistency != ConsistencyLevel.Any)
            {
                flags |= QueryFlags.WithSerialConsistency;
            }
            if (protocolVersion.SupportsTimestamp() && RawTimestamp != null)
            {
                flags |= QueryFlags.WithDefaultTimestamp;
            }
            if (ValueNames != null && ValueNames.Count > 0)
            {
                flags |= QueryFlags.WithNameForValues;
            }

            if (!isPrepared && protocolVersion.SupportsKeyspaceInRequest() && _keyspace != null)
            {
                // Providing keyspace is only useful for QUERY requests.
                // For EXECUTE requests, the keyspace will be the one from the prepared statement.
                flags |= QueryFlags.WithKeyspace;
            }

            return(flags);
        }
Exemplo n.º 29
0
        // this is a low level method that doesn't require a MongoServer
        // so it can be used while connecting to a MongoServer
        internal CommandResult RunCommand(
            string databaseName,
            QueryFlags queryFlags,
            CommandDocument command,
            bool throwOnError)
        {
            var commandName = command.GetElement(0).Name;

            var writerSettings = new BsonBinaryWriterSettings
            {
                GuidRepresentation = GuidRepresentation.Unspecified,
                MaxDocumentSize    = _serverInstance.MaxDocumentSize
            };

            using (var message = new MongoQueryMessage(writerSettings, databaseName + ".$cmd", queryFlags, 0, 1, command, null))
            {
                SendMessage(message, null, databaseName); // write concern doesn't apply to queries
            }

            var readerSettings = new BsonBinaryReaderSettings
            {
                GuidRepresentation = GuidRepresentation.Unspecified,
                MaxDocumentSize    = _serverInstance.MaxDocumentSize
            };
            var reply = ReceiveMessage <BsonDocument>(readerSettings, null);

            if (reply.NumberReturned == 0)
            {
                var message = string.Format("Command '{0}' failed. No response returned.", commandName);
                throw new MongoCommandException(message);
            }

            var commandResult = new CommandResult(command, reply.Documents[0]);

            if (throwOnError && !commandResult.Ok)
            {
                throw new MongoCommandException(commandResult);
            }

            return(commandResult);
        }
Exemplo n.º 30
0
        // this is a low level method that doesn't require a MongoServer
        // so it can be used while connecting to a MongoServer
        internal CommandResult RunCommand(
            MongoServer server,
            string collectionName,
            QueryFlags queryFlags,
            CommandDocument command
            )
        {
            var commandName = command.GetElement(0).Name;

            using (
                var message = new MongoQueryMessage(
                    server,
                    collectionName,
                    queryFlags,
                    0,   // numberToSkip
                    1,   // numberToReturn (must be 1 or -1 for commands)
                    command,
                    null // fields
                    )
                ) {
                SendMessage(message, SafeMode.False);
            }

            var reply = ReceiveMessage <BsonDocument>(server);

            if (reply.NumberReturned == 0)
            {
                var message = string.Format("Command '{0}' failed: no response returned", commandName);
                throw new MongoCommandException(message);
            }

            var commandResult = new CommandResult(command, reply.Documents[0]);

            if (!commandResult.Ok)
            {
                throw new MongoCommandException(commandResult);
            }

            return(commandResult);
        }
Exemplo n.º 31
0
        internal void SetupQueryClaim(QueryRequest query)
        {
            if (!GraphTrustService.Graph.Scopes.ContainsKey(query.Scope))
            {
                Errors.Add($"Unknown claim scope {query.Scope}");
            }
            else
            {
                ClaimScope = GraphTrustService.Graph.Scopes.GetIndex(query.Scope);
            }

            // If no types have been defined then use the defaults
            if (query.Types == null || query.Types.Count == 0)
            {
                var graphClaim = GraphTrustService.CreateGraphClaim(PackageBuilder.BINARY_CLAIM_DTP1, "", PackageBuilder.CreateBinaryTrustAttributes(true));
                ClaimTypes.Add(graphClaim.Index);
                //var idClaim = GraphTrustService.CreateGraphClaim(PackageBuilder.ID_IDENTITY_DTP1, "", PackageBuilder.CreateBinaryTrustAttributes(true));
                //ClaimTypes.Add(idClaim.Index);
            }
            else
            {
                foreach (var type in query.Types)
                {
                    if (!GraphTrustService.Graph.ClaimType.ContainsKey(type))
                    {
                        Errors.Add($"Unknown claim type {type}"); // Why!?
                    }
                    else
                    {
                        ClaimTypes.Add(GraphTrustService.Graph.ClaimType.GetIndex(type));
                    }
                }

                if (!ClaimTypes.Contains(this.BinaryClaimTypeIndex))
                {
                    Flags |= QueryFlags.IncludeClaimTrust;
                }
            }
        }
Exemplo n.º 32
0
 private void AddFlags()
 {
     if (Values != null && Values.Length > 0)
     {
         Flags |= QueryFlags.Values;
     }
     if (SkipMetadata)
     {
         Flags |= QueryFlags.SkipMetadata;
     }
     if (PageSize != int.MaxValue && PageSize >= 0)
     {
         Flags |= QueryFlags.PageSize;
     }
     if (PagingState != null)
     {
         Flags |= QueryFlags.WithPagingState;
     }
     if (SerialConsistency != ConsistencyLevel.Any)
     {
         Flags |= QueryFlags.WithSerialConsistency;
     }
 }
Exemplo n.º 33
0
        public static Int32 Write_QUERY(Stream stream,
                                        Int32 requestID,
                                        Database db,
                                        Collection collection,     //may be null for $CMD
                                        QueryFlags flags,
                                        Int32 numberToSkip,
                                        Int32 numberToReturn,
                                        BSONDocument query,
                                        BSONDocument selector    //may be null
                                        )
        {
            stream.Position = STD_HDR_LEN;              //skip the header

            BinUtils.WriteInt32(stream, (Int32)flags);

            //if collection==null then query the $CMD collection
            var fullNameBuffer = collection != null ? collection.m_FullNameCStringBuffer : db.m_CMD_NameCStringBuffer;

            stream.Write(fullNameBuffer, 0, fullNameBuffer.Length);


            BinUtils.WriteInt32(stream, numberToSkip);
            BinUtils.WriteInt32(stream, numberToReturn);

            query.WriteAsBSON(stream);

            if (selector != null)
            {
                selector.WriteAsBSON(stream);
            }

            var total = (Int32)stream.Position;

            stream.Position = 0;
            writeStandardHeader(stream, total, requestID, 0, OP_QUERY);
            return(total);
        }
Exemplo n.º 34
0
 internal void AddFlags(QueryFlags flags)
 {
     _queryFlags |= flags;
 }
Exemplo n.º 35
0
        public IEnumerable<object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var cursor = _this.FindAs(documentType, query);

            if (modes != QueryFlags.None)
                cursor.SetFlags(modes);

            if (skip > 0)
                cursor.SetSkip(skip);

            if (first > 0)
                cursor.SetLimit(first);

            if (sortBy != null)
                cursor.SetSortOrder(sortBy);

            if (fields != null)
                cursor.SetFields(fields);

            foreach (var it in cursor)
                yield return it;
        }
Exemplo n.º 36
0
 internal bool HasFlag(QueryFlags flags)
 {
     return _queryFlags.HasFlag(flags);
 }
Exemplo n.º 37
0
        public static Int32 Write_QUERY(Stream stream,
            Int32 requestID,
            Database db,
            Collection collection, //may be null for $CMD
            QueryFlags flags,
            Int32 numberToSkip,
            Int32 numberToReturn,
            BSONDocument query,
            BSONDocument selector//may be null
            )
        {
            stream.Position = STD_HDR_LEN;//skip the header

                          BinUtils.WriteInt32(stream, (Int32)flags);

                          //if collection==null then query the $CMD collection
                          var fullNameBuffer = collection!=null ? collection.m_FullNameCStringBuffer : db.m_CMD_NameCStringBuffer;
                          stream.Write(fullNameBuffer, 0, fullNameBuffer.Length);

                          BinUtils.WriteInt32(stream, numberToSkip);
                          BinUtils.WriteInt32(stream, numberToReturn);

                          query.WriteAsBSON(stream);

                          if (selector!=null)
                           selector.WriteAsBSON(stream);

                          var total = (Int32)stream.Position;
                          stream.Position = 0;
                          writeStandardHeader(stream, total, requestID, 0, OP_QUERY);
                          return total;
        }
Exemplo n.º 38
0
        /// <summary>
        /// Verify the RopQueryNamedProperties operation related requirements.
        /// </summary>
        /// <param name="queryFlags">The QueryFlags specified in request buffer.</param>
        /// <param name="propertyGuid">The PropertyGuid specified in request buffer.</param>       
        /// <param name="ropQueryNamedPropertiesResopnse">The RopQueryNamedProperties response buffer structure.</param>
        /// <param name="objectType">Indicates which object type the RopQueryNamedProperties operation is acting on.</param>
        /// <param name="isOrdered">A boolean value which indicates whether the order of elements in request/response buffer is right.</param>
        private void VerifyRopQueryNamedProperties(
            QueryFlags queryFlags,
            byte[] propertyGuid,
            RopQueryNamedPropertiesResponse ropQueryNamedPropertiesResopnse,
            ServerObjectType objectType,
            bool isOrdered)
        {
            // Since the RopQueryNamedProperties ROP response was parsed successfully, MS-OXCPRPT_R49502 can be captured directly.
            Site.CaptureRequirement(
                 49502,
                 @"[In Processing RopQueryNamedProperties] The server responds with a RopQueryNamedProperties ROP response buffer.");

            if (ropQueryNamedPropertiesResopnse.ReturnValue.Equals((uint)CPRPTErrorCode.None))
            {
                if (objectType == ServerObjectType.Message)
                {
                    // If the object type this operation acting on is Message object and this operation is performed successfully, then the following requirement can be captured.
                    Site.CaptureRequirement(
                        12901,
                        @"[In RopQueryNamedProperties ROP] This operation is valid on Message objects.");
                }

                if (objectType == ServerObjectType.Folder)
                {
                    // If the object type this operation acting on is Folder object and this operation is performed successfully, then the following requirement can be captured.
                    Site.CaptureRequirement(
                        12902,
                        @"[In RopQueryNamedProperties ROP] This operation is valid on Folder objects.");
                }

                if (objectType == ServerObjectType.Attachment)
                {
                    // If the object type this operation acting on is Attachment object and this operation is performed successfully, then the following requirement can be captured.
                    Site.CaptureRequirement(
                        12903,
                        @"[In RopQueryNamedProperties ROP] This operation is valid on Attachment objects.");
                }

                if (objectType == ServerObjectType.Logon)
                {
                    if (Common.IsRequirementEnabled(12904, this.Site))
                    {
                        // If the object type this operation acting on is Logon object and this operation is performed successfully, then the following requirement can be captured.
                        Site.CaptureRequirement(
                            12904,
                            @"[In RopQueryNamedProperties ROP] Implementation is valid on Logon objects. (Microsoft Exchange Server 2010 and above follow this behavior)");
                    }
                }

                if (ropQueryNamedPropertiesResopnse.IdCount != 0)
                {
                    // The parser has ensured the field satisfied the format, otherwise the response cannot be received.
                    Site.CaptureRequirement(
                        14301,
                        @"[In RopQueryNamedProperties ROP Response Buffer] propertyNames (variable): An array of PropertyName structures ([MS-OXCDATA] section 2.6.1). ");
                }

                // The parser has ensured the field satisfied the format, otherwise the response cannot be received.
                Site.CaptureRequirement(
                    14201,
                     @"[In RopQueryNamedProperties ROP Response Buffer] propertyIds (variable): An array of 16-bit integers, each of which is a property ID.");

                if (ropQueryNamedPropertiesResopnse.PropertyNames != null)
                {
                    Site.CaptureRequirementIfAreEqual<int>(
                       ropQueryNamedPropertiesResopnse.PropertyIds.Length,
                       ropQueryNamedPropertiesResopnse.PropertyNames.Length,
                       14203,
                       @"[In RopQueryNamedProperties ROP Response Buffer] PropertyIds: The array MUST contain one property ID for each of the named properties specified in the PropertyNames field.");

                    if (queryFlags == QueryFlags.NoStrings)
                    {
                        // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R132
                        bool isVerifyR132 = true;

                        // Examine every PropertyName in the ropQueryNamedPropertiesResponse.
                        for (int i = 0; i < ropQueryNamedPropertiesResopnse.IdCount; i++)
                        {
                            // If any Named properties with a Kind of 0x1 actually presents in the response, isVerifyR132 should be set to false.
                            if (ropQueryNamedPropertiesResopnse.PropertyNames[i].Kind == 0x01)
                            {
                                // Add the debug information
                                Site.Log.Add(
                                    LogEntryKind.Debug,
                                    "Verify MS-OXCPRPT_R132, QueryFlags is {0}, PropertyName.Kind in the response is {1}",
                                    queryFlags,
                                    ropQueryNamedPropertiesResopnse.PropertyNames[i].Kind);

                                isVerifyR132 = false;
                                break;
                            }
                        }

                        Site.CaptureRequirementIfIsTrue(
                            isVerifyR132,
                            132,
                            @"[In RopQueryNamedProperties ROP Request Buffer] QueryFlags: NoStrings:Named properties that have a property name identifier MUST NOT be included in the response.");
                    }

                    if (queryFlags == QueryFlags.NoIds)
                    {
                        // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R134
                        bool isVerifyR134 = true;

                        // Examine every PropertyName in the ropQueryNamedPropertiesResponse.
                        for (int i = 0; i < ropQueryNamedPropertiesResopnse.IdCount; i++)
                        {
                            // If any Named properties with a Kind of 0x00 actually presents in the response, isVerifyR134 should be set to false.
                            if (ropQueryNamedPropertiesResopnse.PropertyNames[i].Kind == 0x00)
                            {
                                // Add the debug information
                                Site.Log.Add(
                                    LogEntryKind.Debug,
                                    "Verify MS-OXCPRPT_R134, QueryFlags is {0}, PropertyName.Kind in the response is {1}",
                                    queryFlags,
                                    ropQueryNamedPropertiesResopnse.PropertyNames[i].Kind);

                                isVerifyR134 = false;
                                break;
                            }
                        }

                        Site.CaptureRequirementIfIsTrue(
                            isVerifyR134,
                            134,
                            @"[In RopQueryNamedProperties ROP Request Buffer] QueryFlags: NoIds:Named properties that have a long ID (LID) MUST NOT be included in the response.");
                    }

                    // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R141
                    Site.CaptureRequirementIfAreEqual<ushort>(
                        (ushort)ropQueryNamedPropertiesResopnse.PropertyNames.Length,
                        ropQueryNamedPropertiesResopnse.IdCount,
                        141,
                        @"[In IdCount] IdCount: 2 byte integer.");

                    // Add the debug information
                    Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCPRPT_R14101");

                    // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R14101
                    Site.CaptureRequirementIfAreEqual<ushort>(
                        (ushort)ropQueryNamedPropertiesResopnse.PropertyIds.Length,
                        ropQueryNamedPropertiesResopnse.IdCount,
                        14101,
                        @"[In RopQueryNamedProperties ROP Response Buffer] IdCount: An integer that specifies the number of elements contained in the PropertyIds field.");

                    Site.CaptureRequirementIfAreEqual<ushort>(
                        (ushort)ropQueryNamedPropertiesResopnse.PropertyIds.Length,
                        ropQueryNamedPropertiesResopnse.IdCount,
                        14202,
                        @"[In RopQueryNamedProperties ROP Response Buffer] propertyIds: The number of integers contained in the array MUST equal the value specified in the IdCount field. ");

                    bool isVerifyR238 = true;
                    foreach (PropertyId id in ropQueryNamedPropertiesResopnse.PropertyIds)
                    {
                        if ((id.ID & 0x8000) != 0x8000)
                        {
                            isVerifyR238 = false;
                            break;
                        }
                    }

                    Site.CaptureRequirementIfIsTrue(
                        isVerifyR238,
                        238,
                        @"[In RopGetNamesFromPropertyIds ROP] Property IDs for named properties are identified by having their most significant bit set (0x8000). ");

                    Site.CaptureRequirementIfIsTrue(
                        isVerifyR238,
                        41405,
                        @"[In Getting Property IDs for Named Properties] The property ID of a named property has the most significant bit set (0x8000).");
                }

                if (queryFlags == QueryFlags.OtherValue)
                {
                    Site.CaptureRequirementIfAreEqual<uint>(
                        0x00,
                        ropQueryNamedPropertiesResopnse.ReturnValue,
                        87802,
                        @"[In Processing RopQueryNamedProperties] No matter what the invalid bits that are set in the QueryFlags field of the ROP request buffer, the server return the same.");
                }

                // propertyGuid is not null means that the client specified this field in the request buffer, this field is present.
                if (propertyGuid != null)
                {
                    // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R138
                    bool isVerifyR138 = true;

                    // Examine every PropertyName's Guid return by server.
                    for (int i = 0; i < ropQueryNamedPropertiesResopnse.PropertyNames.Length; i++)
                    {
                        // Check whether the Guid returned in response buffer matches the PropertyGuid specified in request buffer.
                        if (!Common.CompareByteArray(ropQueryNamedPropertiesResopnse.PropertyNames[i].Guid, propertyGuid))
                        {
                            // Add the debug information
                            Site.Log.Add(
                                LogEntryKind.Debug,
                                "Verify MS-OXCPRPT_R138,PropertyGuid in request buffer is {0}, Guid in response buffer is {1}",
                                propertyGuid.ToString(),
                                ropQueryNamedPropertiesResopnse.PropertyNames[i].Guid.ToString());

                            isVerifyR138 = false;
                            break;
                        }
                    }

                    Site.CaptureRequirementIfIsTrue(
                        isVerifyR138,
                        138,
                        @"[In RopQueryNamedProperties ROP Request Buffer] PropertyGuid: A GUID that specifies the property set of properties to be returned. If this field is present, only named properties with a property set matching the GUID are returned in a successful response.");
                }

                // Verify MS-OXCPRPT requirement: MS-OXCPRPT_R145
                // The order has been verified when de-serializing the related structures and represented by the variable isOrdered.
                // Whether the named properties match the PropertyGUID specified in the request has been verified in MS-OXCPRPT_R138 above.
                Site.CaptureRequirementIfIsTrue(
                    isOrdered,
                    145,
                    @"[In RopQueryNamedProperties ROP Response Buffer] PropertyNames:The entries in this list MUST match the order of the entries in the PropertyIds field, and the number of entries MUST be equal.");
            }
        }
        /// <summary>
        /// The method is used to query an object for all the named properties. 
        /// </summary>
        /// <param name="queryFlags">Specifies QueryFlags parameter in request.</param>
        /// <param name="hasGuid">Indicates whether HasGuid is zero, 
        /// If the HasGUID field is non-zero then the PropertyGUID field MUST be included in the request. 
        /// If no PropertyGUID is specified, then properties from any GUID MUST be returned in the results.</param>
        /// <param name="isKind0x01Returned">True if the named properties of the response with the Kind field 
        /// ([MS-OXCDATA] section 2.6.1) set to 0x1 was returned.</param>
        /// <param name="isKind0x00Returned">True if the named properties of the response with the Kind field 
        /// ([MS-OXCDATA] section 2.6.1) set to 0x0 was returned.</param>
        /// <param name="isNamedPropertyGuidReturned">True if the named properties  with a GUID field ([MS-OXCDATA] 
        /// section 2.6.1) value that does not match the value of the PropertyGUID field was returned.</param>
        public void RopQueryNamedPropertiesMethod(
            QueryFlags queryFlags,
            bool hasGuid,
            out bool isKind0x01Returned,
            out bool isKind0x00Returned,
            out bool isNamedPropertyGuidReturned)
        {
            #region Initialize parameters property
            // The value of hasGuid in RopQueryNameProperties method.
            byte hasGuidRequest = 0;

            // The value of queryFlags in RopQueryNameProperties method.
            byte queryFlagRequest = Convert.ToByte(queryFlags);

            // The value of propertyGuid in RopQuerynameProperties method.
            byte[] propertyGuid = null;

            // Set default values for three parameters.
            isKind0x01Returned = false;
            isKind0x00Returned = false;
            isNamedPropertyGuidReturned = false;

            // When name property has GUID, set parameters.
            if (hasGuid)
            {
                hasGuidRequest = Convert.ToByte(true);
                PropertyName[] ptyName = new PropertyName[1];
                ptyName[0] = this.GetPropertyName((byte)Kind.NameField);
                propertyGuid = ptyName[0].Guid;

                this.RopGetPropertyIdsFromNames(this.cprptCurrentHandle, (byte)GetPropertyIdsFromNamesFlags.Create, ptyName, true);
                if (this.cprptCurrentType == ServerObjectType.Message)
                {
                    this.RopSaveChangesMessage(this.cprptCurrentHandle, true);
                }
                else if (this.cprptCurrentType == ServerObjectType.Attachment)
                {
                    this.RopSaveChangesAttachment(this.cprptCurrentHandle, true);
                }
            }
            #endregion
            // Call RopQueryNamedProperties.
            RopQueryNamedPropertiesResponse queryNamePtyRes = this.RopQueryNamedProperties(this.cprptCurrentHandle, queryFlagRequest, hasGuidRequest, propertyGuid);

            #region Verify isKind0x00Return and isKind0x00Return
            // Verify if the kind of NamedProperties in RopQueryNamedPropertiesResponse is 0x01.
            for (int i = 0; i < queryNamePtyRes.IdCount; i++)
            {
                if (queryNamePtyRes.PropertyNames[i].Kind == (byte)Kind.NameField)
                {
                    isKind0x01Returned = true;
                    break;
                }
            }

            // Verify if the kind of NamedProperties in RopQueryNamedPropertiesResponse is 0x00.
            for (int i = 0; i < queryNamePtyRes.IdCount; i++)
            {
                if (queryNamePtyRes.PropertyNames[i].Kind == (byte)Kind.LidField)
                {
                    isKind0x00Returned = true;
                    break;
                }
            }
            #endregion

            #region Verify isNamedPropertyGuidReturn
            // If the PropertyGUID field presents, named properties with a GUID field value that does not match the value of the PropertyGUID field MUST NOT be returned.
            for (int i = 0; i < queryNamePtyRes.IdCount; i++)
            {
                if (hasGuid && Common.CompareByteArray(queryNamePtyRes.PropertyNames[i].Guid, propertyGuid))
                {
                    isNamedPropertyGuidReturned = true;
                }
                else
                {
                    isNamedPropertyGuidReturned = false;
                    break;
                }
            }
            #endregion

            // Verify RopQueryNamedProperties.
            this.VerifyRopQueryNamedProperties(queryFlags, propertyGuid, queryNamePtyRes, this.cprptCurrentType, true);
        }
Exemplo n.º 40
0
 // accepts components to avoid QueryCacheEntry allocation for cached query
 public bool Compare(IDataContext context, Expression queryExpression, QueryFlags flags)
 {
     return(Flags == flags && Query.Compare(context, queryExpression));
 }
Exemplo n.º 41
0
        public static void Main(string[] args)
        {
            int exitCode = 0;

            String     path;
            String     query      = "*";
            QueryFlags queryflags = QueryFlags.QueryChannelPath | QueryFlags.QueryForwardDirection;
            UInt32     count      = UInt32.MaxValue;
            String     format     = "xml";

            try
            {
                // parse the command line

                if (args.Length == 0)
                {
                    Console.WriteLine("Error: No parameters provided.");
                    PrintUsage();
                    Environment.Exit(1);
                }

                if (args[0] == "/?")
                {
                    PrintUsage();
                    Environment.Exit(1);
                }

                path = args[0];

                char[] delimiters = { ':' };

                for (int i = 1; i < args.Length; i++)
                {
                    String   option = args[i].Substring(1);
                    String[] words  = option.Split(delimiters, 2);
                    words[0] = words[0].ToLower();

                    switch (words[0])
                    {
                    case "logfile":
                    case "lf":
                        queryflags &= ~QueryFlags.QueryChannelPath;
                        queryflags |= QueryFlags.QueryFilePath;
                        break;

                    case "query":
                    case "q":
                        query = words[1];
                        break;

                    case "reversedirection":
                    case "rd":
                        queryflags &= ~QueryFlags.QueryForwardDirection;
                        queryflags |= QueryFlags.QueryReverseDirection;
                        break;

                    case "count":
                    case "c":
                        count = Convert.ToUInt32(words[1]);
                        break;

                    case "format":
                    case "f":
                        format = words[1].ToLower();
                        if (format != "text" && format != "xml")
                        {
                            throw (new Exception(String.Format("Unrecognized format option: {0}.", format)));
                        }
                        break;

                    default:
                        throw (new Exception(String.Format("Unrecognized parameter option: {0}.", words[0])));
                    }
                }


                // query the event log

                IntPtr resultSetPtr = Events.Query(IntPtr.Zero, path, query, queryflags);
                if (resultSetPtr == IntPtr.Zero)
                {
                    Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                    throw (new Exception(String.Format("Query failed with error {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message)));
                }

                using (SafeEventHandle resultSet = new SafeEventHandle(resultSetPtr))
                {
                    // read the selected events

                    IntPtr[] events   = new IntPtr[1];
                    int      timeout  = 5000; // 5 seconds
                    int      returned = 0;
                    UInt32   n        = 0;

                    while (Events.Next(resultSet.Handle, 1, events, timeout, 0, out returned) && n++ < count)
                    {
                        foreach (IntPtr evtptr in events)
                        {
                            using (SafeEventHandle evt = new SafeEventHandle(evtptr))
                            {
                                if (format == "xml")
                                {
                                    Console.WriteLine("\n" + RenderEventToXml(evt, RenderFlags.RenderEventXml));
                                }
                                else if (format == "text")
                                {
                                    Console.WriteLine("\n" + FormatEventAsText(evt));
                                }
                            }
                        }
                    }

                    if (Win32Error.ErrorNoMoreItems != Marshal.GetLastWin32Error() &&
                        Win32Error.ErrorSuccess != Marshal.GetLastWin32Error())
                    {
                        Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                        throw (new Exception(String.Format("Failed to read next event. error: {0}, {1}.", Marshal.GetLastWin32Error().ToString(), ex.Message)));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                exitCode = 1;
            }

            Environment.Exit(exitCode);
        }
Exemplo n.º 42
0
 public QueryCacheEntry(Query <T> query, QueryFlags flags)
 {
     // query doesn't have GetHashCode now, so we cannot precalculate hashcode to speed-up search
     Query = query;
     Flags = flags;
 }
Exemplo n.º 43
0
        public IEnumerable<object> FindAs(Type documentType, IMongoQuery query, QueryFlags modes, IMongoSortBy sortBy, int skip, int first, IMongoFields fields)
        {
            var iter = QueryCompiler.Query(Documents, Documents2, query, sortBy, skip, first);
            if (fields == null)
                return iter.Select(x => BsonSerializer.Deserialize(x, documentType));

            var project = FieldCompiler.GetFunction(fields);
            return iter.Select(project).Select(x => BsonSerializer.Deserialize(x, documentType));
        }
Exemplo n.º 44
0
 public IMongoCursor SetFlags(QueryFlags flags)
 {
     return(new MongoCursorProxy(_mongoMongoCursor.SetFlags(flags)));
 }
Exemplo n.º 45
0
        public static void RopQueryNamedPropertiesMethod(
            QueryFlags queryFlags,
            bool hasGuid,
            out bool isKind0x01Return,
            out bool isKind0x00Return,
            out bool isNamedPropertyGuidReturn)
        {
            Condition.IsTrue(isInitialized);
            Condition.IsTrue(
                (globalObj == ServerObjectType.Logon && requirementContainer[12904]) ||
                globalObj == ServerObjectType.Folder ||
                globalObj == ServerObjectType.Message ||
                globalObj == ServerObjectType.Attachment);

            isKind0x01Return = false;
            isKind0x00Return = false;
            isNamedPropertyGuidReturn = false;

            if (queryFlags == QueryFlags.NoIds)
            {
                if (hasGuid)
                {
                    isKind0x01Return = true;
                    ModelHelper.CaptureRequirement(
                        877,
                        @"[In Processing RopQueryNamedProperties] Starting with the full list of all  named properties:
                        If the NoIds bit is set in the QueryFlags field, named properties with the Kind field set to 0x0 MUST NOT be returned.");

                    isNamedPropertyGuidReturn = true;
                    ModelHelper.CaptureRequirement(
                        878,
                        @"[In Processing RopQueryNamedProperties] Starting with the full list of all  named properties: 
                        If the PropertyGuid field of the ROP request buffer is present, named properties with a GUID field ([MS-OXCDATA] section 2.6.1) value 
                        that does not match the value of the PropertyGuid field MUST NOT be returned.");
                }
            }
            else if (!hasGuid && queryFlags == QueryFlags.NoStrings)
            {
                isKind0x00Return = true;
                ModelHelper.CaptureRequirement(
                    876,
                    @"[In Processing RopQueryNamedProperties] Starting with the full list of all  named properties: 
                    If the NoStrings bit is set in the QueryFlags field of the ROP request buffer, named properties with the Kind field ([MS-OXCDATA] section 2.6.1) 
                    set to 0x1 MUST NOT be returned.");
            }
        }