Represents a GridFS file system.
 public void TestConstructorFreezesSettings()
 {
     var settings = new MongoGridFSSettings();
     Assert.False(settings.IsFrozen);
     var gridFS = new MongoGridFS(_server, _database.Name, settings);
     Assert.True(gridFS.Settings.IsFrozen);
 }
Exemple #2
0
 /// <summary>
 /// Store a file in the database
 /// </summary>
 /// <param name="stream">The stream of the files content</param>
 /// <param name="fileName">The remote filename</param>
 /// <param name="contentType">The file's content type</param>
 /// <returns>GridFS File Info</returns>
 public MongoGridFSFileInfo Upload(Stream stream, string fileName, string contentType)
 {
     MongoGridFS fs = new MongoGridFS(this.store);
     MongoGridFSCreateOptions options = new MongoGridFSCreateOptions();
     options.ContentType = contentType;
     return fs.Upload(stream, fileName, options);
 }
 internal MongoGridFSFileInfo(
     MongoGridFS gridFS,
     BsonDocument fileInfo
 ) {
     this.gridFS = gridFS;
     CacheFileInfo(fileInfo);
 }
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName
 )
     : this(gridFS, remoteFileName, gridFS.Settings.DefaultChunkSize)
 {
 }
 public void TestConstructorFeezesSettings()
 {
     var settings = new MongoGridFSSettings();
     Assert.IsFalse(settings.IsFrozen);
     var gridFS = new MongoGridFS(_database, settings);
     Assert.IsTrue(gridFS.Settings.IsFrozen);
 }
Exemple #6
0
 /// <summary>
 ///     Create a MongoReaderPlugin with an existing MongoDatabase and specific settings for GridFS
 /// </summary>
 /// <param name="prefix">The virtual folder representing GridFS assets</param>
 /// <param name="db">An existing MongoDatabase instance</param>
 /// <param name="gridSettings">
 ///     Settings for the GridFS connection
 ///     <see href="http://api.mongodb.org/csharp/1.8/html/7a3abd48-0532-8e7f-3c05-6c9812eb06f8.htm" />
 /// </param>
 public MongoReaderPlugin(string prefix, MongoDatabase db, MongoGridFSSettings gridSettings)
 {
     _db = db;
     _gridSettings = gridSettings;
     _grid = _db.GetGridFS(gridSettings);
     VirtualFilesystemPrefix = prefix;
 }
        /// <summary>
        /// Construct MongoQueue
        /// </summary>
        /// <param name="collection">collection</param>
        /// <exception cref="ArgumentNullException">collection is null</exception>
        public Queue(MongoCollection collection)
        {
            if (collection == null) throw new ArgumentNullException("collection");

            this.collection = collection;
            this.gridfs = collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
        }
        public void ConstructorFeezesSettingsTest() {
            var settings = new MongoGridFSSettings();
            settings.IsFrozen.Should().Be.False();

            var gridFS = new MongoGridFS(Database, settings);
            gridFS.Settings.IsFrozen.Should().Be.True();
        }
Exemple #9
0
        /// <summary>
        /// 添加本地文件
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <param name="remoteFile">服务Id</param>
        /// <returns></returns>
        public MetaInfo Add(string filePath, string remoteFile)
        {
            try
            {
                _logger.DebugFormat("Add File filePath:{0}, remoteId:{1}", filePath, remoteFile);

                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions
                {
                    Id = remoteFile,
                    UploadDate = DateTime.Now,
                    ContentType = MimeMapper.GetMimeMapping(filePath),
                };

                using (var stream = new FileStream(filePath, FileMode.Open))
                {
                    MongoGridFS fs = new MongoGridFS(_context.DataBase);

                    var info = fs.Upload(stream, remoteFile, option);
                    return new MetaInfo
                    {
                        fileName = remoteFile,
                        MD5 = info.MD5,
                        MimeType = info.ContentType,
                    };
                }

            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
 public void TestFixtureSetup() {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     database = server["onlinetests"];
     gridFS = database.GridFS;
     gridFS.Chunks.RemoveAll();
     gridFS.Chunks.ResetIndexCache();
     gridFS.Files.RemoveAll();
 }
 public MongoGridFSTests()
 {
     _server = LegacyTestConfiguration.Server;
     _database = LegacyTestConfiguration.Database;
     _gridFS = _database.GridFS;
     _gridFS.Chunks.RemoveAll();
     _gridFS.Files.RemoveAll();
 }
Exemple #12
0
 public void OneTimeSetUp()
 {
     _server = LegacyTestConfiguration.Server;
     _database = LegacyTestConfiguration.Database;
     _gridFS = _database.GridFS;
     _gridFS.Chunks.RemoveAll();
     _gridFS.Files.RemoveAll();
 }
 public void TestFixtureSetup()
 {
     _server = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     _gridFS = _database.GridFS;
     _gridFS.Chunks.RemoveAll();
     _gridFS.Files.RemoveAll();
 }
        protected override void OnTestFixtureSetUp() {
            base.OnTestFixtureSetUp();

            gridFS = Database.GridFS;
            gridFS.Chunks.RemoveAll();
            gridFS.Chunks.ResetIndexCache();
            gridFS.Files.RemoveAll();
        }
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="chunkSize">The chunk size.</param>
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName,
     int chunkSize
 ) {
     this.gridFS = gridFS;
     this.chunkSize = chunkSize;
     this.name = remoteFileName;
 }
        /// <summary>
        /// Construct MongoQueue
        /// </summary>
        /// <param name="url">mongo url like mongodb://localhost</param>
        /// <param name="db">db name</param>
        /// <param name="collection">collection name</param>
        /// <exception cref="ArgumentNullException">url, db or collection is null</exception>
        public Queue(string url, string db, string collection)
        {
            if (url == null) throw new ArgumentNullException("url");
            if (db == null) throw new ArgumentNullException("db");
            if (collection == null) throw new ArgumentNullException("collection");

            this.collection = new MongoClient(url).GetServer().GetDatabase(db).GetCollection(collection);
            this.gridfs = this.collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
        }
        private MongoGridFS WithReadPreferencePrimary()
        {
            var settings = _settings.Clone();

            settings.ReadPreference = ReadPreference.Primary;
            var gridFS = new MongoGridFS(_server, _databaseName, settings);

            return(gridFS);
        }
Exemple #18
0
        public Driver()
        {
            string url = ConfigurationManager.AppSettings["mongoUrl"];
            string db = ConfigurationManager.AppSettings["mongoDb"];
            this.server = MongoServer.Create(url);

            this.database = server.GetDatabase(db);
            this.gridFS = database.GridFS;
        }
 public void TestFixtureSetup() {
     server = MongoServer.Create("mongodb://localhost/?safe=true");
     database = server["onlinetests"];
     var settings = new MongoGridFSSettings {
         ChunkSize = 16,
         SafeMode = SafeMode.True
     };
     gridFS = database.GetGridFS(settings);
 }
Exemple #20
0
        public MongoReaderPlugin(NameValueCollection args)
        {
            VirtualFilesystemPrefix = string.IsNullOrEmpty(args["prefix"]) ? "~/gridfs/" : args["prefix"];

            string connectionString = args["connectionString"];
            this.db = MongoDatabase.Create(connectionString);
            gridSettings = new MongoGridFSSettings();
            grid = db.GetGridFS(gridSettings);
        }
Exemple #21
0
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="chunkSize">The chunk size.</param>
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName,
     int chunkSize
     )
 {
     this.gridFS    = gridFS;
     this.chunkSize = chunkSize;
     this.name      = remoteFileName;
 }
 public MongoGridFSStreamTests()
 {
     _database = LegacyTestConfiguration.Database;
     var settings = new MongoGridFSSettings
     {
         ChunkSize = 16,
         WriteConcern = WriteConcern.Acknowledged
     };
     _gridFS = _database.GetGridFS(settings);
 }
        protected override void OnTestFixtureSetUp() {
            base.OnTestFixtureSetUp();

            var settings = new MongoGridFSSettings
                           {
                               ChunkSize = 16,
                               SafeMode = SafeMode.True
                           };
            gridFS = Database.GetGridFS(settings);
        }
        public BookContext()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
            var con = new MongoUrlBuilder(connectionString);

            client = new MongoClient(connectionString);
            database = client.GetDatabase(con.DatabaseName);

            gridFS = new MongoGridFS(new MongoServer(new MongoServerSettings { Server = con.Server }),con.DatabaseName, new MongoGridFSSettings());
        }
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName,
     int chunkSize
 )
 {
     this.gridFS = gridFS;
     this.chunkSize = chunkSize;
     this.id = BsonObjectId.GenerateNewId();
     this.name = remoteFileName;
 }
Exemple #26
0
        object IBsonSerializable.Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            IBsonSerializationOptions options
            )
        {
            MongoGridFS gridFS   = ((SerializationOptions)options).GridFS;
            var         fileInfo = BsonDocument.ReadFrom(bsonReader);

            return(new MongoGridFSFileInfo(gridFS, fileInfo));
        }
        public PatientRepository()
        {
            _server = new MongoServer(new MongoServerSettings { Server = new MongoServerAddress(_DBHOST), SafeMode = SafeMode.True });

            //patients
            _patients = _server.GetDatabase(_DBNAME).GetCollection<PatientModel>("patients");
            _patients.EnsureIndex(IndexKeys.Ascending("_id"), IndexOptions.SetUnique(true));
            _gridFS = _server.GetDatabase(_DBNAME).GridFS;

            new MongoDB.Web.Providers.MongoDBMembershipProvider();
        }
 public void TestFixtureSetup()
 {
     _server = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     var settings = new MongoGridFSSettings
     {
         ChunkSize = 16,
         SafeMode = SafeMode.True
     };
     _gridFS = _database.GetGridFS(settings);
 }
 public void TestFixtureSetup()
 {
     _server = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     var settings = new MongoGridFSSettings(_database)
     {
         ChunkSize = 16,
         WriteConcern = WriteConcern.Errors
     };
     _gridFS = _database.GetGridFS(settings);
 }
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     _gridFS      = gridFS;
     _aliases     = createOptions.Aliases;
     _chunkSize   = (createOptions.ChunkSize == 0) ? gridFS.Settings.ChunkSize : createOptions.ChunkSize;
     _contentType = createOptions.ContentType;
     _id          = createOptions.Id;
     _metadata    = createOptions.Metadata;
     _name        = remoteFileName;
     _uploadDate  = createOptions.UploadDate;
     _cached      = true; // prevent values from being overwritten by automatic Refresh
 }
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     this.gridFS      = gridFS;
     this.aliases     = createOptions.Aliases;
     this.chunkSize   = createOptions.ChunkSize == 0 ? gridFS.Settings.ChunkSize : createOptions.ChunkSize;
     this.contentType = createOptions.ContentType;
     this.id          = createOptions.Id;
     this.metadata    = createOptions.Metadata;
     this.name        = remoteFileName;
     this.uploadDate  = createOptions.UploadDate;
     this.cached      = true; // prevent values from being overwritten by automatic Refresh
 }
        private void OpenAppend()
        {
            EnsureServerInstanceIsPrimary();
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                gridFS.EnsureIndexes();

                _length   = _fileInfo.Length;
                _position = _fileInfo.Length;
            }
        }
 /// <summary>
 /// Copies a GridFS file.
 /// </summary>
 /// <param name="destFileName">The destination file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>The file info of the new GridFS file.</returns>
 public MongoGridFSFileInfo CopyTo(string destFileName, MongoGridFSCreateOptions createOptions)
 {
     EnsureServerInstanceIsPrimary();
     using (_server.RequestStart(_serverInstance))
     {
         // note: we are aware that the data is making a round trip from and back to the server
         // but we choose not to use a script to copy the data locally on the server
         // because that would lock the database for too long
         var gridFS = new MongoGridFS(_server, _databaseName, _settings);
         var stream = OpenRead();
         return(gridFS.Upload(stream, destFileName, createOptions));
     }
 }
Exemple #34
0
        /// <summary>
        ///     Create a MongoReaderPlugin from plug-in arguments
        /// </summary>
        /// <param name="args"></param>
        public MongoReaderPlugin(NameValueCollection args)
        {
            VirtualFilesystemPrefix = string.IsNullOrEmpty(args["prefix"]) ? "~/gridfs/" : args["prefix"];

            var mongoUrl = new MongoUrl(args["connectionString"]);

            // Using new client, server database initialization. Wordy but recommended.
            var mongoClient = new MongoClient(mongoUrl);
            var mongoServer = mongoClient.GetServer();
            _db = mongoServer.GetDatabase(mongoUrl.DatabaseName);
            _gridSettings = new MongoGridFSSettings();
            _grid = _db.GetGridFS(_gridSettings);
        }
Exemple #35
0
        public static MongoGridFSFileInfo UploadImageToDish(this Dish dishWithImages, MongoGridFS gridFS, System.IO.Stream fs, string imageName, string contentType)
        {
            log.DebugFormat("[UploadImageToDish] This RestaurantBasicData.Id={0}, MongoGridFS, imageName={1}, contentType={2}.", dishWithImages.Id, gridFS.ToString(), imageName, contentType);

            MongoGridFSCreateOptions gridFSOption = new MongoGridFSCreateOptions();
            gridFSOption.ContentType = contentType;
            var gridFsInfo = gridFS.Upload(fs, imageName, gridFSOption);
            ImageData convertedValue = ImageServices.ConvertToImageData(gridFsInfo);
            dishWithImages.Image = convertedValue;
            //dishWithImages.Images[0] = convertedValue;
            var fileId = gridFsInfo.Id;
            return gridFsInfo;
        }
 /// <summary>
 /// Moves the most recent version of a GridFS file.
 /// </summary>
 /// <param name="destFileName">The destination file name.</param>
 public void MoveTo(string destFileName)
 {
     EnsureServerInstanceIsPrimary();
     using (_server.RequestStart(_serverInstance))
     {
         var gridFS          = new MongoGridFS(_server, _databaseName, _settings);
         var database        = gridFS.GetDatabase(ReadPreference.Primary);
         var filesCollection = gridFS.GetFilesCollection(database);
         var query           = Query.EQ("_id", _id);
         var update          = Update.Set("filename", destFileName);
         filesCollection.Update(query, update);
     }
 }
        private void OpenTruncate()
        {
            EnsureServerInstanceIsPrimary();
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                gridFS.EnsureIndexes();

                _fileIsDirty = true;
                // existing chunks will be overwritten as needed and extra chunks will be removed on Close
                _length   = 0;
                _position = 0;
            }
        }
        // private methods
        private void AddMissingChunks()
        {
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS           = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database         = gridFS.GetDatabase(ReadPreference.Primary);
                var chunksCollection = gridFS.GetChunksCollection(database);

                var query            = Query.EQ("files_id", _fileInfo.Id);
                var fields           = Fields.Include("n");
                var chunkCount       = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize;
                var chunksFound      = new HashSet <long>();
                var foundExtraChunks = false;
                foreach (var chunk in chunksCollection.Find(query).SetFields(fields))
                {
                    var n = chunk["n"].ToInt64();
                    chunksFound.Add(n);
                    if (n >= chunkCount)
                    {
                        foundExtraChunks = true;
                    }
                }

                if (foundExtraChunks)
                {
                    var extraChunksQuery = Query.And(Query.EQ("files_id", _fileInfo.Id), Query.GTE("n", chunkCount));
                    chunksCollection.Remove(extraChunksQuery);
                }

                BsonBinaryData zeros = null; // delay creating it until it's actually needed
                for (var n = 0L; n < chunkCount; n++)
                {
                    if (!chunksFound.Contains(n))
                    {
                        if (zeros == null)
                        {
                            zeros = new BsonBinaryData(new byte[_fileInfo.ChunkSize]);
                        }
                        var missingChunk = new BsonDocument
                        {
                            { "_id", ObjectId.GenerateNewId() },
                            { "files_id", _fileInfo.Id },
                            { "n", (n < int.MaxValue) ? (BsonValue) new BsonInt32((int)n) : new BsonInt64(n) },
                            { "data", zeros }
                        };
                        chunksCollection.Insert(missingChunk);
                    }
                }
            }
        }
Exemple #39
0
 // uploading all the chunks into grid.fs.files asynchronously but we have to watch out for
 // resource competition. so we will only allow upto 'simultaneousUploads' tasks run at a time.
 // this ensure that gridfs to not overwhelm with write requests.
 public void multiThreadedUpload(List<byte[]> chunks, string id, MongoGridFS grid)
 {
     SemaphoreSlim max = new SemaphoreSlim(simultaneousUploads);
     var tasks = new Task[chunks.Count];
     for (var i = 0; i < chunks.Count; i++) {
         max.Wait();
         var index = i;
         var chunkMetadata = new BsonDocument { { "files_id", new ObjectId(id) }, { "n", i }, { "data", chunks[i] } };
         tasks[i] = Task.Factory.StartNew(() => writeToGrid(chunkMetadata, grid, index)
             , TaskCreationOptions.LongRunning)
             .ContinueWith( (task) => max.Release());
     }
     Task.WaitAll(tasks);
 }
        private static MongoServerInstance GetServerInstance(MongoGridFS gridFS)
        {
            if (gridFS == null)
            {
                throw new ArgumentNullException("gridFS");
            }

            // bind to one of the nodes using the ReadPreference
            var server = gridFS.Server;

            using (server.RequestStart(gridFS.Settings.ReadPreference))
            {
                return(server.RequestServerInstance);
            }
        }
        public virtual void Setup()
        {
            collection = new MongoClient(ConfigurationManager.AppSettings["mongoQueueUrl"])
                .GetServer()
                .GetDatabase(ConfigurationManager.AppSettings["mongoQueueDb"])
                .GetCollection(ConfigurationManager.AppSettings["mongoQueueCollection"]);

            collection.Drop();

            gridfs = collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
            gridfs.Files.Drop();
            gridfs.Chunks.Drop();

            queue = new Queue();
        }
        private void LoadChunk(long chunkIndex)
        {
            if (_chunkIsDirty)
            {
                SaveChunk();
            }

            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS           = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database         = gridFS.GetDatabase();
                var chunksCollection = gridFS.GetChunksCollection(database);

                var query    = Query.And(Query.EQ("files_id", _fileInfo.Id), Query.EQ("n", chunkIndex));
                var document = chunksCollection.FindOne(query);
                if (document == null)
                {
                    if (_chunk == null)
                    {
                        _chunk = new byte[_fileInfo.ChunkSize];
                    }
                    else
                    {
                        Array.Clear(_chunk, 0, _chunk.Length);
                    }
                    _chunkId = ObjectId.GenerateNewId();
                }
                else
                {
                    var bytes = document["data"].AsBsonBinaryData.Bytes;
                    if (bytes.Length == _fileInfo.ChunkSize)
                    {
                        _chunk = bytes;
                    }
                    else
                    {
                        if (_chunk == null)
                        {
                            _chunk = new byte[_fileInfo.ChunkSize];
                        }
                        Buffer.BlockCopy(bytes, 0, _chunk, 0, bytes.Length);
                        Array.Clear(_chunk, bytes.Length, _chunk.Length - bytes.Length);
                    }
                    _chunkId = document["_id"];
                }
                _chunkIndex = chunkIndex;
            }
        }
        private void SaveChunk()
        {
            using (_fileInfo.Server.RequestStart(_fileInfo.ServerInstance))
            {
                var connectionId     = _fileInfo.Server.RequestConnectionId;
                var gridFS           = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database         = gridFS.GetDatabase(ReadPreference.Primary);
                var chunksCollection = gridFS.GetChunksCollection(database);

                var lastChunkIndex = (_length + _fileInfo.ChunkSize - 1) / _fileInfo.ChunkSize - 1;
                if (_chunkIndex == -1 || _chunkIndex > lastChunkIndex)
                {
                    var message = string.Format("Invalid chunk index {0}.", _chunkIndex);
                    throw new MongoGridFSException(connectionId, message);
                }

                var lastChunkSize = (int)(_length % _fileInfo.ChunkSize);
                if (lastChunkSize == 0)
                {
                    lastChunkSize = _fileInfo.ChunkSize;
                }

                BsonBinaryData data;
                if (_chunkIndex < lastChunkIndex || lastChunkSize == _fileInfo.ChunkSize)
                {
                    data = new BsonBinaryData(_chunk);
                }
                else
                {
                    var lastChunk = new byte[lastChunkSize];
                    Buffer.BlockCopy(_chunk, 0, lastChunk, 0, lastChunkSize);
                    data = new BsonBinaryData(lastChunk);
                }

                var query  = Query.EQ("_id", _chunkId);
                var update = new UpdateDocument
                {
                    { "_id", _chunkId },
                    { "files_id", _fileInfo.Id },
                    { "n", _chunkIndex < int.MaxValue ? (BsonValue)(BsonInt32)(int)_chunkIndex : (BsonInt64)_chunkIndex },
                    { "data", data }
                };
                chunksCollection.Update(query, update, UpdateFlags.Upsert);
                _chunkIsDirty = false;
            }
        }
        /// <summary>
        /// Deletes a GridFS file.
        /// </summary>
        public void Delete()
        {
            EnsureServerInstanceIsPrimary();
            using (_server.RequestStart(_serverInstance))
            {
                var gridFS = new MongoGridFS(_server, _databaseName, _settings);
                gridFS.EnsureIndexes();

                if (Exists)
                {
                    var database         = gridFS.GetDatabase(ReadPreference.Primary);
                    var filesCollection  = gridFS.GetFilesCollection(database);
                    var chunksCollection = gridFS.GetChunksCollection(database);

                    filesCollection.Remove(Query.EQ("_id", _id), gridFS.Settings.WriteConcern);
                    chunksCollection.Remove(Query.EQ("files_id", _id), gridFS.Settings.WriteConcern);
                }
            }
        }
        private void LoadChunkNoData(long chunkIndex)
        {
            if (_chunkIsDirty)
            {
                SaveChunk();
            }

            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS           = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database         = gridFS.GetDatabase();
                var chunksCollection = gridFS.GetChunksCollection(database);

                if (_chunk == null)
                {
                    _chunk = new byte[_fileInfo.ChunkSize];
                }
                else
                {
                    Array.Clear(_chunk, 0, _chunk.Length);
                }

                var query    = Query.And(Query.EQ("files_id", _fileInfo.Id), Query.EQ("n", chunkIndex));
                var fields   = Fields.Include("_id");
                var document = chunksCollection.Find(query).SetFields(fields).SetLimit(1).FirstOrDefault();
                if (document == null)
                {
                    _chunkId = ObjectId.GenerateNewId();
                }
                else
                {
                    _chunkId = document["_id"];
                }
                _chunkIndex = chunkIndex;
            }
        }
        private void OpenCreate()
        {
            EnsureServerInstanceIsPrimary();
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS          = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database        = gridFS.GetDatabase(ReadPreference.Primary);
                var filesCollection = gridFS.GetFilesCollection(database);

                gridFS.EnsureIndexes();

                _fileIsDirty = true;
                if (_fileInfo.Id == null)
                {
                    _fileInfo.SetId(ObjectId.GenerateNewId());
                }

                var aliases = (_fileInfo.Aliases != null) ? new BsonArray(_fileInfo.Aliases) : null;
                var file    = new BsonDocument
                {
                    { "_id", _fileInfo.Id },
                    { "filename", _fileInfo.Name, !string.IsNullOrEmpty(_fileInfo.Name) },
                    { "length", 0 },
                    { "chunkSize", _fileInfo.ChunkSize },
                    { "uploadDate", _fileInfo.UploadDate },
                    { "md5", BsonNull.Value },                                                              // will be updated when the file is closed (unless UpdateMD5 is false)
                    { "contentType", _fileInfo.ContentType, !string.IsNullOrEmpty(_fileInfo.ContentType) }, // optional
                    { "aliases", aliases, aliases != null },                                                // optional
                    { "metadata", _fileInfo.Metadata, _fileInfo.Metadata != null } // optional
                };
                filesCollection.Insert(file);

                _length   = 0;
                _position = 0;
            }
        }
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName)
     : this(gridFS, remoteFileName, gridFS.Settings.ChunkSize)
 {
 }
 internal MongoGridFSFileInfo(MongoGridFS gridFS, BsonDocument fileInfo)
 {
     this.gridFS = gridFS;
     CacheFileInfo(fileInfo);
 }
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, int chunkSize)
     : this(GetServer(gridFS), GetServerInstance(gridFS), GetDatabaseName(gridFS), GetGridFSSettings(gridFS), remoteFileName)
 {
     _chunkSize = chunkSize;
 }
 /// <summary>
 /// Initializes a new instance of the GridFSFileInfo class.
 /// </summary>
 /// <param name="gridFS">The GridFS file system that contains the GridFS file.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="chunkSize">The chunk size.</param>
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, int chunkSize)
 {
     _gridFS    = gridFS;
     _chunkSize = chunkSize;
     _name      = remoteFileName;
 }
Exemple #51
0
        /// <summary>
        /// Initializes a new instance of the MongoGridFSStream class.
        /// </summary>
        /// <param name="fileInfo">The GridFS file info.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="access">The acess.</param>
        public MongoGridFSStream(MongoGridFSFileInfo fileInfo, FileMode mode, FileAccess access)
        {
            _gridFS    = fileInfo.GridFS;
            _fileInfo  = fileInfo;
            _mode      = mode;
            _access    = access;
            _updateMD5 = _gridFS.Settings.UpdateMD5;

            var    exists = fileInfo.Exists;
            string message;

            switch (mode)
            {
            case FileMode.Append:
                if (exists)
                {
                    OpenAppend();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Create:
                if (exists)
                {
                    OpenTruncate();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.CreateNew:
                if (exists)
                {
                    message = string.Format("File '{0}' already exists.", fileInfo.Name);
                    throw new IOException(message);
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Open:
                if (exists)
                {
                    OpenExisting();
                }
                else
                {
                    message = string.Format("File '{0}' not found.", fileInfo.Name);
                    throw new FileNotFoundException(message);
                }
                break;

            case FileMode.OpenOrCreate:
                if (exists)
                {
                    OpenExisting();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Truncate:
                if (exists)
                {
                    OpenTruncate();
                }
                else
                {
                    message = string.Format("File '{0}' not found.", fileInfo.Name);
                    throw new FileNotFoundException(message);
                }
                break;

            default:
                message = string.Format("Invalid FileMode {0}.", mode);
                throw new ArgumentException(message, "mode");
            }
        }
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, MongoGridFSCreateOptions createOptions)
     : this(GetServer(gridFS), GetServerInstance(gridFS), GetDatabaseName(gridFS), GetGridFSSettings(gridFS), remoteFileName, createOptions)
 {
 }
        /// <summary>
        /// Initializes a new instance of the MongoGridFSStream class.
        /// </summary>
        /// <param name="fileInfo">The GridFS file info.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="access">The acess.</param>
        public MongoGridFSStream(
            MongoGridFSFileInfo fileInfo,
            FileMode mode,
            FileAccess access
            )
        {
            this.gridFS   = fileInfo.GridFS;
            this.fileInfo = fileInfo;
            this.mode     = mode;
            this.access   = access;

            var    exists = fileInfo.Exists;
            string message;

            switch (mode)
            {
            case FileMode.Append:
                if (exists)
                {
                    OpenAppend();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Create:
                if (exists)
                {
                    OpenTruncate();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.CreateNew:
                if (exists)
                {
                    message = string.Format("File already exists: {0}", fileInfo.Name);
                    throw new IOException(message);
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Open:
                if (exists)
                {
                    OpenExisting();
                }
                else
                {
                    message = string.Format("File not found: {0}", fileInfo.Name);
                    throw new FileNotFoundException(message);
                }
                break;

            case FileMode.OpenOrCreate:
                if (exists)
                {
                    OpenExisting();
                }
                else
                {
                    OpenCreate();
                }
                break;

            case FileMode.Truncate:
                if (exists)
                {
                    OpenTruncate();
                }
                else
                {
                    message = string.Format("File not found: {0}", fileInfo.Name);
                    throw new FileNotFoundException(message);
                }
                break;

            default:
                message = string.Format("Invalid FileMode: {0}", fileInfo.Name);
                throw new ArgumentException(message, "mode");
            }
            gridFS.EnsureIndexes();
        }