Example #1
1
        public async Task<bool> FileExistsAsync(string gfsname, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });
            
            var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, gfsname);
            var fileInfo = await bucket.FindAsync(filter);

            return fileInfo.Any();
        }
Example #2
0
        /// <summary>
        /// 将数据库数据还原为文件
        /// </summary>
        /// <param name="DatabaseName"></param>
        /// <param name="id"></param>
        /// <param name="FilePath"></param>
        /// <param name="GridFSName"></param>
        public void DownloadFile(String DatabaseName, String id, String FilePath, String GridFSName = "")
        {
            if (conn == null)
            {
                throw new Exception("Connection has not initialize.");
            }

            if (DatabaseName.Length == 0)
            {
                throw new Exception("Database Name is invalid.");
            }

            IMongoDatabase database = conn.GetDatabase(DatabaseName);

            MongoDB.Driver.GridFS.GridFSBucket bucket;
            if (String.IsNullOrEmpty(GridFSName))
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database);
            }
            else
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database, new GridFSBucketOptions {
                    BucketName = GridFSName
                });
            }
            Byte[] s = bucket.DownloadAsBytes(new ObjectId(id));

            File.WriteAllBytes(FilePath, s);

            return;
        }
Example #3
0
        public MongoStorage()
        {
            var client = new MongoClient(ConfigurationManager.AppSettings["Storage.ConnectionString"]);

            var database = client.GetDatabase("salusdb");
            this.gridFs = new GridFSBucket(database);
        }
Example #4
0
 public async Task<GridFSFileInfo> GetBigFire(string fileId)
 {
     var bucket = new GridFSBucket(Client.GetDatabase(BigDataFireDBName));
     var filter = Builders<GridFSFileInfo>.Filter.Eq(f => f.Filename, fileId);
     var fires = await (await bucket.FindAsync(filter)).ToListAsync();
     return fires.First();
 }
        private static GridFSBucket GetGridFsBucket()
        {
            var db = new MongoClient().GetDatabase("document");

            var gridFsBucket = new GridFSBucket(db);
            return gridFsBucket;
        }
        public void GivenAMongoMessageDataRepository_WhenPuttingMessageDataWithExpiration()
        {
            var db = new MongoClient().GetDatabase("messagedatastoretests");
            _bucket = new GridFSBucket(db);

            _now = DateTime.UtcNow;
            SystemDateTime.Set(_now);

            var fixture = new Fixture();

            var resolver = new Mock<IMongoMessageUriResolver>();
            resolver.Setup(x => x.Resolve(It.IsAny<ObjectId>()))
                .Callback((ObjectId id) => _id = id);

            var nameCreator = new Mock<IFileNameCreator>();
            nameCreator.Setup(x => x.CreateFileName())
                .Returns(fixture.Create<string>());
            
            var sut = new MongoMessageDataRepository(resolver.Object, _bucket, nameCreator.Object);
            _expectedTtl = TimeSpan.FromHours(1);

            using (var stream = new MemoryStream(fixture.Create<byte[]>()))
            {
                sut.Put(stream, _expectedTtl).GetAwaiter().GetResult();
            }
        }
Example #7
0
        private void button10_Click(object sender, EventArgs e)
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("docs");
            var fs = new GridFSBucket(database);

            //var aaa = fs.Find()
            var test = fs.DownloadAsBytesByName("Muzika");

            MemoryStream memStream = new MemoryStream(test);

            //OpenFileDialog open = new OpenFileDialog();
            //open.Filter = "Audio File (*.mp3;*.wav)|*.mp3;*.wav;";
            //if (open.ShowDialog() != DialogResult.OK) return;

            DisposeWave();

               // if (open.FileName.EndsWith(".mp3"))
               // {
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(memStream));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
               // }
               // else if (open.FileName.EndsWith(".wav"))
            //{
            //    NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName));
            //    stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            //}
            //else throw new InvalidOperationException("Not a correct audio file type.");

            output = new NAudio.Wave.DirectSoundOut();
            output.Init(stream);
            output.Play();
        }
 // constructors
 public GridFSSeekableDownloadStream(
     GridFSBucket bucket,
     IReadBinding binding,
     GridFSFileInfo fileInfo)
     : base(bucket, binding, fileInfo)
 {
 }
 // constructors
 public GridFSSeekableDownloadStream(
     GridFSBucket bucket,
     IReadBinding binding,
     GridFSFilesCollectionDocument filesCollectionDocument)
     : base(bucket, binding, filesCollectionDocument)
 {
 }
        public async Task<ActionResult> EditPhoto(HttpPostedFileBase profilePhotoUser, string usernamePhoto)
        {
            if (profilePhotoUser != null)
            {
                if (profilePhotoUser.ContentLength > 0)
                {
                    GridFSBucketOptions bucketOptions = new GridFSBucketOptions() { BucketName = "ProfileImages" };
                    var fs = new GridFSBucket(KonradRequirementsDatabase, bucketOptions);

                    // getting filename
                    string fileName = Path.GetFileName(profilePhotoUser.FileName);

                    //get the bytes from the content stream of the file
                    byte[] pictureBytes = new byte[profilePhotoUser.ContentLength];
                    using (BinaryReader theReader = new BinaryReader(profilePhotoUser.InputStream))
                    {
                        pictureBytes = theReader.ReadBytes(profilePhotoUser.ContentLength);
                    }
                    
                    // Saving picture
                    var objectId = await fs.UploadFromBytesAsync(fileName, pictureBytes);

                    var filter = Builders<BsonDocument>.Filter.Eq("Username", usernamePhoto);

                    var update = Builders<BsonDocument>.Update
                    .Set("ProfileImageName", fileName);

                    var result = await usersCollection.UpdateOneAsync(filter, update);

                    return RedirectToAction("MyProfile", new { ReLogin = true, result = result });
                }
            }
            return null;
        }
Example #11
0
        /// <summary>
        /// 删除文件库
        /// </summary>
        /// <param name="DatabaseName"></param>
        /// <param name="GridFSName"></param>
        public void DeleteGridFS(String DatabaseName, String GridFSName = "")
        {
            if (conn == null)
            {
                throw new Exception("Connection has not initialize.");
            }

            if (DatabaseName.Length == 0)
            {
                throw new Exception("Database Name is invalid.");
            }

            IMongoDatabase database = conn.GetDatabase(DatabaseName);

            MongoDB.Driver.GridFS.GridFSBucket bucket;
            if (String.IsNullOrEmpty(GridFSName))
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database);
            }
            else
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database, new GridFSBucketOptions {
                    BucketName = GridFSName
                });
            }
            bucket.Drop();

            return;
        }
Example #12
0
        /// <summary>
        /// 将文件写入数据库
        /// </summary>
        /// <param name="DatabaseName"></param>
        /// <param name="FilePath"></param>
        /// <param name="GridFSName"></param>
        /// <returns></returns>
        public String UploadFile(String DatabaseName, String FilePath, String GridFSName = "")
        {
            if (conn == null)
            {
                throw new Exception("Connection has not initialize.");
            }

            if (DatabaseName.Length == 0)
            {
                throw new Exception("Database Name is invalid.");
            }

            if (File.Exists(FilePath) == false)
            {
                throw new Exception("File path is not exist.");
            }

            IMongoDatabase database = conn.GetDatabase(DatabaseName);

            MongoDB.Driver.GridFS.GridFSBucket bucket;
            if (String.IsNullOrEmpty(GridFSName))
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database);
            }
            else
            {
                bucket = new MongoDB.Driver.GridFS.GridFSBucket(database, new GridFSBucketOptions {
                    BucketName = GridFSName
                });
            }
            ObjectId id = bucket.UploadFromBytes(Path.GetFileName(FilePath), File.ReadAllBytes(FilePath));

            return(id.ToString());
        }
Example #13
0
        public async Task DownloadToStreamByNameAsync(string gfsname, Stream source, MediaTypeEnum bucketName) {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            await bucket.DownloadToStreamByNameAsync(gfsname, source);
        }
Example #14
0
        public async Task<GridFSDownloadStream> OpenDownloadStreamAsync(ObjectId id, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            return await bucket.OpenDownloadStreamAsync(id);
        }
Example #15
0
 public async Task DownloadToStreamAsync(ObjectId id, Stream source, MediaTypeEnum bucketName)
 {
     var bucket = new GridFSBucket(_db, new GridFSBucketOptions
     {
         BucketName = bucketName.ToString()
     });
     
     await bucket.DownloadToStreamAsync(id, source);
 }
Example #16
0
        public async Task<GridFSDownloadStream> OpenDownloadStreamByNameAsync(string name, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            return await bucket.OpenDownloadStreamByNameAsync(name);
        }
 // constructors
 protected GridFSDownloadStreamBase(
     GridFSBucket bucket,
     IReadBinding binding,
     GridFSFileInfo fileInfo)
 {
     _bucket = bucket;
     _binding = binding;
     _fileInfo = fileInfo;
 }
 // constructors
 protected GridFSDownloadStreamBase(
     GridFSBucket bucket,
     IReadBinding binding,
     GridFSFilesCollectionDocument filesCollectionDocument)
 {
     _bucket = bucket;
     _binding = binding;
     _filesCollectionDocument = filesCollectionDocument;
 }
Example #19
0
        public async Task<byte[]> DownloadAsBytesAsync(ObjectId id, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            return await bucket.DownloadAsBytesAsync(id);
        }
Example #20
0
        public async Task<ObjectId> UploadFromStreamAsync(string gfsname, Stream source,string filename, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions {
                BucketName = bucketName.ToString()
            });

            var options = new GridFSUploadOptions {
                Metadata = new BsonDocument {
                    { "filename", filename },
                    { "contentType", MimeMapping.GetMimeMapping(filename) }
                }
            };

            return await bucket.UploadFromStreamAsync(gfsname, source, options);
        }
        public void GivenAMongoMessageDataRepository_WhenPuttingMessageData()
        {
            var db = new MongoClient().GetDatabase("messagedatastoretests");
            _bucket = new GridFSBucket(db);

            _expectedData = Encoding.UTF8.GetBytes("This is a test message data block");

            _resolver = new MessageDataResolver();
            _nameCreator = new StaticFileNameGenerator();
            _filename = _nameCreator.GenerateFileName();

            IMessageDataRepository repository = new MongoDbMessageDataRepository(_resolver, _bucket, _nameCreator);

            using (var stream = new MemoryStream(_expectedData))
            {
                _actualUri = repository.Put(stream).GetAwaiter().GetResult();

            }
        }
        public void GivenAMongoMessageDataRepository_WhenGettingMessageData()
        {
            var db = new MongoClient().GetDatabase("messagedatastoretests");
            _bucket = new GridFSBucket(db);

            var fixture = new Fixture();
            _expected = fixture.Create<byte[]>();
            _uri = fixture.Create<Uri>();

            var objectId = SeedBucket(_expected).GetAwaiter().GetResult();
            _resolver = new Mock<IMongoMessageUriResolver>();
            _resolver.Setup(m => m.Resolve(_uri)).Returns(objectId);

            var nameCreator = new Mock<IFileNameCreator>();
            nameCreator.Setup(m => m.CreateFileName()).Returns(fixture.Create<string>());

            var sut = new MongoMessageDataRepository(_resolver.Object, _bucket, nameCreator.Object);
            _result = sut.Get(_uri).GetAwaiter().GetResult();
        }
Example #23
0
        internal ImageDataAccess()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            Database = client.GetDatabase("v2");
            Collection = Database.GetCollection<Image>("Images");
            GridFs = new GridFSBucket(Database);

            var fs = new FileStream("config.json", FileMode.Open, FileAccess.Read);
            JObject config = null;
            using (StreamReader streamReader = new StreamReader(fs))
            using (JsonTextReader reader = new JsonTextReader(streamReader))
            {
                config = (JObject)JToken.ReadFrom(reader);
            }
            ImageDirectory = config?.GetValue("ImageDirectory").ToString();
            if (!Directory.Exists(ImageDirectory))
            {
                Directory.CreateDirectory(ImageDirectory);
            }
        }
        // constructors
        public GridFSForwardOnlyDownloadStream(
            GridFSBucket bucket,
            IReadBinding binding,
            GridFSFilesCollectionDocument filesCollectionDocument,
            bool checkMD5)
            : base(bucket, binding, filesCollectionDocument)
        {
            _checkMD5 = checkMD5;
            if (_checkMD5)
            {
                _md5 = MD5.Create();
            }

            _lastChunkNumber = (int)((filesCollectionDocument.Length - 1) / filesCollectionDocument.ChunkSizeBytes);
            _lastChunkSize = (int)(filesCollectionDocument.Length % filesCollectionDocument.ChunkSizeBytes);

            if (_lastChunkSize == 0)
            {
                _lastChunkSize = filesCollectionDocument.ChunkSizeBytes;
            }
        }
        public void GivenAMongoMessageDataRepository_WhenPuttingMessageData()
        {
            var db = new MongoClient().GetDatabase("messagedatastoretests");
            _bucket = new GridFSBucket(db);

            var fixture = new Fixture();
            _expectedData = fixture.Create<byte[]>();
            _expectedUri = fixture.Create<Uri>();

            _resolver = new Mock<IMongoMessageUriResolver>();
            _resolver.Setup(m => m.Resolve(It.IsAny<ObjectId>()))
                .Returns((ObjectId x) => _expectedUri);

            _nameCreator = new Mock<IFileNameCreator>();
            _filename = fixture.Create<string>();
            _nameCreator.Setup(m => m.CreateFileName()).Returns(_filename);

            var sut = new MongoMessageDataRepository(_resolver.Object, _bucket, _nameCreator.Object);

            using (var stream = new MemoryStream(_expectedData))
            {
                _actualUri = sut.Put(stream).GetAwaiter().GetResult();
            }
        }
        // constructors
        public GridFSForwardOnlyUploadStream(
            GridFSBucket bucket,
            IWriteBinding binding,
            ObjectId id,
            string filename,
            BsonDocument metadata,
            IEnumerable<string> aliases,
            string contentType,
            int chunkSizeBytes,
            int batchSize)
        {
            _bucket = bucket;
            _binding = binding;
            _id = id;
            _filename = filename;
            _metadata = metadata; // can be null
            _aliases = aliases == null ? null : aliases.ToList(); // can be null
            _contentType = contentType; // can be null
            _chunkSizeBytes = chunkSizeBytes;
            _batchSize = batchSize;

            _batch = new List<byte[]>();
            _md5 = MD5.Create();
        }
Example #27
0
        private void button9_Click(object sender, EventArgs e)
        {
            FileStream Tstream;
            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)
            {
                Tstream = 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;
                }
                DisposeWave();

                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(Tstream));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
                // }
                // else if (open.FileName.EndsWith(".wav"))
                //{
                //    NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName));
                //    stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
                //}
                //else throw new InvalidOperationException("Not a correct audio file type.");

                output = new NAudio.Wave.DirectSoundOut();
                output.Init(stream);
                output.Play();

                //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);
                //FormaPesma = ofd.SafeFileName;
            }
           
        }
Example #28
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);

            }
        }
Example #29
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");
        }
Example #30
0
        private void button7_Click(object sender, EventArgs e)
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("docs");
            var fs = new GridFSBucket(database);

            var test = fs.DownloadAsBytesByName("Test");

            //System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            //Image img = (Image)converter.ConvertFrom(test);

            //MemoryStream mem = new MemoryStream(test);

            Image returnImage = null;
            using (MemoryStream ms = new MemoryStream(test))
            {
                returnImage = Image.FromStream(ms);
            }
            //return returnImage;
            //Bitmap x = new Bitmap(mem, true);

            this.pictureBox1.Image = returnImage;
            this.pictureBox1.Height = returnImage.Height;
            this.pictureBox1.Width = returnImage.Width;
        }
Example #31
0
        private void button6_Click(object sender, EventArgs e)
        {
            //string host = "localhost";
            //int port = 27017;
            //string databaseName = "docs";

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

            //MemoryStream m = new MemoryStream();

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

            //var file = grid.FindOne("Test");
            ////MongoGridFSStream read = grid.OpenRead("Test");
            ////read.CopyTo(m);
            //Image slika;
            //var newFileName = "D:\\new_Untitled.jpg";
            //using (var stream = file.OpenRead())
            //{
            //    var bytes = new byte[stream.Length];
            //    stream.Read(bytes, 0, (int)stream.Length);

            //    using (var newFs = new FileStream(newFileName, FileMode.Create))
            //    {

            //        newFs.Write(bytes, 0, bytes.Length);
            //        //slika = Image.FromStream(newFs);
            //    }
            //}

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

            //var aaa = fs.Find()
            var test = fs.DownloadAsBytesByName("nebo");

            MemoryStream stream = new MemoryStream(test);

            this.pictureBox1.Image = Image.FromStream(stream);
        }
Example #32
0
        public async Task<byte[]> DownloadAsBytesByNameAsync(string gfsname, MediaTypeEnum bucketName) {
            var bucket = new GridFSBucket(_db, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            return await bucket.DownloadAsBytesByNameAsync(gfsname);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="GridFSBucket" /> class.
 /// </summary>
 /// <param name="database">The database.</param>
 /// <param name="options">The options.</param>
 public GridFSBucket(IMongoDatabase database, GridFSBucketOptions options = null)
     : base(database, options)
 {
     _bsonValueBucket = new GridFSBucket <BsonValue>(database, options);
 }
Example #34
-2
 public async Task<ObjectId> SaveBigFire(string fileName, Stream fireStream)
 {
     var bucket = new GridFSBucket(Client.GetDatabase(BigDataFireDBName));
     return await bucket.UploadFromStreamAsync(fileName, fireStream);
 }