Exemple #1
0
        private async Task <GridFSFileInfo> GetFileInfoAsync(IReadBindingHandle binding, BsonValue id, CancellationToken cancellationToken)
        {
            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry       = _database.Settings.SerializerRegistry;
            var fileInfoSerializer       = serializerRegistry.GetSerializer <GridFSFileInfo>();
            var messageEncoderSettings   = GetMessageEncoderSettings();
            var filter = new BsonDocument("_id", id);

            var operation = new FindOperation <GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit  = -1
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                var fileInfoList = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);

                var fileInfo = fileInfoList.FirstOrDefault();
                if (fileInfo == null)
                {
                    throw new GridFSFileNotFoundException(id);
                }
                return(fileInfo);
            }
        }
Exemple #2
0
        /// <inheritdoc />
        public async Task <IAsyncCursor <GridFSFileInfo> > FindAsync(FilterDefinition <GridFSFileInfo> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(filter, nameof(filter));
            options = options ?? new GridFSFindOptions();

            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry       = _database.Settings.SerializerRegistry;
            var fileInfoSerializer       = serializerRegistry.GetSerializer <GridFSFileInfo>();
            var messageEncoderSettings   = GetMessageEncoderSettings();
            var renderedFilter           = filter.Render(fileInfoSerializer, serializerRegistry);
            var renderedSort             = options.Sort == null ? null : options.Sort.Render(fileInfoSerializer, serializerRegistry);

            var operation = new FindOperation <GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                BatchSize       = options.BatchSize,
                Filter          = renderedFilter,
                Limit           = options.Limit,
                MaxTime         = options.MaxTime,
                NoCursorTimeout = options.NoCursorTimeout ?? false,
                Skip            = options.Skip,
                Sort            = renderedSort
            };

            using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false))
            {
                return(await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false));
            }
        }
Exemple #3
0
        private async Task <bool> IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken)
        {
            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var messageEncoderSettings   = GetMessageEncoderSettings();
            var operation = new FindOperation <BsonDocument>(filesCollectionNamespace, BsonDocumentSerializer.Instance, messageEncoderSettings)
            {
                Limit       = 1,
                ReadConcern = GetReadConcern(),
                SingleBatch = true,
                Projection  = new BsonDocument("_id", 1)
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                if (await cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false))
                {
                    var batch = cursor.Current;
                    if (batch.Count() > 0)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemple #4
0
        private async Task <GridFSFileInfo> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, CancellationToken cancellationToken)
        {
            var collectionNamespace    = GetFilesCollectionNamespace();
            var serializerRegistry     = _database.Settings.SerializerRegistry;
            var fileInfoSerializer     = serializerRegistry.GetSerializer <GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var filter = new BsonDocument("filename", filename);
            var skip   = revision >= 0 ? revision : -revision - 1;
            var limit  = 1;
            var sort   = new BsonDocument("uploadDate", revision >= 0 ? 1 : -1);

            var operation = new FindOperation <GridFSFileInfo>(
                collectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit  = limit,
                Skip   = skip,
                Sort   = sort
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                var fileInfoList = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);

                var fileInfo = fileInfoList.FirstOrDefault();
                if (fileInfo == null)
                {
                    throw new GridFSFileNotFoundException(filename, revision);
                }
                return(fileInfo);
            }
        }
Exemple #5
0
        private static Task <Cursor <BsonDocument> > Query(IReadBinding binding, BsonDocument query)
        {
            var queryOp = new FindOperation <BsonDocument>(__collection, query, BsonDocumentSerializer.Instance, __messageEncoderSettings)
            {
                Limit = 1
            };

            return(queryOp.ExecuteAsync(binding));
        }
Exemple #6
0
        private static Task <Cursor <BsonDocument> > Query(IReadBinding binding, BsonDocument query)
        {
            var queryOp = new FindOperation <BsonDocument>(
                _database,
                _collection,
                BsonDocumentSerializer.Instance,
                query).WithLimit(1);

            return(queryOp.ExecuteAsync(binding));
        }
Exemple #7
0
        private static Task <IAsyncCursor <BsonDocument> > Query(IReadBinding binding, BsonDocument query)
        {
            var findOp = new FindOperation <BsonDocument>(__collection, BsonDocumentSerializer.Instance, __messageEncoderSettings)
            {
                Criteria = query,
                Limit    = -1
            };

            return(findOp.ExecuteAsync(binding, Timeout.InfiniteTimeSpan, CancellationToken.None));
        }
        private static Task <IAsyncCursor <BsonDocument> > Query(IReadBinding binding, BsonDocument filter)
        {
            var findOp = new FindOperation <BsonDocument>(__collection, BsonDocumentSerializer.Instance, __messageEncoderSettings)
            {
                Filter = filter,
                Limit  = -1
            };

            return(findOp.ExecuteAsync(binding, __cancellationTokenSource.Token));
        }
        // methods
        public async Task <IEnumerable <BsonDocument> > ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
        {
            var collectionNamespace = new CollectionNamespace(_databaseNamespace, "system.users");
            var filter    = _username == null ? new BsonDocument() : new BsonDocument("user", _username);
            var operation = new FindOperation <BsonDocument>(collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Filter = filter
            };
            var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false);

            return(await cursor.ToListAsync(cancellationToken).ConfigureAwait(false));
        }
Exemple #10
0
        private async Task <BsonDocument> FindUserAsync(IChannelSourceHandle channelSource, CollectionNamespace collectionNamespace, CancellationToken cancellationToken)
        {
            var operation = new FindOperation <BsonDocument>(collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Filter = new BsonDocument("user", _username),
                Limit  = -1
            };
            var cursor = await operation.ExecuteAsync(channelSource, ReadPreference.Primary, cancellationToken).ConfigureAwait(false);

            var userDocuments = await cursor.ToListAsync().ConfigureAwait(false);

            return(userDocuments.FirstOrDefault());
        }
Exemple #11
0
        // private methods
        private async Task GetChunkAsync(long n, CancellationToken cancellationToken)
        {
            var chunksCollectionNamespace = Bucket.GetChunksCollectionNamespace();
            var messageEncoderSettings    = Bucket.GetMessageEncoderSettings();

#pragma warning disable 618
            var filter = new BsonDocument
            {
                { "files_id", FilesCollectionDocument.IdAsBsonValue },
                { "n", n }
            };
#pragma warning restore

            var operation = new FindOperation <BsonDocument>(
                chunksCollectionNamespace,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit  = -1
            };

            using (var cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false))
            {
                var documents = await cursor.ToListAsync();

                if (documents.Count == 0)
                {
#pragma warning disable 618
                    throw new GridFSChunkException(FilesCollectionDocument.IdAsBsonValue, n, "missing");
#pragma warning restore
                }

                var document = documents[0];
                var data     = document["data"].AsBsonBinaryData.Bytes;

                var chunkSizeBytes    = FilesCollectionDocument.ChunkSizeBytes;
                var lastChunk         = 0;
                var expectedChunkSize = n == lastChunk ? FilesCollectionDocument.Length % chunkSizeBytes : chunkSizeBytes;
                if (data.Length != expectedChunkSize)
                {
#pragma warning disable 618
                    throw new GridFSChunkException(FilesCollectionDocument.IdAsBsonValue, n, "the wrong size");
#pragma warning restore
                }

                _chunk = data;
                _n     = n;
            }
        }
Exemple #12
0
        private async Task <IAsyncCursor <BsonDocument> > Query(IReadBinding binding, BsonDocument filter)
        {
            var findOp = new FindOperation <BsonDocument>(_collection, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Filter = filter,
                Limit  = -1
            };

            using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
                using (var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _cancellationTokenSource.Token))
                {
                    return(await findOp.ExecuteAsync(binding, linked.Token));
                }
        }
Exemple #13
0
        private IAsyncCursor <BsonDocument> CreateAndRunFindOperation(RetryableReadContext context, bool async)
        {
            var findOperation = new FindOperation <BsonDocument>(
                _collectionNamespace,
                BsonDocumentSerializer.Instance,
                _messageEncoderSettings)
            {
                BatchSize = 1
            };

            if (async)
            {
                return(findOperation.ExecuteAsync(context, CancellationToken.None).GetAwaiter().GetResult());
            }
            else
            {
                return(findOperation.Execute(context, CancellationToken.None));
            }
        }
Exemple #14
0
        // private methods
        private async Task GetFirstBatchAsync(CancellationToken cancellationToken)
        {
            var chunksCollectionNamespace = Bucket.GetChunksCollectionNamespace();
            var messageEncoderSettings    = Bucket.GetMessageEncoderSettings();

#pragma warning disable 618
            var filter = new BsonDocument("files_id", FileInfo.IdAsBsonValue);
#pragma warning restore
            var sort = new BsonDocument("n", 1);

            var operation = new FindOperation <BsonDocument>(
                chunksCollectionNamespace,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings)
            {
                Filter = filter,
                Sort   = sort
            };

            _cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false);
            await GetNextBatchAsync(cancellationToken).ConfigureAwait(false);
        }
        private async Task<GridFSFileInfo> GetFileInfoAsync(IReadBindingHandle binding, BsonValue id, CancellationToken cancellationToken)
        {
            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry = _database.Settings.SerializerRegistry;
            var fileInfoSerializer = serializerRegistry.GetSerializer<GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var filter = new BsonDocument("_id", id);

            var operation = new FindOperation<GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit = 1,
                SingleBatch = true
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                var fileInfoList = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
                var fileInfo = fileInfoList.FirstOrDefault();
                if (fileInfo == null)
                {
                    throw new GridFSFileNotFoundException(id);
                }
                return fileInfo;
            }
        }
        private static Task<Cursor<BsonDocument>> Query(IReadBinding binding, BsonDocument query)
        {
            var queryOp = new FindOperation<BsonDocument>(__collection, query, BsonDocumentSerializer.Instance, __messageEncoderSettings)
            {
                Limit = 1
            };

            return queryOp.ExecuteAsync(binding);
        }
Exemple #17
0
        private static Task<Cursor<BsonDocument>> Query(IReadBinding binding, BsonDocument query)
        {
            var queryOp = new FindOperation<BsonDocument>(
                _database,
                _collection,
                BsonDocumentSerializer.Instance,
                query).WithLimit(1);

            return queryOp.ExecuteAsync(binding);
        }
        public void ExecuteAsync_should_throw_when_binding_is_null()
        {
            var subject = new FindOperation<BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings);

            Func<Task> action = () => subject.ExecuteAsync(null, CancellationToken.None);

            action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("binding");
        }
        private async Task<bool> IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken)
        {
            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var operation = new FindOperation<BsonDocument>(filesCollectionNamespace, BsonDocumentSerializer.Instance, messageEncoderSettings)
            {
                Limit = 1,
                SingleBatch = true,
                Projection = new BsonDocument("_id", 1)
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                if (await cursor.MoveNextAsync(cancellationToken).ConfigureAwait(false))
                {
                    var batch = cursor.Current;
                    if (batch.Count() > 0)
                    {
                        return false;
                    }
                }
            }

            return true;
        }
        private async Task<GridFSFileInfo> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, CancellationToken cancellationToken)
        {
            var collectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry = _database.Settings.SerializerRegistry;
            var fileInfoSerializer = serializerRegistry.GetSerializer<GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var filter = new BsonDocument("filename", filename);
            var skip = revision >= 0 ? revision : -revision - 1;
            var limit = 1;
            var sort = new BsonDocument("uploadDate", revision >= 0 ? 1 : -1);

            var operation = new FindOperation<GridFSFileInfo>(
                collectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit = limit,
                Skip = skip,
                Sort = sort
            };

            using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false))
            {
                var fileInfoList = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false);
                var fileInfo = fileInfoList.FirstOrDefault();
                if (fileInfo == null)
                {
                    throw new GridFSFileNotFoundException(filename, revision);
                }
                return fileInfo;
            }
        }
        // private methods
        private async Task GetChunkAsync(long n, CancellationToken cancellationToken)
        {
            var chunksCollectionNamespace = Bucket.GetChunksCollectionNamespace();
            var messageEncoderSettings = Bucket.GetMessageEncoderSettings();
#pragma warning disable 618
            var filter = new BsonDocument
            {
                { "files_id", FileInfo.IdAsBsonValue },
                { "n", n }
            };
#pragma warning restore

            var operation = new FindOperation<BsonDocument>(
                chunksCollectionNamespace,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings)
            {
                Filter = filter,
                Limit = -1
            };

            using (var cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false))
            {
                var documents = await cursor.ToListAsync().ConfigureAwait(false);
                if (documents.Count == 0)
                {
#pragma warning disable 618
                    throw new GridFSChunkException(FileInfo.IdAsBsonValue, n, "missing");
#pragma warning restore
                }

                var document = documents[0];
                var data = document["data"].AsBsonBinaryData.Bytes;

                var chunkSizeBytes = FileInfo.ChunkSizeBytes;
                var lastChunk = 0;
                var expectedChunkSize = n == lastChunk ? FileInfo.Length % chunkSizeBytes : chunkSizeBytes;
                if (data.Length != expectedChunkSize)
                {
#pragma warning disable 618
                    throw new GridFSChunkException(FileInfo.IdAsBsonValue, n, "the wrong size");
#pragma warning restore
                }

                _chunk = data;
                _n = n;
            }
        }
        /// <inheritdoc />
        public async Task<IAsyncCursor<GridFSFileInfo>> FindAsync(FilterDefinition<GridFSFileInfo> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(filter, nameof(filter));
            options = options ?? new GridFSFindOptions();

            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry = _database.Settings.SerializerRegistry;
            var fileInfoSerializer = serializerRegistry.GetSerializer<GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var renderedFilter = filter.Render(fileInfoSerializer, serializerRegistry);
            var renderedSort = options.Sort == null ? null : options.Sort.Render(fileInfoSerializer, serializerRegistry);

            var operation = new FindOperation<GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                BatchSize = options.BatchSize,
                Filter = renderedFilter,
                Limit = options.Limit,
                MaxTime = options.MaxTime,
                NoCursorTimeout = options.NoCursorTimeout ?? false,
                Skip = options.Skip,
                Sort = renderedSort
            };

            using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false))
            {
                return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false);
            }
        }
Exemple #23
0
        private async Task<IAsyncCursor<BsonDocument>> Query(IReadBinding binding, BsonDocument filter)
        {
            var findOp = new FindOperation<BsonDocument>(_collection, BsonDocumentSerializer.Instance, _messageEncoderSettings)
            {
                Filter = filter,
                Limit = -1
            };

            using (var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
            using (var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _cancellationTokenSource.Token))
            {
                return await findOp.ExecuteAsync(binding, linked.Token);
            }
        }
        public void Execute_should_throw_when_binding_is_null(
            [Values(false, true)]
            bool async)
        {
            var subject = new FindOperation<BsonDocument>(_collectionNamespace, BsonDocumentSerializer.Instance, _messageEncoderSettings);

            var exception = Record.Exception(() =>
            {
                if (async)
                {
                    subject.ExecuteAsync(null, CancellationToken.None).GetAwaiter().GetResult();
                }
                else
                {
                    subject.Execute(null, CancellationToken.None);
                }
            });

            var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject;
            argumentNullException.ParamName.Should().Be("binding");
        }
        // private methods
        private async Task GetFirstBatchAsync(CancellationToken cancellationToken)
        {
            var chunksCollectionNamespace = Bucket.GetChunksCollectionNamespace();
            var messageEncoderSettings = Bucket.GetMessageEncoderSettings();
#pragma warning disable 618
            var filter = new BsonDocument("files_id", FilesCollectionDocument.IdAsBsonValue);
#pragma warning restore
            var sort = new BsonDocument("n", 1);

            var operation = new FindOperation<BsonDocument>(
                chunksCollectionNamespace,
                BsonDocumentSerializer.Instance,
                messageEncoderSettings)
            {
                Filter = filter,
                Sort = sort
            };

            _cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false);
            await GetNextBatchAsync(cancellationToken).ConfigureAwait(false);
        }