Esempio n. 1
0
        public void BackingDocument_get_should_return_the_expected_result()
        {
            var backingDocument = new BsonDocument("x", 1);
            var subject = new GridFSFileInfo(backingDocument);

            var result = subject.BackingDocument;

            result.Should().BeSameAs(backingDocument);
        }
        public void constructor_should_initialize_instance()
        {
            var database = Substitute.For<IMongoDatabase>();
            var bucket = new GridFSBucket(database);
            var binding = Substitute.For<IReadBinding>();
            var fileInfo = new GridFSFileInfo(new BsonDocument());

            var result = new GridFSSeekableDownloadStream(bucket, binding, fileInfo);

            result.Position.Should().Be(0);
            result._chunk().Should().BeNull();
            result._n().Should().Be(-1);
        }
        public void DownLoad <T>(Expression <Func <T, bool> > where, string saveFile) where T : IMetaEntity, new()
        {
            Excute(() =>
            {
                var entity = GetCollection <T>().AsQueryable().Where(where).Select(p => p).FirstOrDefault();
                if (entity == null)
                {
                    throw new FileNotFoundException("文件不存在。");
                }
                using (var stream = new FileStream(saveFile, FileMode.OpenOrCreate))
                {
                    var gridfs          = GetGridFSForEntity(entity);
                    GridFSFileInfo info = CheckGridFsFileExists(gridfs, entity.Id);

                    gridfs.DownloadToStream(info.Id, stream);
                }
            });
        }
Esempio n. 4
0
        public async Task <String> GetFileInfo(string id)
        {
            GridFSFileInfo info     = null;
            var            objectId = new ObjectId(id);

            try
            {
                using (var stream = await _context.Bucket.OpenDownloadStreamAsync(objectId))
                {
                    info = stream.FileInfo;
                }
                return(info.Filename);
            }
            catch (Exception)
            {
                return("Not Found");
            }
        }
        public Stream DownLoad <T>(Expression <Func <T, bool> > where) where T : IMetaEntity, new()
        {
            return(Excute(() =>
            {
                var entity = GetCollection <T>().AsQueryable().Where(where).Select(p => p).FirstOrDefault();
                if (entity == null)
                {
                    throw new FileNotFoundException("文件不存在。");
                }
                var stream = new MemoryStream();

                var gridfs = GetGridFSForEntity(entity);
                GridFSFileInfo info = CheckGridFsFileExists(gridfs, entity.Id);

                gridfs.DownloadToStream(info.Id, stream);
                stream.Position = 0;
                return stream;
            }));
        }
Esempio n. 6
0
        private static string GetContentType(GridFSFileInfo fileInfo, IDictionary <string, object> dictionary)
        {
            var contentType = fileInfo.ContentType;

            if (dictionary.TryGetValue("contentType", out object value))
            {
                contentType = (string)value;
            }
            else if (dictionary.TryGetValue("Content-Type", out value))
            {
                contentType = (string)value;
            }
            else if (dictionary.TryGetValue("ContentType", out value))
            {
                contentType = (string)value;
            }

            return(contentType);
        }
Esempio n. 7
0
        private static string GetContentType(GridFSFileInfo fileInfo, IDictionary <string, object> dictionary)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var contentType = fileInfo.ContentType;
#pragma warning restore CS0618 // Type or member is obsolete
            if (dictionary.TryGetValue("contentType", out object value))
            {
                contentType = (string)value;
            }
            else if (dictionary.TryGetValue("Content-Type", out value))
            {
                contentType = (string)value;
            }
            else if (dictionary.TryGetValue("ContentType", out value))
            {
                contentType = (string)value;
            }

            return(contentType);
        }
Esempio n. 8
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="condition">下载字典条件</param>
        /// <returns>返回下载流数据</returns>
        void DownLoad <T>(IDictionary <string, object> condition, Stream stream) where T : IMetaEntity, new()
        {
            if (condition == null || condition.Count == 0)
            {
                throw new InfrastructureException("条件condition不能为null或键数据为0。");
            }

            var query  = ConvertDictionaryToFilterDefinition <T>(DictionaryWarp(condition));
            var entity = GetCollection <T>().Find(query).FirstOrDefault();

            if (entity == null)
            {
                throw new FileNotFoundException();
            }
            var            gridfs = GetGridFSForEntity(entity);
            GridFSFileInfo info   = CheckGridFsFileExists(gridfs, entity.Id);


            gridfs.DownloadToStream(info.Id, stream);
        }
Esempio n. 9
0
        /// <summary>
        /// 查询文件
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public GridFSFileInfo FindFiles(string filename)
        {
            var filter = Builders <GridFSFileInfo> .Filter.And(
                Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, "man"),
                Builders <GridFSFileInfo> .Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
                Builders <GridFSFileInfo> .Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));

            var sort = Builders <GridFSFileInfo> .Sort.Descending(x => x.UploadDateTime);

            var options = new GridFSFindOptions
            {
                Limit = 1,
                Sort  = sort
            };

            using (var cursor = bucket.Find(filter, options))
            {
                fileInfo = cursor.ToList().FirstOrDefault();
            }
            return(fileInfo);
        }
Esempio n. 10
0
        public void constructor_should_initialize_instance()
        {
#pragma warning disable 618
            var aliases        = new[] { "alias" };
            var chunkSizeBytes = 1024;
            var contentType    = "type";
            var extraElements  = new BsonDocument();
            var filename       = "name";
            var id             = ObjectId.GenerateNewId();
            var idAsBsonValue  = (BsonValue)id;
            var length         = 512;
            var md5            = "md5";
            var metadata       = new BsonDocument();
            var uploadDateTime = DateTime.UtcNow;

            var result = new GridFSFileInfo(
                aliases,
                chunkSizeBytes,
                contentType,
                extraElements,
                filename,
                idAsBsonValue,
                length,
                md5,
                metadata,
                uploadDateTime);

            result.Aliases.Should().BeSameAs(aliases);
            result.ChunkSizeBytes.Should().Be(chunkSizeBytes);
            result.ContentType.Should().Be(contentType);
            result.ExtraElements.Should().Be(extraElements);
            result.Filename.Should().Be(filename);
            result.Id.Should().Be(id);
            result.IdAsBsonValue.Should().Be(idAsBsonValue);
            result.Length.Should().Be(length);
            result.MD5.Should().Be(md5);
            result.Metadata.Should().Be(metadata);
            result.UploadDateTime.Should().Be(uploadDateTime);
#pragma warning restore
        }
Esempio n. 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Task <ObjectId> UploadFromBytes(string fileName, byte[] source)
        {
            //构建查询,用于检查是否已存在
            FilterDefinition <GridFSFileInfo> filter = Builders <GridFSFileInfo> .Filter.And(
                Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, fileName)
                //Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
                );

            //排序规则
            SortDefinition <GridFSFileInfo> sort = Builders <GridFSFileInfo> .Sort.Descending(x => x.UploadDateTime);

            //查找限制,提高处理速度
            GridFSFindOptions options = new GridFSFindOptions {
                Limit = 1,
                Sort  = sort
            };

            using (var cursor = bucket.Find(filter, options))
            {
                GridFSFileInfo fileInfo = cursor.ToList().FirstOrDefault();
                return(fileInfo == null?Task.FromResult(bucket.UploadFromBytesAsync(fileName, source).Result) : Task.FromResult(fileInfo.Id));
            }
        }
Esempio n. 12
0
        private async void downloadAndViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GridFSFileInfo item = GetSelectedItem();

            if (item == null)
            {
                return;
            }
            try
            {
                // string fileResult = Task.Run(() => DownloadFileAsync(item)).GetAwaiter().GetResult();
                // var result = Task.Run(() => DownloadFileAsync(item));
                var result = await DownloadFileAsync(item);

                if (!string.IsNullOrEmpty(result))
                {
                    ProgramUI.OpenJson(result);
                }
            }
            catch (Exception ex)
            {
                Logger.Log("***GridFS Error " + ex.Message);
            }
        }
        public void Length_should_return_expected_result()
        {
            var length = 123;
            var fileInfo = new GridFSFileInfo(new BsonDocument("length", length));
            var subject = CreateSubject(fileInfo: fileInfo);

            var result = subject.Length;

            result.Should().Be(length);
        }
        private GridFSSeekableDownloadStream CreateSubject(long? length = null)
        {
            var database = Substitute.For<IMongoDatabase>();
            var bucket = new GridFSBucket(database);
            var binding = Substitute.For<IReadBinding>();
            var fileInfoDocument = new BsonDocument
            {
                { "length", () => length.Value, length.HasValue }
            };
            var fileInfo = new GridFSFileInfo(fileInfoDocument);

            return new GridFSSeekableDownloadStream(bucket, binding, fileInfo);
        }
Esempio n. 15
0
 public FakeGridFSDownloadStream(GridFSBucket <ObjectId> bucket, IReadBinding binding, GridFSFileInfo <ObjectId> fileInfo)
     : base(bucket, binding, fileInfo)
 {
 }
Esempio n. 16
0
 public GridFSFolderStorage(IGridFSBucket bucket, GridFSFileInfo fileInfo)
 {
     _fileInfo = fileInfo;
     _bucket   = bucket;
 }
Esempio n. 17
0
        public void constructor_should_initialize_instance()
        {
            var backdocument = new BsonDocument();

            var result = new GridFSFileInfo(backdocument);

            result.BackingDocument.Should().BeSameAs(backdocument);
        }
Esempio n. 18
0
 internal static FileInfo ToFileInfo(this GridFSFileInfo info)
 {
     return(new FileInfo(info.Filename, info.Length, info.UploadDateTime));
 }
        private GridFSDownloadStreamBase CreateSubject(GridFSFileInfo fileInfo = null)
        {
            var database = Substitute.For<IMongoDatabase>();
            var bucket = new GridFSBucket(database);
            var binding = Substitute.For<IReadBinding>();
            fileInfo = fileInfo ?? new GridFSFileInfo(new BsonDocument());

            return new FakeGridFSDownloadStream(bucket, binding, fileInfo);
        }
        public void FileInfo_should_return_expected_result()
        {
            var fileInfo = new GridFSFileInfo(new BsonDocument());
            var subject = CreateSubject(fileInfo: fileInfo);

            var result = subject.FileInfo;

            result.Should().Be(fileInfo);
        }
Esempio n. 21
0
 public MongoDBStoreEntry(string path, GridFSFileInfo fileInfo)
 {
     _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo));
     _path     = path ?? throw new ArgumentNullException(nameof(path));
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            // or use a connection string
            var client = new MongoClient("mongodb://localhost:27017");
            //Get a Database
            var database = client.GetDatabase("foo");
            //Get a Collection
            var collection = database.GetCollection <BsonDocument>("bar");


            //        var document = new BsonDocument
            //                           {
            //{ "name", "MongoDB" },
            //{ "type", "Database" },
            //{ "count", 1 },
            //{ "info", new BsonDocument
            //    {
            //        { "x", 203 },
            //        { "y", 102 }
            //    }}
            //};
            //            collection.InsertOne(document);

            //            var documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i));
            //            collection.InsertMany(documents);

            //Counting Documents
            var count = collection.CountDocuments(new BsonDocument());

            Console.WriteLine("文档个数:" + count.ToString());

            //Find the First Document in a Collection
            var documentNew = collection.Find(new BsonDocument()).FirstOrDefault();

            Console.WriteLine(documentNew.ToString());

            //Find All Documents in a Collection
            var documents = collection.Find(new BsonDocument()).ToList();

            foreach (var d in documents)
            {
                Console.WriteLine(d);
            }
            //var cursor = collection.Find(new BsonDocument()).ToCursor();
            //foreach (var document in cursor.ToEnumerable())
            //{
            //    Console.WriteLine(document);
            //}

            //Get a Single Document with a Filter
            var filter = Builders <BsonDocument> .Filter.Eq("counter", 71);

            var document = collection.Find(filter).First();

            Console.WriteLine(document);
            var filter2 = Builders <BsonDocument> .Filter.Gt("counter", 50);

            var cursor = collection.Find(filter2).ToCursor();

            foreach (var d in cursor.ToEnumerable())
            {
                Console.WriteLine(d);
            }

            //Updating Documents
            var filter6 = Builders <BsonDocument> .Filter.Eq("counter", 10);

            var update6 = Builders <BsonDocument> .Update.Set("counter", 110);

            var result6 = collection.UpdateOne(filter6, update6);

            var filter7 = Builders <BsonDocument> .Filter.Lt("counter", 100);

            var update7 = Builders <BsonDocument> .Update.Inc("counter", 100);

            var result = collection.UpdateMany(filter7, update7);

            if (result.IsModifiedCountAvailable)
            {
                Console.WriteLine(result.ModifiedCount);
            }

            //Deleting Documents
            var filter8 = Builders <BsonDocument> .Filter.Eq("counter", 110);

            collection.DeleteOne(filter8);

            var filter9 = Builders <BsonDocument> .Filter.Gte("counter", 100);

            var result9 = collection.DeleteMany(filter9);

            Console.WriteLine(result9.DeletedCount);

            //Bulk Writes
            var models = new WriteModel <BsonDocument>[]
            {
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 4)),
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 5)),
                new InsertOneModel <BsonDocument>(new BsonDocument("_id", 6)),
                new UpdateOneModel <BsonDocument>(
                    new BsonDocument("_id", 1),
                    new BsonDocument("$set", new BsonDocument("x", 2))),
                new DeleteOneModel <BsonDocument>(new BsonDocument("_id", 3)),
                new ReplaceOneModel <BsonDocument>(
                    new BsonDocument("_id", 3),
                    new BsonDocument("_id", 3).Add("x", 4))
            };

            // 1. Ordered bulk operation - order of operation is guaranteed
            collection.BulkWrite(models);

            // 2. Unordered bulk operation - no guarantee of order of operation
            collection.BulkWrite(models, new BulkWriteOptions {
                IsOrdered = false
            });

            Console.Read();

            GridFSHelper helper = new GridFSHelper("mongodb://localhost:27017", "GridFSDemo", "Pictures");

            #region   图片

            Image    image2 = Image.FromFile("D:\\man.png");
            var      stream = image2.ImageToStream();
            ObjectId oid2   = helper.UploadGridFSFromStream("man", stream);
            Console.WriteLine(oid2.ToString());

            Image    image   = Image.FromFile("D:\\dog.jpg");
            byte[]   imgdata = image.ImageToBytes();
            ObjectId oid     = helper.UploadGridFSFromBytes("dog", imgdata);
            Console.WriteLine(oid.ToString());

            #endregion

            #region  载图片

            //第一种
            var ms = helper.DownloadToStream(oid2);
            Image.FromStream(ms).Save("d:\\aaa.jpg");

            //第二种
            byte[] Downdata = helper.DownloadAsByteArray(oid);
            var    img      = Downdata.BytesToImage();
            img.Save("D:\\qqqq.jpg");

            #endregion

            #region 查找图片
            GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");
            Console.WriteLine(gridFsFileInfo.Id);
            #endregion

            #region  除图片
            //helper.DroppGridFSBucket();
            #endregion

            Console.ReadKey();
        }
Esempio n. 23
0
 public GridFsBlobInfo(GridFSFileInfo <Guid> fileInfo)
 {
     _fileInfo = fileInfo;
 }
        public void constructor_should_initialize_instance()
        {
#pragma warning disable 618
            var aliases = new[] { "alias" };
            var chunkSizeBytes = 1024;
            var contentType = "type";
            var extraElements = new BsonDocument();
            var filename = "name";
            var id = ObjectId.GenerateNewId();
            var idAsBsonValue = (BsonValue)id;
            var length = 512;
            var md5 = "md5";
            var metadata = new BsonDocument();
            var uploadDateTime = DateTime.UtcNow;

            var result = new GridFSFileInfo(
                aliases,
                chunkSizeBytes,
                contentType,
                extraElements,
                filename,
                idAsBsonValue,
                length,
                md5,
                metadata,
                uploadDateTime);

            result.Aliases.Should().BeSameAs(aliases);
            result.ChunkSizeBytes.Should().Be(chunkSizeBytes);
            result.ContentType.Should().Be(contentType);
            result.ExtraElements.Should().Be(extraElements);
            result.Filename.Should().Be(filename);
            result.Id.Should().Be(id);
            result.IdAsBsonValue.Should().Be(idAsBsonValue);
            result.Length.Should().Be(length);
            result.MD5.Should().Be(md5);
            result.Metadata.Should().Be(metadata);
            result.UploadDateTime.Should().Be(uploadDateTime);
#pragma warning restore
        }
Esempio n. 25
0
 public GridFSFileStorage(GridFSFileInfo fileInfo, IGridFSBucket bucket)
 {
     _bucket   = bucket;
     _fileInfo = fileInfo;
 }
        public void constructor_should_initialize_instance()
        {
            var database = Substitute.For<IMongoDatabase>();
            var bucket = new GridFSBucket(database);
            var binding = Substitute.For<IReadBinding>();
            var fileInfo = new GridFSFileInfo(new BsonDocument());

            var result = new FakeGridFSDownloadStream(bucket, binding, fileInfo);

            result.FileInfo.Should().Be(fileInfo);
            result._binding().Should().Be(binding);
            result._bucket().Should().Be(bucket);
            result._disposed().Should().BeFalse();
        }
 public FakeGridFSDownloadStream(GridFSBucket bucket, IReadBinding binding, GridFSFileInfo fileInfo)
     : base(bucket, binding, fileInfo)
 {
 }