Пример #1
0
        public string InsertFileByPath(string set_name, string file_path, Dictionary <object, object> info = null)
        {
            MongoGridFSSettings mgfs = new MongoGridFSSettings();

            mgfs.Root = set_name;
            MongoGridFSCreateOptions mgfsco = new MongoGridFSCreateOptions();

            if (info == null)
            {
                info = new Dictionary <object, object>();
            }
            FileInfo fi = new FileInfo(file_path);

            info.Add("file_name", fi.Name);
            info.Add("timestamp", GetTimestamp());
            info.Add("content_type", fi.Extension);
            mgfsco.Metadata = new BsonDocument(info);
            if (fi.Exists)
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    MongoGridFSFileInfo file_info = mdbs.GetGridFS(mgfs).Upload(fs, fi.Name, mgfsco);
                    if (file_info.Exists)
                    {
                        return(file_info.Id.ToString());
                    }
                }
            }
            return(null);
        }
        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 settings = new MongoGridFSSettings();
            var info     = new MongoGridFSFileInfo(_server, _server.Primary, _database.Name, settings, "filename", createOptions);

            Assert.IsTrue(aliases.SequenceEqual(info.Aliases));
            Assert.AreEqual(123, info.ChunkSize);
            Assert.AreEqual("content", info.ContentType);
            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);
        }
Пример #3
0
        public Stream OpenStream(string remoteFile, string mimetype)
        {
            _logger.DebugFormat("Open MongoDB By Stream, Id {0}.", remoteFile);

            Stream stream = null;

            try
            {
                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions
                {
                    Id          = remoteFile,
                    UploadDate  = DateTime.Now,
                    ContentType = mimetype,
                };

                MongoGridFS fs = new MongoGridFS(_context.DataBase);
                stream = fs.OpenWrite(remoteFile, option);
                return(stream);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                if (stream != null)
                {
                    stream.Close();
                }
                throw;
            }
        }
Пример #4
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;
            }
        }
Пример #5
0
        public List <string> InsertFilesByPath(string set_name, string directory, Dictionary <object, object> infos = null)
        {
            MongoGridFSSettings mgfs = new MongoGridFSSettings();

            mgfs.Root = set_name;
            List <string> ids     = new List <string>();
            DirectoryInfo dirInfo = new DirectoryInfo(directory);

            if (dirInfo.Exists)
            {
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    MongoGridFSCreateOptions    mgfsco = new MongoGridFSCreateOptions();
                    Dictionary <object, object> info   = new Dictionary <object, object>();
                    info.Add("file_name", file.Name);
                    info.Add("timestamp", GetTimestamp());
                    info.Add("content_type", file.Extension);
                    if (infos != null)
                    {
                        info.ToList().ForEach(item => info.Add(item.Key, item.Value));
                    }
                    mgfsco.Metadata = new BsonDocument(info);
                    using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
                    {
                        MongoGridFSFileInfo file_info = mdbs.GetGridFS(mgfs).Upload(fs, file.Name, mgfsco);
                        if (file_info.Exists)
                        {
                            ids.Add(file_info.Id.ToString());
                        }
                    }
                }
            }
            return(ids);
        }
Пример #6
0
        public void TestOpenWriteWithSecondaryReadPreferenceAndOptions()
        {
            _gridFS.Delete(Query.Null);
            var settings = new MongoGridFSSettings()
            {
                ReadPreference = ReadPreference.Secondary
            };
            var gridFS        = _database.GetGridFS(settings);
            var fileName      = "test.txt";
            var createOptions = new MongoGridFSCreateOptions
            {
                Aliases  = new[] { "test" },
                Id       = ObjectId.GenerateNewId(),
                Metadata = new BsonDocument {
                    { "a", 1 }
                }
            };

            using (var stream = gridFS.OpenWrite(fileName, createOptions))
            {
                stream.WriteByte(1);
            }
            var fileInfo = _gridFS.FindOne("test.txt");

            Assert.IsNotNull(fileInfo);
            Assert.AreEqual(createOptions.Aliases, fileInfo.Aliases);
            Assert.AreEqual(createOptions.Id, fileInfo.Id);
            Assert.AreEqual(createOptions.Metadata, fileInfo.Metadata);
        }
Пример #7
0
        /// <summary>
        /// 字节数组方式保存文件
        /// </summary>
        /// <param name="fileData">数据内容</param>
        /// <param name="fileName">文件名</param>
        /// <param name="fileCollectionName"></param>
        public virtual void SaveFileByByteArray(byte[] fileData, string fileName, string fileCollectionName)
        {
            try
            {
                if (0 == fileData.Length || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileCollectionName))
                {
                    throw new KnownException("缺失必需数据,无法保存数据!");
                }
                MongoGridFSSettings fsSetting = new MongoGridFSSettings()
                {
                    Root = fileCollectionName
                };

                //MongoGridFS fs = new MongoGridFS(_database, fsSetting);   //  将被遗弃的方法
                MongoGridFS fs = new MongoGridFS(_server, _database.Name, fsSetting);
                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions {
                    UploadDate = DateTime.Now
                };
                using (MongoGridFSStream gfs = fs.Create(fileName, option))
                {
                    gfs.Write(fileData, 0, fileData.Length);
                    gfs.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //  设定查询集合的名称
        }
        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);
        }
        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.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());
        }
Пример #10
0
        public void Upload(string job_id, UploadedFile file)
        {
            var gfs     = Repository.Database.GridFS;
            var options = new MongoGridFSCreateOptions
            {
                Metadata = new BsonDocument(new BsonElement("job_id", job_id))
            };
            var info       = gfs.Upload(file.InputStream, file.FileName, options);
            var attachment = FromFileInfo(info);

            var query  = Query.EQ("_id", ObjectId.Parse(job_id));
            var update = UpdateBuilder.AddToSet("attachment_ids", attachment.id);

            Jobs.Collection.Update(query, update);

            var units = Plugin.TryParse(attachment);

            if (units.Count() > 0)
            {
                var ids = new List <string>();
                foreach (var unit in units)
                {
                    ids.Add(Units.Create(unit).id);
                }
                var units_update = UpdateBuilder.AddToSetEach("unit_ids", new BsonArray(ids));
                Jobs.Collection.Update(query, units_update);
            }
        }
Пример #11
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\" />";
            }
        }
Пример #12
0
        /// <summary>
        /// 流模式添加文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public MetaInfo AddStream(Stream stream, string mimetype, string remoteFile)
        {
            _logger.DebugFormat("Add File By Stream, Id {0}.", remoteFile);

            try
            {
                MongoGridFSCreateOptions option = new MongoGridFSCreateOptions
                {
                    Id          = remoteFile,
                    UploadDate  = DateTime.Now,
                    ContentType = mimetype,
                };

                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;
            }
        }
Пример #13
0
        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);
        }
Пример #14
0
        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);
        }
Пример #15
0
        public void UploadTest()
        {
            gridFS.Delete(Query.Null);
            Assert.AreEqual(0, gridFS.Chunks.Count());
            Assert.AreEqual(0, gridFS.Files.Count());

            using (var uploadStream = new MemoryStream(ContentBytes)) {
                var createOptions = new MongoGridFSCreateOptions
                {
                    Aliases     = new[] { UploadFileName, "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, UploadFileName, 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(ContentBytes.Length, fileInfo.Length);
                Assert.IsTrue(!string.IsNullOrEmpty(fileInfo.MD5));
                Assert.AreEqual(createOptions.Metadata, fileInfo.Metadata);
                Assert.AreEqual(UploadFileName, fileInfo.Name);
                Assert.AreEqual(createOptions.UploadDate.ToMongoDateTime(), fileInfo.UploadDate);
            }
        }
Пример #16
0
        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));
        }
Пример #17
0
        public MongoObjectId SaveFile(string filename, byte[] fileBytes, string contentType)
        {
            Stream stream  = new MemoryStream(fileBytes);
            var    options = new MongoGridFSCreateOptions();

            options.ContentType = contentType;
            var file = db.GridFS.Upload(stream, filename, options);

            return((MongoObjectId)file.Id);
        }
Пример #18
0
        //internal static IMongoFile DBLoadGridFS(IMongoFile file)
        //{
        //    using (IDBClient client = DBFactory.GetClient(typeof(IMongoFile)))
        //    {
        //        file.Attach(client.GridFS.FindOneById(file.Id));
        //        return file;
        //    }
        //}
        internal static MongoGridFSCreateOptions BuildMongoGridFSCreateOptions(IMongoFile file)
        {
            MongoGridFSCreateOptions options = new MongoGridFSCreateOptions();

            options.Id          = file.Id;
            options.ChunkSize   = file.Size;
            options.ContentType = file.ContentType;
            options.Aliases     = file.Aliases;
            options.Metadata    = file.Metadata;
            options.UploadDate  = file.UploadDate;
            return(options);
        }
Пример #19
0
        public void Save()
        {
            var gridFS = GetGridFS();

            if (IsPersisted)
            {
                if (!IsLoaded)
                {
                    Load();
                }

                if (_contentChanged || _fileNameChanged)
                {
                    gridFS.DeleteById(ID);
                    var options = new MongoGridFSCreateOptions
                    {
                        ContentType = ContentType,
                        Id          = ID,
                        UploadDate  = DateTime.UtcNow,
                        Metadata    = _metadata
                    };
                    gridFS.Upload(Content, FileName, options);
                }
                else
                {
                    if (_contentTypeChanged)
                    {
                        gridFS.SetContentType(_fileInfo, _contentType);
                    }
                    // Metadata is a BsonDocument - we can't detect if it's changed, so always save it.
                    gridFS.SetMetadata(_fileInfo, _metadata);
                }
            }
            else
            {
                ID = ObjectId.GenerateNewId();

                var options = new MongoGridFSCreateOptions
                {
                    ContentType = _contentType,
                    Id          = ID,
                    UploadDate  = DateTime.UtcNow,
                    Metadata    = _metadata
                };
                gridFS.Upload(_content, _fileName, options);

                IsPersisted = true;
            }

            _contentChanged     = false;
            _fileNameChanged    = false;
            _contentTypeChanged = false;
        }
Пример #20
0
        private string InsertFileToDB(HttpPostedFileBase file)
        {
            ObjectId fileID1 = ObjectId.GenerateNewId();

            var options = new MongoGridFSCreateOptions
            {
                Id          = fileID1,
                ContentType = file.ContentType
            };

            Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
            return(fileID1.ToString());
        }
Пример #21
0
        // modify operation
        private void StoreImage(HttpPostedFileBase file, string rentalId)
        {
            var imageId = ObjectId.GenerateNewId();

            SetRentalImageId(rentalId, imageId.ToString());
            var options = new MongoGridFSCreateOptions()
            {
                Id          = imageId,
                ContentType = file.ContentType
            };

            Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
        }
        private void AttachImageToCar(HttpPostedFileBase file, Car car)
        {
            ObjectId imageId = ObjectId.GenerateNewId();

            car.ImageId = imageId.ToString();
            CarRentalContext.Cars.Save(car);
            MongoGridFSCreateOptions createOptions = new MongoGridFSCreateOptions()
            {
                Id            = imageId
                , ContentType = file.ContentType
            };

            CarRentalContext.CarRentalDatabase.GridFS.Upload(file.InputStream, file.FileName, createOptions);
        }
        private void StoreImage(HttpPostedFileBase file, Rental rental)
        {
            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);
        }
Пример #24
0
        public void Upload()
        {
            var pathToFile = "credolab.jpg";
            var fileStream = File.Open(pathToFile, FileMode.Open);

            var option = new MongoGridFSCreateOptions()
            {
                Id          = ObjectId.GenerateNewId(),
                ContentType = Path.GetExtension(pathToFile),
                Metadata    = new BsonDocument()
                {
                    { "creator", "Vitek" }
                }
            };

            _mongoGridFs.Upload(fileStream, Path.GetFileName(pathToFile), option);
        }
Пример #25
0
        public void TestUploadStreamFile2GridFS()
        {
            var server = MongoServer.Create("mongodb://*****:*****@"D:\Download\FileTestUpload\Hello2.txt", FileMode.Open, FileAccess.Read);

            System.IO.Stream strm = fs;

            MongoGridFS file            = new MongoGridFS(db);
            MongoGridFSCreateOptions op = new MongoGridFSCreateOptions();

            op.Aliases = new string[] { "Home" };

            var upFile = file.Upload(strm, "SayHi", op);

            Console.WriteLine("MD5: {0}", upFile.MD5);
        }
Пример #26
0
        public string Add(string path, Stream stream, string contentType, string category)
        {
            var gridFs  = client.GetServer().GetDatabase(this.dbname).GridFS;
            var options = new MongoGridFSCreateOptions();

            if (contentType != null)
            {
                options.ContentType = contentType;
            }
            if (category != null)
            {
                options.Metadata = new MongoDB.Bson.BsonDocument();
                options.Metadata.Add(category, BsonValue.Create(category));
            }
            options.UploadDate = DateTime.Now;
            var result = gridFs.Upload(stream, path, options);

            return(result.Id.ToString());
        }
Пример #27
0
        private void AgregarImagenCarro(HttpPostedFileBase file, CarModel car)
        {
            ObjectId imageId = ObjectId.GenerateNewId();

            car.ImageId = imageId.ToString();


            var document = dbContext.database.GetCollection <BsonDocument>("CarModel");
            var result   = document.Insert(car);

            MongoGridFSCreateOptions createOptions = new MongoGridFSCreateOptions()
            {
                Id = imageId
                ,
                ContentType = file.ContentType
            };

            dbContext.database.GridFS.Upload(file.InputStream, file.FileName, createOptions);
        }
Пример #28
0
        /// <summary>
        /// Actualiza o inserta el json sobre la colección.
        /// </summary>
        /// <param name="iMongoCollection">Objeto que define en que collection de MogoDB sera insertada la información.</param>
        /// <param name="oBlockStoreDocumentosyFiltros">Objeto que contiene el documento en </param>
        /// <returns>Resultado de la inserción</returns>
        public async Task <EntLogActualizarInsertar> actualizaroInsertar(IMongoCollection <BsonDocument> iMongoCollection, EntBlockStoreDocumentosyFiltros oBlockStoreDocumentosyFiltros)
        {
            var log = new EntLogActualizarInsertar {
                miReplaceOneResultsMongo = new List <ReplaceOneResult>(), miColleccionObjetosRepetidos = new EntBlockStoreDocumentosyFiltros {
                    filtrosBlockStore = new BsonDocument(), registroBlockStore = new BsonDocument()
                }, TieneError = false
            };

            try
            {
                var remplazar = await iMongoCollection.ReplaceOneAsync(oBlockStoreDocumentosyFiltros.filtrosBlockStore, options : new UpdateOptions {
                    IsUpsert = true
                }, replacement : oBlockStoreDocumentosyFiltros.registroBlockStore);

                if (oBlockStoreDocumentosyFiltros.EsValorChunks)
                {
                    var stream = new System.IO.MemoryStream();
                    var writer = new System.IO.StreamWriter(stream);
                    writer.Write(oBlockStoreDocumentosyFiltros.ValorHecho);
                    writer.Flush();
                    stream.Position = 0;
                    var options = new MongoGridFSCreateOptions
                    {
                        ChunkSize   = AbaxXBRLBlockStore.Common.Constants.ConstBlockStoreHechos.MAX_STRING_VALUE_LENGTH,
                        ContentType = "text/plain",
                        Metadata    = new BsonDocument
                        {
                            { "codigoHashRegistro", oBlockStoreDocumentosyFiltros.CodigoHashRegistro }
                        }
                    };

                    miConectionServer.ObtenerInterfaceGridFS().Upload(stream, oBlockStoreDocumentosyFiltros.CodigoHashRegistro, options);
                }
            }
            catch (Exception ex)
            {
                log.TieneError   = true;
                log.MensajeError = ex.Message;

                LogUtil.Error(ex);
            }
            return(log);
        }
Пример #29
0
        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);
        }
Пример #30
0
        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);
        }