public void Drop_should_drop_the_files_and_chunks_collections(
            [Values(false, true)] bool async)
        {
            var client = DriverTestConfiguration.Client;
            var database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
            var subject = new GridFSBucket(database);
            subject.UploadFromBytes("test", new byte[] { 0 }); // causes the collections to be created

            if (async)
            {
                subject.DropAsync().GetAwaiter().GetResult();
            }
            else
            {
                subject.Drop();
            }

            var collections = database.ListCollections().ToList();
            var collectionNames = collections.Select(c => c["name"].AsString);
            collectionNames.Should().NotContain("fs.files");
            collectionNames.Should().NotContain("fs.chunks");
        }
Beispiel #2
0
        public bool EditFuncionario(Funcionario funcionario, byte[] Photo, string fileName)
        {
            try
            {
                // Remove imagem antiga caso exista
                Funcionario func = _context.Funcionarios.Find(x => x.CPF == funcionario.CPF).FirstOrDefault();
                if (func != null && func.Photo != null)
                {
                    _gridFS.Delete(func.Photo);
                }

                // Adiciona nova imagem caso exista
                if (funcionario.Photo != null)
                {
                    ObjectId photoId = _gridFS.UploadFromBytes(fileName, Photo);
                    funcionario.Photo = photoId;
                }

                // Atualiza valores do funcionário no database
                ReplaceOneResult result = _context.Funcionarios.ReplaceOne(filter: f => f.CPF == funcionario.CPF, replacement: funcionario);
                return(result.IsAcknowledged && result.ModifiedCount > 0);
            }
            catch (Exception ex)
            {
                throw new Exception("Falha ao editar funcionário", ex);
            }
        }
        public void UploadImage(Image imageToUpload, string imageName)
        {
            var cardHashName = imageName.Substring(0, 4) +
                               imageName.Substring(imageName.Length - 8, 4) +
                               imageName.Substring(imageName.Length - 4, 4);

            MongoClient client = connection();
            var         db     = client.GetDatabase("CreditCardIMG");
            var         bucket = new GridFSBucket(db);
            Image       img    = imageToUpload;

            byte[] source = ImageToByteArray(img);

            if (IsImageExist(cardHashName))
            {
                var filter = Builders <GridFSFileInfo> .Filter.And(
                    Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, cardHashName));

                var options = new GridFSFindOptions
                {
                    Limit = 1
                };

                using (var cursor = bucket.Find(filter, options))
                {
                    var fileInfo = cursor.ToList().FirstOrDefault();
                    bucket.Delete(fileInfo.Id);
                    bucket.UploadFromBytes(cardHashName, source);
                }
            }
            else
            {
                bucket.UploadFromBytes(cardHashName, source);
            }
        }
 public bool SetKeyValue(string key, byte[] value)
 {
     if (BigFileMode)
     {
         var bucket = new GridFSBucket(db);               //这个是初始化gridFs存储的
         var id     = bucket.UploadFromBytes(key, value); //source字节数组
         return(!string.IsNullOrEmpty(id.ToString()));
     }
     else
     {
         try
         {
             var col = db.GetCollection <FileData>(CollectionName);
             col.InsertOne(new FileData()
             {
                 Key = key, Value = value
             });                                                         //插入一条数据
             return(true);
         }
         catch
         {
             throw;
         }
     }
 }
Beispiel #5
0
        //private  void RetrieveFromGridBucketFS()
        //{
        //    SetupMongoDb();
        //    var bucket = new GridFSBucket(mongoDb, new GridFSBucketOptions
        //    {
        //        BucketName = "pdfs",



        //    });
        //    var filesIds = mongoDb.GetCollection<DataClasses.Document>("pictures.files").Find(new BsonDocument()).ToEnumerable().Select(doc => doc.GetElement("_id").Value);

        //    foreach (var id in filesIds)
        //    {
        //        var fileBytes = bucket.DownloadAsBytes(id);
        //        fileBytes = null;
        //    }
        //}
        public DataClasses.Document SaveFilesToGridFSBinary(int numFiles, byte[] content, string fileName, DataClasses.Document document)
        {
            SetupMongoDb();
            fileName = document.UploadFilePath;
            string MongoFileId = string.Empty;

            var bucket = new GridFSBucket(mongoDb, new GridFSBucketOptions
            {
                BucketName = document.BucketName
            });

            for (int i = 0; i < numFiles; ++i)
            {
                string targetFileName = $"{fileName.Substring(0, fileName.Length - ".pdf".Length)}{i}.pdf";
                int    chunkSize      = content.Length <= 1048576 ? 51200 : 1048576;
                var    id             = bucket.UploadFromBytes(targetFileName, content, new GridFSUploadOptions {
                    ChunkSizeBytes = chunkSize
                });
                document.FileId     = "";
                document.DocumentId = id.ToString();
                //InsertMongoDBLink(document);
            }

            return(document);
        }
        /// <summary>
        /// 存储文件到FileBucket数据库
        /// </summary>
        /// <param name="filepath">本地文件</param>
        /// <param name="savename">保存到Bucket中的文件名</param>
        public void UploadFile(string filepath, string savename = null)
        {
            var fpath = filepath.Trim('"');
            var bytes = File.ReadAllBytes(fpath);

            if (string.IsNullOrEmpty(savename))
            {
                savename = Path.GetFileName(fpath);
            }
            var collection = fileInfoDB.GetCollection <BucketFileInfo>(fileInfoDbName);

            if (collection.Find(info => info.FileName.Equals(savename)).Any())
            {
                throw new GridFSException($"\'{savename}\' already exists");
            }

            var id = fsBucket.UploadFromBytes(savename, bytes);

            // 更新到FilInfo数据库
            var fileInfo = new BucketFileInfo(DateTime.UtcNow)
            {
                Id       = id,
                FileName = savename,
                FileSize = bytes.Length,
            };

            collection.InsertOne(fileInfo);
        }
        /// <summary>
        /// GridFS文件操作——上传
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileData"></param>
        /// <returns></returns>
        public ObjectId UpLoad(string fileName, byte[] fileData)
        {
            var      gridfs = new GridFSBucket(database);
            ObjectId oId    = gridfs.UploadFromBytes(fileName, fileData);

            return(oId);
        }
        private void btnQLSach_OK_Click(object sender, EventArgs e)
        {
            var db         = Module.GetDatabase("QLTHUVIEN");
            var collection = db.GetCollection <Sach>("SACH");

            Sach sachTemplate = new Sach();

            sachTemplate.tenSach   = txtQLSach_TenSach.Text;
            sachTemplate.soTrang   = Convert.ToInt32(Math.Round(nudQLSach_SoTrang.Value, 0));
            sachTemplate.giaCa     = txtQLSach_Gia.Text; //chưa xử lý kiểu tiền tệ
            sachTemplate.soLuong   = Convert.ToInt32(Math.Round(nudQLSach_SoLuong.Value, 0));
            sachTemplate.tenTacGia = cbQLSach_TenTacGia.Text;
            //sachTempte.nhaXuatBan.tenNhaXuatBan = cbQLSach_NhaXuatBan.Text; Chưa xử lý nhà xuất bản
            //chua xu ly tinh trang
            sachTemplate.theLoai  = cbQLSach_TheLoai.Text;
            sachTemplate.ngonNgu  = cbQLSach_NgonNgu.Text;
            sachTemplate.ngayNhap = dtpkQLSach_NgayNhap.Value;

            //Xử lý hình ảnh
            GridFSBucket gbucket = new GridFSBucket(db);
            var          id      = gbucket.UploadFromBytes("filename", File.ReadAllBytes(@pbQLSach_Hinh.ImageLocation));

            sachTemplate.ImageId = id;

            collection.InsertOne(sachTemplate);
            txtQLSach_TenSach.Text  = "";
            nudQLSach_SoTrang.Value = 0;
            txtQLSach_Gia.Text      = "";
            MessageBox.Show("Insert thành công");
        }
Beispiel #9
0
        private void button9_Click(object sender, EventArgs e)
        {
            FileStream     stream;
            OpenFileDialog ofd      = new OpenFileDialog();
            var            client   = new MongoClient("mongodb://localhost");
            var            database = client.GetDatabase("docs");
            var            fs       = new GridFSBucket(database);

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                stream = new System.IO.FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
                //SoundPlayer simpleSound = new SoundPlayer(stream);
                //simpleSound.Play();
                var split = ofd.SafeFileName.Split('.');
                if (split[1] != "mp3")
                {
                    MessageBox.Show("Izaberite mp3 fajl!");
                    return;
                }
                GridFSUploadOptions opcije = new GridFSUploadOptions();
                opcije.ContentType    = "audio/mp3";
                opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length) / 4;

                int    duzina  = Convert.ToInt32(stream.Length);
                byte[] bajtovi = new byte[duzina];
                stream.Seek(0, SeekOrigin.Begin);
                int bytesRead = stream.Read(bajtovi, 0, duzina);

                fs.UploadFromBytes(ofd.SafeFileName, bajtovi, opcije);
            }
        }
Beispiel #10
0
        public static bool AddSoundToGridFS(FileStream stream, string imePesme, string format)
        {
            try
            {
                var client   = new MongoClient("mongodb://localhost");
                var database = client.GetDatabase("docs");
                var fs       = new GridFSBucket(database);
                //BsonValue test = new BsonValue();
                //fs.Delete()
                GridFSUploadOptions opcije = new GridFSUploadOptions();
                opcije.ContentType    = "audio/" + format;
                opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length) / 4;

                int    duzina  = Convert.ToInt32(stream.Length);
                byte[] bajtovi = new byte[duzina];
                stream.Seek(0, SeekOrigin.Begin);
                int bytesRead = stream.Read(bajtovi, 0, duzina);

                fs.UploadFromBytes(imePesme, bajtovi, opcije);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Beispiel #11
0
        public void UploadBlob()
        {
            var bucket = new GridFSBucket(db);
            var id     = bucket.UploadFromBytes("test_blob", new byte[] { 1, 2, 3 });

            Console.WriteLine(id.ToString());
        }
Beispiel #12
0
        private void button8_Click(object sender, EventArgs e)
        {
            Image          slika;
            FileStream     stream;
            var            client   = new MongoClient("mongodb://localhost");
            var            database = client.GetDatabase("docs");
            var            fs       = new GridFSBucket(database);
            OpenFileDialog ofd      = new OpenFileDialog();

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                stream = new System.IO.FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
                slika  = Image.FromStream(stream);

                GridFSUploadOptions opcije = new GridFSUploadOptions();
                opcije.ContentType    = "image/jpg";
                opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length);

                int    duzina  = Convert.ToInt32(stream.Length);
                byte[] bajtovi = new byte[duzina];
                stream.Seek(0, SeekOrigin.Begin);
                int bytesRead = stream.Read(bajtovi, 0, duzina);

                fs.UploadFromBytes("Test", bajtovi, opcije);
            }
            MessageBox.Show("done");
        }
Beispiel #13
0
        private static ObjectId UploadFile(GridFSBucket fs, string path)
        {
            var fileName = Path.GetFileName(path);
            var file     = File.ReadAllBytes(Path.GetFullPath(path));

            return(fs.UploadFromBytes(fileName, file));
        }
Beispiel #14
0
        public string Upload(string fileName, byte[] content)
        {
            var fs = new GridFSBucket(_context.Database);
            var id = fs.UploadFromBytes(fileName, content);

            return(id.ToString());
        }
        public ObjectId UploadFromBytes(byte[] source, string fileName, GridFSUploadOptions options = null)
        {
            MongoClient client = GetClient(m_connectionStr);
            var         db     = client.GetDatabase(DatabaseName);
            var         bucket = new GridFSBucket(db, BucksOptions);

            return(bucket.UploadFromBytes(fileName, source, options));
        }
Beispiel #16
0
        public MongoDB.Bson.ObjectId AttachFile(byte[] source)
        {
            var bucket = new GridFSBucket(getDatabase());
            //var id = bucket.UploadFromStream("filename", source);
            var id = bucket.UploadFromBytes("filename", source);

            return(id);
        }
Beispiel #17
0
        /// <summary>
        /// Used to send image to gridFS of database
        /// </summary>
        /// <param name="img">image source</param>
        /// <param name="name">name of the file</param>
        /// <returns>Id pointing to a new img</returns>
        public ObjectId SendImage(Image img, string name)
        {
            var      bytes  = converterDemo(img);
            var      bucket = new GridFSBucket(db);
            ObjectId id     = bucket.UploadFromBytes(name, bytes);

            return(id);
        }
        public Task <ObjectId> SavePdf(string file, byte[] data, MetaData metaData)
        {
            var gridFsBucket = new GridFSBucket(_database);

            var tsk = Task.Run(() => gridFsBucket.UploadFromBytes(file, data, new GridFSUploadOptions()
            {
                Metadata = metaData.ToBsonDocument()
            }));

            return(tsk);
        }
Beispiel #19
0
        public void Store(Guid id, byte[] imageData)
        {
            var database = GetDatabase();

            var fileStorage = new GridFSBucket(database, new GridFSBucketOptions
            {
                BucketName = "images"
            });

            fileStorage.UploadFromBytes(id.ToString(), imageData);
        }
        public void SetDocument(Document document)
        {
            var bson = new BsonDocument((Dictionary <string, string>)document.Metadata.Data);

            bson.Add(IdKey, document.Key);

            metadataCollection.ReplaceOne($"{{{IdKey}: '{document.Key}'}}", bson, new UpdateOptions {
                IsUpsert = true
            });
            fileBucket.UploadFromBytes(document.Key, document.Binary);
        }
        public static void UploadFile()
        {
            var database = DatabaseHelper.GetDatabaseReference("localhost", "file_store");

            IGridFSBucket bucket = new GridFSBucket(database);

            byte[] source = File.ReadAllBytes("sample.pdf");

            var id = bucket.UploadFromBytes("sample.pdf", source);

            Console.WriteLine(id.ToString());
        }
        public MongoGridFsProviderTest()
        {
            _runner = MongoDbRunner.Start();
            _mongoClientSettings = MongoClientSettings.FromConnectionString(_runner.ConnectionString);

            _client = new MongoClient(_mongoClientSettings);
            _db     = _client.GetDatabase("foo");

            // Create db and gridfs collections
            var bucket   = new GridFSBucket(_db);
            var createDb = bucket.UploadFromBytes("someData", new byte[1]);
        }
Beispiel #23
0
        public static bool AddImageToGridFS(Image slika, string imeSlike, string format)
        {
            try
            {
                //provera da li postoji slika
                //var client = new MongoClient("mongodb://localhost");
                //var database = client.GetDatabase("docs");
                //var fs = new GridFSBucket(database);

                //var test = fs.DownloadAsBytesByName(imeSlike);


                byte[]       data;
                MemoryStream stream = new MemoryStream();


                slika.Save(stream, slika.RawFormat);
                data = stream.ToArray();

                //string host = "localhost";
                //int port = 27017;
                //string databaseName = "docs";

                //var _client = new MongoClient();
                // var _database = (MongoDatabase)_client.GetDatabase("docs");

                var client   = new MongoClient("mongodb://localhost");
                var database = client.GetDatabase("docs");
                var fs       = new GridFSBucket(database);
                GridFSUploadOptions opcije = new GridFSUploadOptions();

                opcije.ContentType    = "image/" + format;
                opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length) / 4;

                fs.UploadFromBytes(imeSlike, data, opcije);

                //var grid = new MongoGridFS(new MongoServer(new MongoServerSettings { Server = new MongoServerAddress(host, port) }), databaseName, new MongoGridFSSettings());

                // grid.Upload(m, imeSlike, new MongoGridFSCreateOptions
                //{
                //Id = 1,
                //     ContentType = "image/"+format
                // });

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
        public void TestGetChildItem()
        {
            // Arrange
            var bucket = new GridFSBucket(_db);
            var id1    = bucket.UploadFromBytes(ObjectId.GenerateNewId().ToString(), new byte[1]);
            var id2    = bucket.UploadFromBytes(ObjectId.GenerateNewId().ToString(), new byte[1]);
            var id3    = bucket.UploadFromBytes(ObjectId.GenerateNewId().ToString(), new byte[1]);
            var ps     = CreatePowerShell();

            // Act
            var result = ps.AddCommand("Get-ChildItem")
                         .AddParameter("Path", "mongodb:")
                         .Invoke();

            // Assert
            result.Should().NotBeNull();

            result.Cast <PSObject>()
            .Select(x => x.ImmediateBaseObject)
            .Should().AllBeOfType <GridFSFileInfo>()
            .And.Subject.Cast <GridFSFileInfo>().Select(x => x.Id).Should().Contain(new[] { id1, id2, id3 });
        }
Beispiel #25
0
        public string CreateImage(string id, byte[] bytes)
        {
            var bucket = new GridFSBucket(db, new GridFSBucketOptions
            {
                BucketName = "CourseImages"
            });

            Course course = courses.Find(u => u.Id == id).FirstOrDefault();

            ObjectId bid = bucket.UploadFromBytes(course.Name, bytes);

            return(bid.ToString());
        }
Beispiel #26
0
 public void UploadImageToGridFS(string imageFileName, byte[] bytes)
 {
     try
     {
         GridFSUploadOptions options = new GridFSUploadOptions();
         options.ChunkSizeBytes = 24 * 1024;
         mGridFSBucket.UploadFromBytes(imageFileName, bytes, options);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
        public string CreateImage(string id, byte[] bytes)
        {
            var bucket = new GridFSBucket(db, new GridFSBucketOptions
            {
                BucketName = "UniversityImages",
            });

            University universidad = universidades.Find(u => u.Id == id).FirstOrDefault();

            ObjectId bid = bucket.UploadFromBytes(universidad.Name, bytes);

            return(bid.ToString());
        }
Beispiel #28
0
        public ObjectId InserirImagem(string nome, byte[] conteudo)
        {
            var bucket = new GridFSBucket(database, new GridFSBucketOptions {
                BucketName = "imagens",
                //ChunkSizeBytes = 1048576, 1MB
                WriteConcern   = WriteConcern.WMajority,
                ReadPreference = ReadPreference.Secondary
            });
            var id = bucket.UploadFromBytes(nome, conteudo);

            return(id);
            //result = Convert.ToByte(number);
        }
Beispiel #29
0
        public bool Insert(WallpaperData data)
        {
            var options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument
                {
                    { WALLPAPER_ID_FIELD_NAME, data.WallpaperId }
                }
            };

            _fs.UploadFromBytes(data.Id, data.Id.ToString(), data.Data, options);

            return(true);
        }
Beispiel #30
0
        public void GetTest(MongoDatabaseFactory factory, byte[] data)
        {
            var gridFsBucket = new GridFSBucket(factory.GetDatabase());
            var key          = gridFsBucket.UploadFromBytes(Guid.NewGuid().ToString(), data);

            var sut          = new MongoGridFSDataBus(factory);
            var resultStream = sut.Get(key.ToString()).Result;

            var result = new byte[data.Length];

            resultStream.Read(result, 0, data.Length);

            resultStream.Length.Should().Be(data.Length);
            result.Should().BeEquivalentTo(data);
        }
Beispiel #31
0
        public IActionResult Post()
        {
            var           database = _client.GetDatabase("UploadDB");
            GridFSBucket  g        = new GridFSBucket(database);
            List <string> result   = new List <string>();
            var           files    = Request.Form.Files;

            foreach (var file in files)
            {
                var bytes = new byte[file.Length];
                file.OpenReadStream().Read(bytes, 0, bytes.Length);
                result.Add($"api/files/{g.UploadFromBytes(file.FileName, bytes)}?name={file.FileName}");
            }
            return(Ok(new { result = string.Join(",", result) }));
        }
 // protected methods
 protected ObjectId InvokeMethod(GridFSBucket bucket)
 {
     return bucket.UploadFromBytes(_filename, _source, _options);
 }