Represents options used when creating a GridFS file.
        public void TestEquals()
        {
            var createOptions = new MongoGridFSCreateOptions { ChunkSize = 123 };
            var a = new MongoGridFSFileInfo(gridFS, "f", createOptions);
            var b = new MongoGridFSFileInfo(gridFS, "f", createOptions);
            var c = new MongoGridFSFileInfo(gridFS, "g", createOptions);
            var n = (MongoCredentials) null;

            Assert.IsTrue(object.Equals(a, b));
            Assert.IsFalse(object.Equals(a, c));
            Assert.IsFalse(a.Equals(n));
            Assert.IsFalse(a.Equals(null));

            Assert.IsTrue(a == b);
            Assert.IsFalse(a == c);
            Assert.IsFalse(a == null);
            Assert.IsFalse(null == a);
            Assert.IsTrue(n == null);
            Assert.IsTrue(null == n);

            Assert.IsFalse(a != b);
            Assert.IsTrue(a != c);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
Example #2
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 TestCreateWithRemoteFileNameAndCreateOptions()
 {
     var aliases = new string[] { "a", "b" };
     var uploadDate = new DateTime(2011, 11, 10, 19, 57, 0, DateTimeKind.Utc);
     var metadata = new BsonDocument("x", 1);
     var createOptions = new MongoGridFSCreateOptions()
     {
         Aliases = aliases,
         ChunkSize = 123,
         ContentType = "content",
         Id = 1,
         Metadata = metadata,
         UploadDate = uploadDate
     };
     var info = new MongoGridFSFileInfo(_gridFS, "filename", createOptions);
     Assert.IsTrue(aliases.SequenceEqual(info.Aliases));
     Assert.AreEqual(123, info.ChunkSize);
     Assert.AreEqual("content", info.ContentType);
     Assert.AreEqual(_gridFS, info.GridFS);
     Assert.AreEqual(1, info.Id.AsInt32);
     Assert.AreEqual(0, info.Length);
     Assert.AreEqual(null, info.MD5);
     Assert.AreEqual(metadata, info.Metadata);
     Assert.AreEqual("filename", info.Name);
     Assert.AreEqual(uploadDate, info.UploadDate);
 }
        public void TestEquals()
        {
            var createOptions = new MongoGridFSCreateOptions { ChunkSize = 123 };
            var a1 = new MongoGridFSFileInfo(_gridFS, "f", createOptions);
            var a2 = new MongoGridFSFileInfo(_gridFS, "f", createOptions);
            var a3 = a2;
            var b = new MongoGridFSFileInfo(_gridFS, "g", createOptions);
            var null1 = (MongoGridFSFileInfo)null;
            var null2 = (MongoGridFSFileInfo)null;

            Assert.AreNotSame(a1, a2);
            Assert.AreSame(a2, a3);
            Assert.IsTrue(a1.Equals((object)a2));
            Assert.IsFalse(a1.Equals((object)null));
            Assert.IsFalse(a1.Equals((object)"x"));

            Assert.IsTrue(a1 == a2);
            Assert.IsTrue(a2 == a3);
            Assert.IsFalse(a1 == b);
            Assert.IsFalse(a1 == null1);
            Assert.IsFalse(null1 == a1);
            Assert.IsTrue(null1 == null2);

            Assert.IsFalse(a1 != a2);
            Assert.IsFalse(a2 != a3);
            Assert.IsTrue(a1 != b);
            Assert.IsTrue(a1 != null1);
            Assert.IsTrue(null1 != a1);
            Assert.IsFalse(null1 != null2);

            Assert.AreEqual(a1.GetHashCode(), a2.GetHashCode());
        }
Example #5
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);
 }
        public void TestEquals()
        {
            var settings = new MongoGridFSSettings();
            var createOptions = new MongoGridFSCreateOptions { ChunkSize = 123 };
            var a1 = new MongoGridFSFileInfo(_server, _server.Primary, _database.Name, settings, "f", createOptions);
            var a2 = new MongoGridFSFileInfo(_server, _server.Primary, _database.Name, settings, "f", createOptions);
            var a3 = a2;
            var b = new MongoGridFSFileInfo(_server, _server.Primary, _database.Name, settings, "g", createOptions);
            var null1 = (MongoGridFSFileInfo)null;
            var null2 = (MongoGridFSFileInfo)null;

            Assert.NotSame(a1, a2);
            Assert.Same(a2, a3);
            Assert.True(a1.Equals((object)a2));
            Assert.False(a1.Equals((object)null));
            Assert.False(a1.Equals((object)"x"));

            Assert.True(a1 == a2);
            Assert.True(a2 == a3);
            Assert.False(a1 == b);
            Assert.False(a1 == null1);
            Assert.False(null1 == a1);
            Assert.True(null1 == null2);

            Assert.False(a1 != a2);
            Assert.False(a2 != a3);
            Assert.True(a1 != b);
            Assert.True(a1 != null1);
            Assert.True(null1 != a1);
            Assert.False(null1 != null2);

            Assert.Equal(a1.GetHashCode(), a2.GetHashCode());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MongoGridFSFileInfo"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="serverInstance">The server instance.</param>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="gridFSSettings">The GridFS settings.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        public MongoGridFSFileInfo(
            MongoServer server,
            MongoServerInstance serverInstance,
            string databaseName,
            MongoGridFSSettings gridFSSettings,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions)
            : this(server, serverInstance, databaseName, gridFSSettings)
        {
            if (remoteFileName == null)
            {
                throw new ArgumentNullException("remoteFileName");
            }
            if (createOptions == null)
            {
                throw new ArgumentNullException("createOptions");
            }

            _aliases     = createOptions.Aliases;
            _chunkSize   = (createOptions.ChunkSize == 0) ? gridFSSettings.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
        }
        public void TestCopyTo()
        {
            _gridFS.Delete(Query.Null);
            Assert.AreEqual(0, _gridFS.Chunks.Count());
            Assert.AreEqual(0, _gridFS.Files.Count());

            var contents = "Hello World";
            var bytes = Encoding.UTF8.GetBytes(contents);
            var uploadStream = new MemoryStream(bytes);
            var createOptions = new MongoGridFSCreateOptions
            {
                Aliases = new[] { "HelloWorld", "HelloUniverse" },
                ChunkSize = _gridFS.Settings.ChunkSize,
                ContentType = "text/plain",
                Id = ObjectId.GenerateNewId(),
                Metadata = new BsonDocument { { "a", 1 }, { "b", 2 } },
                UploadDate = DateTime.UtcNow
            };
            var fileInfo = _gridFS.Upload(uploadStream, "HelloWorld.txt", createOptions);
            var copyInfo = fileInfo.CopyTo("HelloWorld2.txt");
            Assert.AreEqual(2, _gridFS.Chunks.Count());
            Assert.AreEqual(2, _gridFS.Files.Count());
            Assert.IsNull(copyInfo.Aliases);
            Assert.AreEqual(fileInfo.ChunkSize, copyInfo.ChunkSize);
            Assert.AreEqual(fileInfo.ContentType, copyInfo.ContentType);
            Assert.AreNotEqual(fileInfo.Id, copyInfo.Id);
            Assert.AreEqual(fileInfo.Length, copyInfo.Length);
            Assert.AreEqual(fileInfo.MD5, copyInfo.MD5);
            Assert.AreEqual(fileInfo.Metadata, copyInfo.Metadata);
            Assert.AreEqual("HelloWorld2.txt", copyInfo.Name);
            Assert.AreEqual(fileInfo.UploadDate, copyInfo.UploadDate);
        }
Example #9
0
        public void CopyTo() {
            gridFS.Delete(Query.Null);
            gridFS.Chunks.Count().Should().Be(0);
            gridFS.Files.Count().Should().Be(0);

            var uploadStream = new MemoryStream(ContentBytes);
            var createOptions = new MongoGridFSCreateOptions
                                {
                                    Aliases = new[] { "애국가", "HelloWorld" },
                                    ChunkSize = gridFS.Settings.ChunkSize,
                                    ContentType = "text/plain",
                                    Id = ObjectId.GenerateNewId(),
                                    Metadata = new BsonDocument { { "a", 1 }, { "b", 2 } },
                                    UploadDate = DateTime.UtcNow
                                };

            var fileInfo = gridFS.Upload(uploadStream, "HelloWorld.txt", createOptions);
            fileInfo.Should().Not.Be.Null();
            var copyInfo = fileInfo.CopyTo("HelloWorld2.txt");
            copyInfo.Should().Not.Be.Null();

            gridFS.Chunks.Count().Should().Be(2); // 하나의 파일 크기가 ChunkSize 보다 작으므로
            gridFS.Files.Count().Should().Be(2);
            copyInfo.Aliases.Should().Be.Null(); // Alias는 복사되지 않습니다.

            copyInfo.ChunkSize.Should().Be(fileInfo.ChunkSize);
            copyInfo.ContentType.Should().Be(fileInfo.ContentType);
            copyInfo.Id.Should().Not.Be(fileInfo.Id);
            copyInfo.Length.Should().Be(fileInfo.Length);
            copyInfo.MD5.Should().Be(fileInfo.MD5);
            Assert.AreEqual(fileInfo.Metadata, copyInfo.Metadata);
            copyInfo.Name.Should().Be("HelloWorld2.txt");
            copyInfo.UploadDate.Should().Be(fileInfo.UploadDate);
        }
        public static MongoGridFSFileInfo UploadFile(this IMongoRepository repository, string remoteFilename, Stream stream,
                                                     MongoGridFSCreateOptions createOptions) {
            stream.ShouldNotBeNull("stream");
            remoteFilename.ShouldNotBeWhiteSpace("remoteFilename");

            return repository.GridFS.Upload(stream, remoteFilename, createOptions);
        }
        /// <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)
        {
            // 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 stream = OpenRead();

            return(gridFS.Upload(stream, destFileName, createOptions));
        }
Example #12
0
        /// <summary>
        /// Creates or opens a GridFS file for writing UTF-8 encoded text.
        /// </summary>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>A stream writer.</returns>
        public StreamWriter CreateText(
            string remoteFileName,
            MongoGridFSCreateOptions createOptions
            )
        {
            var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);

            return(fileInfo.CreateText());
        }
Example #13
0
 public ActionResult AttachFile(HttpPostedFileBase file)
 {
     var options = new MongoGridFSCreateOptions
     {
         ContentType = file.ContentType
     };
     var fileInfo = mongoContext.Database.GridFS.Upload(file.InputStream, file.FileName, options);
     return Json(fileInfo, JsonRequestBehavior.AllowGet);
 }
Example #14
0
        /// <summary>
        /// Opens an existing GridFS file for writing.
        /// </summary>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>A stream.</returns>
        public MongoGridFSStream OpenWrite(
            string remoteFileName,
            MongoGridFSCreateOptions createOptions
            )
        {
            var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);

            return(fileInfo.OpenWrite());
        }
Example #15
0
 /// <summary>
 /// Opens an existing GridFS file for writing.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream OpenWrite(string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     using (_server.RequestStart(null, ReadPreference.Primary))
     {
         var serverInstance = _server.RequestConnection.ServerInstance;
         var fileInfo       = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return(fileInfo.OpenWrite());
     }
 }
        /// <summary>
        /// Opens a GridFS file with the specified mode, access and create options.
        /// </summary>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="access">The access.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>A stream.</returns>
        public MongoGridFSStream Open(
            string remoteFileName,
            FileMode mode,
            FileAccess access,
            MongoGridFSCreateOptions createOptions)
        {
            var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);

            return(fileInfo.Open(mode, access));
        }
Example #17
0
 public MongoGridFSFileInfo ImportFile(Stream stream, string fileName, MongoGridFSCreateOptions createOptions)
 {
     if (stream == null) throw new ArgumentNullException("stream");
     if (fileName == null) throw new ArgumentNullException("fileName");
     if (createOptions == null) throw new ArgumentNullException("createOptions");
     if(createOptions.Id == null) throw new NullReferenceException("createOptions.Id");
     if (createOptions.UploadDate == null) throw new NullReferenceException("createOptions.UploadDate");
     if (createOptions.ContentType == null) throw new NullReferenceException("createOptions.ContentType");
     return _mongoGridFS.Upload(stream, fileName, createOptions);
 }
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(Stream stream, string remoteFileName)
        {
            var options = new MongoGridFSCreateOptions
            {
                ChunkSize  = _settings.ChunkSize,
                Id         = ObjectId.GenerateNewId(),
                UploadDate = DateTime.UtcNow
            };

            return(Upload(stream, remoteFileName, options));
        }
 /// <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
 }
 /// <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
 }
Example #21
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>
 /// Opens a GridFS file with the specified mode, access and create options.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="access">The access.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream Open(
     string remoteFileName,
     FileMode mode,
     FileAccess access,
     MongoGridFSCreateOptions createOptions)
 {
     using (_server.RequestStart(DetermineReadPreference(mode, access)))
     {
         var serverInstance = _server.RequestServerInstance;
         var fileInfo       = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return(fileInfo.Open(mode, access));
     }
 }
 /// <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));
     }
 }
        /// <summary>
        /// Copies a GridFS file.
        /// </summary>
        /// <param name="destFileName">The destination file name.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo CopyTo(string destFileName)
        {
            // copy all createOptions except Aliases (which are considered alternate filenames)
            var createOptions = new MongoGridFSCreateOptions
            {
                ChunkSize   = chunkSize,
                ContentType = contentType,
                Metadata    = metadata,
                UploadDate  = uploadDate
            };

            return(CopyTo(destFileName, createOptions));
        }
Example #25
0
        /// <summary>
        /// Copies a GridFS file.
        /// </summary>
        /// <param name="sourceFileName">The source file name.</param>
        /// <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 sourceFileName,
            string destFileName,
            MongoGridFSCreateOptions createOptions)
        {
            var fileInfo = FindOne(sourceFileName);

            if (fileInfo == null)
            {
                var message = string.Format("GridFS file '{0}' not found.", sourceFileName);
                throw new FileNotFoundException(message);
            }
            return(fileInfo.CopyTo(destFileName, createOptions));
        }
Example #26
0
 public ActionResult AttachImage(string id, HttpPostedFileBase file)
 {
     var rental = GetRental(id);
     var imageId = ObjectId.GenerateNewId();
     rental.ImageId = imageId.ToString();
     Context.Rentals.Save(rental);
     var options = new MongoGridFSCreateOptions
     {
         Id = imageId,
         ContentType = file.ContentType
     };
     Context.Database.GridFS.Upload(file.InputStream, file.FileName);
     return RedirectToAction("Index");
 }
Example #27
0
 /// <summary>
 /// Creates or opens a GridFS file for writing UTF-8 encoded text.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream writer.</returns>
 public StreamWriter CreateText(string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     if (_settings.ReadPreference != ReadPreference.Primary)
     {
         var gridFS = GetPrimaryGridFSSettings();
         return(gridFS.CreateText(remoteFileName, createOptions));
     }
     using (_server.RequestStart(null, ReadPreference.Primary))
     {
         var serverInstance = _server.RequestConnection.ServerInstance;
         var fileInfo       = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return(fileInfo.CreateText());
     }
 }
 /// <summary>
 /// Opens an existing GridFS file for writing.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream OpenWrite(string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     if (_settings.ReadPreference != ReadPreference.Primary)
     {
         var gridFS = WithReadPreferencePrimary();
         return(gridFS.OpenWrite(remoteFileName, createOptions));
     }
     using (_server.RequestStart(ReadPreference.Primary))
     {
         var serverInstance = _server.RequestServerInstance;
         var fileInfo       = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return(fileInfo.OpenWrite());
     }
 }
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName,
     MongoGridFSCreateOptions createOptions
 )
 {
     this.gridFS = gridFS;
     this.aliases = createOptions.Aliases;
     this.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
 }
Example #30
0
        public static MongoGridFSFileInfo UploadImageToRestaurant(this RestaurantBasicData rest, MongoGridFS gridFS, System.IO.Stream fs, string imageName, string contentType)
        {
            //resize picture 100 * 100
            //save to profile
            //on output implement logic of presentation  - if we have image let's display it
            //copy all images that we have on links to gridFS
            //Upload images from backoffice.

            log.DebugFormat("[UploadImageToRestaurant] This RestaurantBasicData.Id={0}, MongoGridFS, imageName={1}.", rest.Id, gridFS.ToString(), imageName);

            MongoGridFSCreateOptions gridFSOption = new MongoGridFSCreateOptions();
            gridFSOption.ContentType = contentType;
            var gridFsInfo = gridFS.Upload(fs, imageName, gridFSOption);
            ImageData convertedValue = ImageServices.ConvertToImageData(gridFsInfo);
            rest.Image = convertedValue;
            var fileId = gridFsInfo.Id;
            return gridFsInfo;
        }
        /// <summary>
        /// Copies a GridFS file.
        /// </summary>
        /// <param name="sourceFileName">The source file name.</param>
        /// <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 sourceFileName,
            string destFileName,
            MongoGridFSCreateOptions createOptions)
        {
            if (_settings.ReadPreference != ReadPreference.Primary)
            {
                var gridFS = WithReadPreferencePrimary();
                return(gridFS.CopyTo(sourceFileName, destFileName, createOptions));
            }
            var fileInfo = FindOne(sourceFileName);

            if (fileInfo == null)
            {
                var message = string.Format("GridFS file '{0}' not found.", sourceFileName);
                throw new FileNotFoundException(message);
            }
            return(fileInfo.CopyTo(destFileName, createOptions));
        }
Example #32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            MongoGridFS g = Config.Current.Plugins.Get<MongoReaderPlugin>().GridFS;

            //Loop through each uploaded file
            foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
                HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
                if (file.ContentLength <= 0) continue; //Skip unused file controls.

                //Resize to a memory stream, max 2000x2000 jpeg
                MemoryStream temp = new MemoryStream(4096);
                new ImageJob(file.InputStream,temp,new ResizeSettings("width=2000;height=2000;mode=max;format=jpg")).Build();
                //Reset the stream
                temp.Seek(0, SeekOrigin.Begin);

                MongoGridFSCreateOptions opts = new MongoGridFSCreateOptions();
                opts.ContentType = file.ContentType;

                MongoGridFSFileInfo fi = g.Upload(temp, Path.GetFileName(file.FileName), opts);

                lit.Text += "<img src=\"" + ResolveUrl("~/gridfs/id/") + fi.Id + ".jpg?width=100&amp;height=100\" />";
            }
        }
 /// <summary>
 /// Opens a GridFS file with the specified mode, access and create options.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="access">The access.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream Open(
     string remoteFileName,
     FileMode mode,
     FileAccess access,
     MongoGridFSCreateOptions createOptions)
 {
     using (_server.RequestStart(null, DetermineReadPreference(mode, access)))
     {
         var serverInstance = _server.RequestConnection.ServerInstance;
         var fileInfo = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return fileInfo.Open(mode, access);
     }
 }
Example #34
0
 /// <summary>
 /// Uploads a GridFS file.
 /// </summary>
 /// <param name="stream">The source stream.</param>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <returns>The file info of the new GridFS file.</returns>
 public MongoGridFSFileInfo Upload(
     Stream stream,
     string remoteFileName
 ) {
     var options = new MongoGridFSCreateOptions {
         ChunkSize = settings.ChunkSize,
         Id = BsonObjectId.GenerateNewId(),
         UploadDate = DateTime.UtcNow
     };
     return Upload(stream, remoteFileName, options);
 }
Example #35
0
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions
        ) {
            using (database.RequestStart(false)) { // not slaveOk
                EnsureIndexes();

                var files_id = createOptions.Id ?? BsonObjectId.GenerateNewId();
                var chunkSize = createOptions.ChunkSize == 0 ? settings.ChunkSize : createOptions.ChunkSize;
                var buffer = new byte[chunkSize];

                var length = 0;
                string md5Client;
                using (var md5Algorithm = MD5.Create()) {
                    for (int n = 0; true; n++) {
                        // might have to call Stream.Read several times to get a whole chunk
                        var bytesNeeded = chunkSize;
                        var bytesRead = 0;
                        while (bytesNeeded > 0) {
                            var partialRead = stream.Read(buffer, bytesRead, bytesNeeded);
                            if (partialRead == 0) {
                                break; // EOF may or may not have a partial chunk
                            }
                            bytesNeeded -= partialRead;
                            bytesRead += partialRead;
                        }
                        if (bytesRead == 0) {
                            break; // EOF no partial chunk
                        }
                        length += bytesRead;

                        byte[] data = buffer;
                        if (bytesRead < chunkSize) {
                            data = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                        }

                        var chunk = new BsonDocument {
                            { "_id", BsonObjectId.GenerateNewId() },
                            { "files_id", files_id },
                            { "n", n },
                            { "data", new BsonBinaryData(data) }
                        };
                        chunks.Insert(chunk, settings.SafeMode);

                        md5Algorithm.TransformBlock(data, 0, data.Length, null, 0);

                        if (bytesRead < chunkSize) {
                            break; // EOF after partial chunk
                        }
                    }

                    md5Algorithm.TransformFinalBlock(new byte[0], 0, 0);
                    md5Client = BsonUtils.ToHexString(md5Algorithm.Hash);
                }

                var md5Command = new CommandDocument {
                    { "filemd5", files_id },
                    { "root", settings.Root }
                };
                var md5Result = database.RunCommand(md5Command);
                var md5Server = md5Result.Response["md5"].AsString;

                if (!md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase)) {
                    throw new MongoGridFSException("Upload client and server MD5 hashes are not equal.");
                }

                var uploadDate = createOptions.UploadDate == DateTime.MinValue ? DateTime.UtcNow : createOptions.UploadDate;
                BsonDocument fileInfo = new BsonDocument {
                    { "_id", files_id },
                    { "filename", remoteFileName },
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", md5Server },
                    { "contentType", createOptions.ContentType }, // optional
                    { "aliases", BsonArray.Create(createOptions.Aliases) }, // optional
                    { "metadata", createOptions.Metadata } // optional
                };
                files.Insert(fileInfo, settings.SafeMode);

                return FindOneById(files_id);
            }
        }
Example #36
0
 /// <summary>
 /// Opens a GridFS file with the specified mode, access and create options.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="access">The access.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream Open(
     string remoteFileName,
     FileMode mode,
     FileAccess access,
     MongoGridFSCreateOptions createOptions
 ) {
     var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);
     return fileInfo.Open(mode, access);
 }
Example #37
0
 /// <summary>
 /// Opens an existing GridFS file for writing.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream OpenWrite(
     string remoteFileName,
     MongoGridFSCreateOptions createOptions
 ) {
     var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);
     return fileInfo.OpenWrite();
 }
Example #38
0
 /// <summary>
 /// Copies a GridFS file.
 /// </summary>
 /// <param name="sourceFileName">The source file name.</param>
 /// <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 sourceFileName,
     string destFileName,
     MongoGridFSCreateOptions createOptions
 ) {
     var fileInfo = FindOne(sourceFileName);
     if (fileInfo == null) {
         var message = string.Format("GridFS file '{0}' not found.", sourceFileName);
         throw new FileNotFoundException(message);
     }
     return fileInfo.CopyTo(destFileName, createOptions);
 }
Example #39
0
 /// <summary>
 /// Creates or opens a GridFS file for writing UTF-8 encoded text.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream writer.</returns>
 public StreamWriter CreateText(
     string remoteFileName,
     MongoGridFSCreateOptions createOptions
 ) {
     var fileInfo = new MongoGridFSFileInfo(this, remoteFileName, createOptions);
     return fileInfo.CreateText();
 }
 /// <summary>
 /// Opens an existing GridFS file for writing.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream OpenWrite(string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     using (_server.RequestStart(null, ReadPreference.Primary))
     {
         var serverInstance = _server.RequestConnection.ServerInstance;
         var fileInfo = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return fileInfo.OpenWrite();
     }
 }
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions)
        {
            using (_server.RequestStart(null, ReadPreference.Primary))
            {
                EnsureIndexes();

                var database = GetDatabase(ReadPreference.Primary);
                var chunksCollection = GetChunksCollection(database);
                var filesCollection = GetFilesCollection(database);

                var files_id = createOptions.Id ?? ObjectId.GenerateNewId();
                var chunkSize = (createOptions.ChunkSize == 0) ? _settings.ChunkSize : createOptions.ChunkSize;
                var buffer = new byte[chunkSize];

                var length = 0L;
                string md5Client = null;
                using (var md5Algorithm = _settings.VerifyMD5 ? MD5.Create() : null)
                {
                    for (var n = 0L; true; n++)
                    {
                        // might have to call Stream.Read several times to get a whole chunk
                        var bytesNeeded = chunkSize;
                        var bytesRead = 0;
                        while (bytesNeeded > 0)
                        {
                            var partialRead = stream.Read(buffer, bytesRead, bytesNeeded);
                            if (partialRead == 0)
                            {
                                break; // EOF may or may not have a partial chunk
                            }
                            bytesNeeded -= partialRead;
                            bytesRead += partialRead;
                        }
                        if (bytesRead == 0)
                        {
                            break; // EOF no partial chunk
                        }
                        length += bytesRead;

                        byte[] data = buffer;
                        if (bytesRead < chunkSize)
                        {
                            data = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                        }

                        var chunk = new BsonDocument
                        {
                            { "_id", ObjectId.GenerateNewId() },
                            { "files_id", files_id },
                            { "n", (n < int.MaxValue) ? (BsonValue)new BsonInt32((int)n) : new BsonInt64(n) },
                            { "data", new BsonBinaryData(data) }
                        };
                        chunksCollection.Insert(chunk, _settings.WriteConcern);

                        if (_settings.VerifyMD5)
                        {
                            md5Algorithm.TransformBlock(data, 0, data.Length, null, 0);
                        }

                        if (bytesRead < chunkSize)
                        {
                            break; // EOF after partial chunk
                        }
                    }

                    if (_settings.VerifyMD5)
                    {
                        md5Algorithm.TransformFinalBlock(new byte[0], 0, 0);
                        md5Client = BsonUtils.ToHexString(md5Algorithm.Hash);
                    }
                }

                string md5Server = null;
                if (_settings.UpdateMD5 || _settings.VerifyMD5)
                {
                    var md5Command = new CommandDocument
                    {
                        { "filemd5", files_id },
                        { "root", _settings.Root }
                    };
                    var md5Result = database.RunCommand(md5Command);
                    md5Server = md5Result.Response["md5"].AsString;
                }

                if ( _settings.VerifyMD5 && !md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase))
                {
                    throw new MongoGridFSException("Upload client and server MD5 hashes are not equal.");
                }

                var uploadDate = (createOptions.UploadDate == DateTime.MinValue) ? DateTime.UtcNow : createOptions.UploadDate;
                var aliases = (createOptions.Aliases != null) ? new BsonArray(createOptions.Aliases) : null;
                BsonDocument fileInfo = new BsonDocument
                {
                    { "_id", files_id },
                    { "filename", remoteFileName, !string.IsNullOrEmpty(remoteFileName) }, // optional
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", (md5Server == null) ? (BsonValue)BsonNull.Value : new BsonString(md5Server) },
                    { "contentType", createOptions.ContentType, !string.IsNullOrEmpty(createOptions.ContentType) }, // optional
                    { "aliases", aliases, aliases != null }, // optional
                    { "metadata", createOptions.Metadata, createOptions.Metadata != null } // optional
                };
                filesCollection.Insert(fileInfo, _settings.WriteConcern);

                return FindOneById(files_id);
            }
        }
        public void TestOpenCreateWithMetadata()
        {
            _gridFS.Files.RemoveAll();
            _gridFS.Chunks.RemoveAll();
            _gridFS.Chunks.ResetIndexCache();

            var metadata = new BsonDocument("author", "John Doe");
            var createOptions = new MongoGridFSCreateOptions
            {
                Metadata = metadata
            };
            using (var stream = _gridFS.Create("test", createOptions))
            {
                var bytes = new byte[] { 1, 2, 3, 4 };
                stream.Write(bytes, 0, 4);
            }

            var fileInfo = _gridFS.FindOne("test");
            Assert.AreEqual(metadata, fileInfo.Metadata);
        }
 public MongoGridFSFileInfo(MongoGridFS gridFS, string remoteFileName, MongoGridFSCreateOptions createOptions)
     : this(GetServer(gridFS), GetServerInstance(gridFS), GetDatabaseName(gridFS), GetGridFSSettings(gridFS), remoteFileName, createOptions)
 {
 }
        public void TestUpload()
        {
            _gridFS.Delete(Query.Null);
            Assert.AreEqual(0, _gridFS.Chunks.Count());
            Assert.AreEqual(0, _gridFS.Files.Count());

            var contents = "Hello World";
            var bytes = Encoding.UTF8.GetBytes(contents);
            var uploadStream = new MemoryStream(bytes);
            var createOptions = new MongoGridFSCreateOptions
            {
                Aliases = new[] { "HelloWorld", "HelloUniverse" },
                ChunkSize = _gridFS.Settings.ChunkSize,
                ContentType = "text/plain",
                Id = ObjectId.GenerateNewId(),
                Metadata = new BsonDocument { { "a", 1 }, { "b", 2 } },
                UploadDate = DateTime.UtcNow
            };
            var fileInfo = _gridFS.Upload(uploadStream, "HelloWorld.txt", createOptions);
            Assert.AreEqual(1, _gridFS.Chunks.Count());
            Assert.AreEqual(1, _gridFS.Files.Count());
            Assert.IsTrue(createOptions.Aliases.SequenceEqual(fileInfo.Aliases));
            Assert.AreEqual(createOptions.ChunkSize, fileInfo.ChunkSize);
            Assert.AreEqual(createOptions.ContentType, fileInfo.ContentType);
            Assert.AreEqual(createOptions.Id, fileInfo.Id);
            Assert.AreEqual(11, fileInfo.Length);
            Assert.IsTrue(!string.IsNullOrEmpty(fileInfo.MD5));
            Assert.AreEqual(createOptions.Metadata, fileInfo.Metadata);
            Assert.AreEqual("HelloWorld.txt", fileInfo.Name);
            Assert.AreEqual(createOptions.UploadDate.AddTicks(-(createOptions.UploadDate.Ticks % 10000)), fileInfo.UploadDate);
        }
Example #45
0
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions
            )
        {
            using (database.RequestStart()) {
                EnsureIndexes();

                var files_id  = createOptions.Id ?? BsonObjectId.GenerateNewId();
                var chunkSize = createOptions.ChunkSize == 0 ? settings.ChunkSize : createOptions.ChunkSize;
                var buffer    = new byte[chunkSize];

                var    length = 0;
                string md5Client;
                using (var md5Algorithm = MD5.Create()) {
                    for (int n = 0; true; n++)
                    {
                        // might have to call Stream.Read several times to get a whole chunk
                        var bytesNeeded = chunkSize;
                        var bytesRead   = 0;
                        while (bytesNeeded > 0)
                        {
                            var partialRead = stream.Read(buffer, bytesRead, bytesNeeded);
                            if (partialRead == 0)
                            {
                                break; // EOF may or may not have a partial chunk
                            }
                            bytesNeeded -= partialRead;
                            bytesRead   += partialRead;
                        }
                        if (bytesRead == 0)
                        {
                            break; // EOF no partial chunk
                        }
                        length += bytesRead;

                        byte[] data = buffer;
                        if (bytesRead < chunkSize)
                        {
                            data = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                        }

                        var chunk = new BsonDocument {
                            { "_id", BsonObjectId.GenerateNewId() },
                            { "files_id", files_id },
                            { "n", n },
                            { "data", new BsonBinaryData(data) }
                        };
                        chunks.Insert(chunk, settings.SafeMode);

                        md5Algorithm.TransformBlock(data, 0, data.Length, null, 0);

                        if (bytesRead < chunkSize)
                        {
                            break; // EOF after partial chunk
                        }
                    }

                    md5Algorithm.TransformFinalBlock(new byte[0], 0, 0);
                    md5Client = BsonUtils.ToHexString(md5Algorithm.Hash);
                }

                var md5Command = new CommandDocument {
                    { "filemd5", files_id },
                    { "root", settings.Root }
                };
                var md5Result = database.RunCommand(md5Command);
                var md5Server = md5Result.Response["md5"].AsString;

                if (!md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase))
                {
                    throw new MongoGridFSException("Upload client and server MD5 hashes are not equal.");
                }

                var          uploadDate = createOptions.UploadDate == DateTime.MinValue ? DateTime.UtcNow : createOptions.UploadDate;
                BsonDocument fileInfo   = new BsonDocument {
                    { "_id", files_id },
                    { "filename", remoteFileName },
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", md5Server },
                    { "contentType", createOptions.ContentType },                                 // optional
                    { "aliases", BsonArray.Create((IEnumerable <string>)createOptions.Aliases) }, // optional
                    { "metadata", createOptions.Metadata } // optional
                };
                files.Insert(fileInfo, settings.SafeMode);

                return(FindOneById(files_id));
            }
        }
        public void TestOpenCreateWithId()
        {
            _gridFS.Files.RemoveAll();
            _gridFS.Chunks.RemoveAll();
            _gridFS.Chunks.ResetIndexCache();

            var createOptions = new MongoGridFSCreateOptions
            {
                Id = 1
            };
            using (var stream = _gridFS.Create("test", createOptions))
            {
                var bytes = new byte[] { 1, 2, 3, 4 };
                stream.Write(bytes, 0, 4);
            }

            var fileInfo = _gridFS.FindOne("test");
            Assert.AreEqual(BsonInt32.Create(1), fileInfo.Id);
        }
Example #47
0
 /// <summary>
 /// Copies a GridFS file.
 /// </summary>
 /// <param name="sourceFileName">The source file name.</param>
 /// <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 sourceFileName,
     string destFileName,
     MongoGridFSCreateOptions createOptions)
 {
     if (_settings.ReadPreference != ReadPreference.Primary)
     {
         var gridFS = GetPrimaryGridFSSettings();
         return gridFS.CopyTo(sourceFileName, destFileName, createOptions);
     }
     var fileInfo = FindOne(sourceFileName);
     if (fileInfo == null)
     {
         var message = string.Format("GridFS file '{0}' not found.", sourceFileName);
         throw new FileNotFoundException(message);
     }
     return fileInfo.CopyTo(destFileName, createOptions);
 }
Example #48
0
 /// <summary>
 /// Creates or opens a GridFS file for writing UTF-8 encoded text.
 /// </summary>
 /// <param name="remoteFileName">The remote file name.</param>
 /// <param name="createOptions">The create options.</param>
 /// <returns>A stream writer.</returns>
 public StreamWriter CreateText(string remoteFileName, MongoGridFSCreateOptions createOptions)
 {
     if (_settings.ReadPreference != ReadPreference.Primary)
     {
         var gridFS = GetPrimaryGridFSSettings();
         return gridFS.CreateText(remoteFileName, createOptions);
     }
     using (_server.RequestStart(null, ReadPreference.Primary))
     {
         var serverInstance = _server.RequestConnection.ServerInstance;
         var fileInfo = new MongoGridFSFileInfo(_server, serverInstance, _databaseName, _settings, remoteFileName, createOptions);
         return fileInfo.CreateText();
     }
 }
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions)
        {
            if (_settings.ReadPreference != ReadPreference.Primary)
            {
                var gridFS = WithReadPreferencePrimary();
                return(gridFS.Upload(stream, remoteFileName, createOptions));
            }
            using (_server.RequestStart(ReadPreference.Primary))
            {
                var connectionId = _server.RequestConnectionId;
                EnsureIndexes();

                var database         = GetDatabase(ReadPreference.Primary);
                var chunksCollection = GetChunksCollection(database);
                var filesCollection  = GetFilesCollection(database);

                var files_id  = createOptions.Id ?? ObjectId.GenerateNewId();
                var chunkSize = (createOptions.ChunkSize == 0) ? _settings.ChunkSize : createOptions.ChunkSize;
                var buffer    = new byte[chunkSize];

                var    length    = 0L;
                string md5Client = null;
                using (var md5Algorithm = _settings.VerifyMD5 ? IncrementalHash.CreateHash(HashAlgorithmName.MD5) : null)
                {
                    for (var n = 0L; true; n++)
                    {
                        // might have to call Stream.Read several times to get a whole chunk
                        var bytesNeeded = chunkSize;
                        var bytesRead   = 0;
                        while (bytesNeeded > 0)
                        {
                            var partialRead = stream.Read(buffer, bytesRead, bytesNeeded);
                            if (partialRead == 0)
                            {
                                break; // EOF may or may not have a partial chunk
                            }
                            bytesNeeded -= partialRead;
                            bytesRead   += partialRead;
                        }
                        if (bytesRead == 0)
                        {
                            break; // EOF no partial chunk
                        }
                        length += bytesRead;

                        byte[] data = buffer;
                        if (bytesRead < chunkSize)
                        {
                            data = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                        }

                        var chunk = new BsonDocument
                        {
                            { "_id", ObjectId.GenerateNewId() },
                            { "files_id", files_id },
                            { "n", n < int.MaxValue ? (BsonValue)(BsonInt32)(int)n : (BsonInt64)n },
                            { "data", new BsonBinaryData(data) }
                        };
                        chunksCollection.Insert(chunk, _settings.WriteConcern);

                        if (_settings.VerifyMD5)
                        {
                            md5Algorithm.AppendData(data, 0, data.Length);
                        }

                        if (bytesRead < chunkSize)
                        {
                            break; // EOF after partial chunk
                        }
                    }

                    if (_settings.VerifyMD5)
                    {
                        md5Client = BsonUtils.ToHexString(md5Algorithm.GetHashAndReset());
                    }
                }

                string md5Server = null;
                if (_settings.UpdateMD5 || _settings.VerifyMD5)
                {
                    var md5Command = new CommandDocument
                    {
                        { "filemd5", files_id },
                        { "root", _settings.Root }
                    };
                    var md5Result = database.RunCommand(md5Command);
                    md5Server = md5Result.Response["md5"].AsString;
                }

                if (_settings.VerifyMD5 && !md5Client.Equals(md5Server, StringComparison.OrdinalIgnoreCase))
                {
                    throw new MongoGridFSException(connectionId, "Upload client and server MD5 hashes are not equal.");
                }

                var          uploadDate = (createOptions.UploadDate == DateTime.MinValue) ? DateTime.UtcNow : createOptions.UploadDate;
                var          aliases    = (createOptions.Aliases != null) ? new BsonArray(createOptions.Aliases) : null;
                BsonDocument fileInfo   = new BsonDocument
                {
                    { "_id", files_id },
                    { "filename", remoteFileName, !string.IsNullOrEmpty(remoteFileName) }, // optional
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", (md5Server == null) ? (BsonValue)BsonNull.Value : new BsonString(md5Server) },
                    { "contentType", createOptions.ContentType, !string.IsNullOrEmpty(createOptions.ContentType) }, // optional
                    { "aliases", aliases, aliases != null },                                                        // optional
                    { "metadata", createOptions.Metadata, createOptions.Metadata != null } // optional
                };
                filesCollection.Insert(fileInfo, _settings.WriteConcern);

                return(FindOneById(files_id));
            }
        }
Example #50
0
        /// <summary>
        /// Uploads a GridFS file.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="remoteFileName">The remote file name.</param>
        /// <param name="createOptions">The create options.</param>
        /// <returns>The file info of the new GridFS file.</returns>
        public MongoGridFSFileInfo Upload(
            Stream stream,
            string remoteFileName,
            MongoGridFSCreateOptions createOptions
            )
        {
            using (database.RequestStart()) {
                EnsureIndexes();

                var files_id  = createOptions.Id ?? BsonObjectId.GenerateNewId();
                var chunkSize = createOptions.ChunkSize == 0 ? settings.ChunkSize : createOptions.ChunkSize;
                var buffer    = new byte[chunkSize];

                var length = 0;
                for (int n = 0; true; n++)
                {
                    int bytesRead = stream.Read(buffer, 0, chunkSize);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    length += bytesRead;

                    byte[] data = buffer;
                    if (bytesRead < chunkSize)
                    {
                        data = new byte[bytesRead];
                        Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
                    }

                    var chunk = new BsonDocument {
                        { "_id", BsonObjectId.GenerateNewId() },
                        { "files_id", files_id },
                        { "n", n },
                        { "data", new BsonBinaryData(data) }
                    };
                    chunks.Insert(chunk, settings.SafeMode);

                    if (bytesRead < chunkSize)
                    {
                        break;
                    }
                }

                var md5Command = new CommandDocument {
                    { "filemd5", files_id },
                    { "root", settings.Root }
                };
                var md5Result = database.RunCommand(md5Command);
                var md5       = md5Result.Response["md5"].AsString;

                var          uploadDate = createOptions.UploadDate == DateTime.MinValue ? DateTime.UtcNow : createOptions.UploadDate;
                BsonDocument fileInfo   = new BsonDocument {
                    { "_id", files_id },
                    { "filename", remoteFileName },
                    { "length", length },
                    { "chunkSize", chunkSize },
                    { "uploadDate", uploadDate },
                    { "md5", md5 },
                    { "contentType", createOptions.ContentType },                                 // optional
                    { "aliases", BsonArray.Create((IEnumerable <string>)createOptions.Aliases) }, // optional
                    { "metadata", createOptions.Metadata } // optional
                };
                files.Insert(fileInfo, settings.SafeMode);

                return(FindOneById(files_id));
            }
        }