public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName
 )
     : this(gridFS, remoteFileName, gridFS.Settings.DefaultChunkSize)
 {
 }
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     BsonDocument fileInfoDocument
 )
 {
     this.gridFS = gridFS;
     LoadFileInfo(fileInfoDocument);
 }
Exemple #3
0
        public void TestRemoveAllGFSandDelete()
        {
            var         server       = MongoServer.Create("mongodb://localhost:27017");
            var         db           = server.GetDatabase("dcm");
            var         gridSettings = new MongoGridFSSettings();
            MongoGridFS fs           = db.GetGridFS(gridSettings);

            fs.Files.RemoveAll();
        }
        public void TestConstructorFreezesSettings()
        {
            var settings = new MongoGridFSSettings();

            Assert.False(settings.IsFrozen);
            var gridFS = new MongoGridFS(_server, _database.Name, settings);

            Assert.True(gridFS.Settings.IsFrozen);
        }
        public void TestConstructorFeezesSettings()
        {
            var settings = new MongoGridFSSettings();

            Assert.IsFalse(settings.IsFrozen);
            var gridFS = new MongoGridFS(_database, settings);

            Assert.IsTrue(gridFS.Settings.IsFrozen);
        }
Exemple #6
0
        private void Init()
        {
            IndexKeysBuilder    keys        = IndexKeys.Ascending("metadata.directory_name");
            IndexOptionsBuilder options     = IndexOptions.SetName("directory_name").SetBackground(false);
            MongoGridFS         mongoGridFs = GetGridFS();

            mongoGridFs.EnsureIndexes();
            mongoGridFs.Files.EnsureIndex(keys, options);
        }
 public void TestFixtureSetup()
 {
     _server   = Configuration.TestServer;
     _database = Configuration.TestDatabase;
     _gridFS   = _database.GridFS;
     _gridFS.Chunks.RemoveAll();
     _gridFS.Chunks.ResetIndexCache();
     _gridFS.Files.RemoveAll();
 }
        /// <summary>
        /// Construct MongoQueue
        /// </summary>
        /// <param name="collection">collection</param>
        /// <exception cref="ArgumentNullException">collection is null</exception>
        public Queue(MongoCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            this.collection = collection;
            this.gridfs     = collection.Database.GetGridFS(MongoGridFSSettings.Defaults);
        }
Exemple #9
0
        public GridFs(string mongoDbConnectionString, string dbName, string prefixPath)
        {
            _prefixPath = prefixPath;
            var mongoClient   = new MongoClient(mongoDbConnectionString);
            var mongoServer   = mongoClient.GetServer();
            var mongoDatabase = mongoServer.GetDatabase(dbName);

            _disposableStartResult = mongoServer.RequestStart(mongoDatabase);
            _gridFs = mongoDatabase.GridFS;
        }
Exemple #10
0
        private void InternalMoveFile(string fromVirtualPath, string destinationVirtualPath)
        {
            MongoGridFS mongoGridFs          = GetGridFS();
            string      fixedDestinationPath = FixPath(destinationVirtualPath);

            mongoGridFs.MoveTo(FixPath(fromVirtualPath), fixedDestinationPath);
            MongoGridFSFileInfo fileInfo = mongoGridFs.FindOne(fixedDestinationPath);

            mongoGridFs.SetMetadata(fileInfo, CreateMetadata(fixedDestinationPath, fileInfo.Metadata["is_directory"] == new BsonBoolean(true)));
        }
Exemple #11
0
        public void ConstructorFeezesSettingsTest()
        {
            var settings = new MongoGridFSSettings();

            settings.IsFrozen.Should().Be.False();

            var gridFS = new MongoGridFS(Database, settings);

            gridFS.Settings.IsFrozen.Should().Be.True();
        }
        /// <summary>
        /// One-time static initialization of the _gridFs variable for the static Files class.
        /// </summary>
        static Files()
        {
            string        connectionString = ConfigurationManager.ConnectionStrings["MongoServerSettings"].ConnectionString;
            MongoUrl      conBuilder       = new MongoUrl(connectionString);
            MongoClient   client           = new MongoClient(connectionString);
            MongoServer   server           = client.GetServer();
            MongoDatabase db = server.GetDatabase(conBuilder.DatabaseName ?? "Files");

            _gridFs = db.GridFS;
        }//ctor
Exemple #13
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public UploadResult UploadFile(HttpContextBase context, string collection)
        {
            var client = MongoDbServer.MongoDbClient;
            var server = client.GetServer();
            HttpPostedFileBase file   = context.Request.Files[0];
            UploadResult       Result = new UploadResult()
            {
                State = UploadState.Unknown
            };
            var Size    = file.ContentLength * 1.0 / 1024 / 1024;
            var extName = System.IO.Path.GetExtension(file.FileName).ToLower();

            Result.Url            = FileDomain;
            Result.OriginFileName = file.FileName;
            if (CustomConfig.FileExts.Contains(extName))
            {
                Random rd     = new Random();
                var    fileId = DateTime.Now.Ticks + rd.Next(9999) + extName;
                if (Size < CustomConfig.CanUploadFileSize)
                {
                    if (Size <= 6)
                    {
                        SunFile sunfile = new SunFile();
                        byte[]  data    = new byte[file.ContentLength];
                        file.InputStream.Read(data, 0, data.Length);
                        sunfile.Id   = fileId;
                        sunfile.Data = data;
                        sunfile.Time = DateTime.Now;
                        var imgCollection = server.GetDatabase(fileDatabase).GetCollection <SunFile>(collection);
                        imgCollection.Insert(sunfile);

                        Result.Url  += "/files/SmallFile/" + client.DbGroupName + "/" + collection + "/" + fileId;
                        Result.State = UploadState.Success;
                    }
                    else
                    {
                        MongoGridFS gfs = new MongoGridFS(server, fileDatabase, new MongoGridFSSettings());
                        gfs.Upload(file.InputStream, fileId);
                        Result.Url  += "/files/LargeFile/" + client.DbGroupName + "/" + fileId;
                        Result.State = UploadState.Success;
                    }
                    Result.FileId = fileId;
                }
                else
                {
                    Result.State = UploadState.SizeLimitExceed;
                }
            }
            else
            {
                Result.State = UploadState.TypeNotAllow;
            }
            return(Result);
        }
Exemple #14
0
        public Dictionary <string, string> BuscarArquivo(string id, ref MemoryStream retorno)
        {
            var fileInfo  = database.GridFS.FindOne(Query.EQ("_id", new BsonObjectId(new ObjectId(id))));
            var mySetting = new MongoGridFSSettings();
            var gfs       = new MongoGridFS(server, database.Name, mySetting);

            gfs.Download(retorno, fileInfo);
            return(new Dictionary <string, string> {
                { fileInfo.ContentType, fileInfo.Name }
            });
        }
Exemple #15
0
        public void TestFixtureSetup()
        {
            server   = MongoServer.Create("mongodb://localhost/?safe=true");
            database = server["onlinetests"];
            var settings = new MongoGridFSSettings {
                ChunkSize = 16,
                SafeMode  = SafeMode.True
            };

            gridFS = database.GetGridFS(settings);
        }
 public MongoGridFSFileInfo(
     MongoGridFS gridFS,
     string remoteFileName,
     int chunkSize
 )
 {
     this.gridFS = gridFS;
     this.chunkSize = chunkSize;
     this.id = BsonObjectId.GenerateNewId();
     this.name = remoteFileName;
 }
Exemple #17
0
        public void TestFixtureSetup()
        {
            _database = LegacyTestConfiguration.Database;
            var settings = new MongoGridFSSettings
            {
                ChunkSize    = 16,
                WriteConcern = WriteConcern.Acknowledged
            };

            _gridFS = _database.GetGridFS(settings);
        }
Exemple #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="databasename"></param>
        /// <param name="rootName"></param>
        /// <returns></returns>
        private MongoGridFS GetGridFs(string databasename, string rootName)
        {
            MongoDatabase       dbName    = _msever.GetDatabase(databasename);
            MongoGridFSSettings fsSetting = new MongoGridFSSettings()
            {
                Root = rootName
            };
            MongoGridFS gf = new MongoGridFS(dbName, fsSetting);

            return(gf);
        }
        protected override void OnTestFixtureSetUp()
        {
            base.OnTestFixtureSetUp();

            var settings = new MongoGridFSSettings
            {
                ChunkSize = 16,
                SafeMode  = SafeMode.True
            };

            gridFS = Database.GetGridFS(settings);
        }
        public void TestFixtureSetup()
        {
            _server   = Configuration.TestServer;
            _database = Configuration.TestDatabase;
            var settings = new MongoGridFSSettings(_database)
            {
                ChunkSize    = 16,
                WriteConcern = WriteConcern.Acknowledged
            };

            _gridFS = _database.GetGridFS(settings);
        }
Exemple #21
0
        public void TestFixtureSetup()
        {
            _server   = Configuration.TestServer;
            _database = Configuration.TestDatabase;
            var settings = new MongoGridFSSettings(_database)
            {
                ChunkSize = 16,
                SafeMode  = SafeMode.True
            };

            _gridFS = _database.GetGridFS(settings);
        }
        public PatientRepository()
        {
            _server = new MongoServer(new MongoServerSettings {
                Server = new MongoServerAddress(_DBHOST), SafeMode = SafeMode.True
            });

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

            new MongoDB.Web.Providers.MongoDBMembershipProvider();
        }
Exemple #23
0
        public BlobTest()
        {
            JsonWriterSettings.Defaults.Indent = true;
            var mongoClientSettings = MongoClientSettings.FromUrl(new MongoUrl("mongodb://localhost"));
            var mongoServer         = new MongoServer(MongoServerSettings.FromClientSettings(mongoClientSettings));

            _mongoGridFs = new MongoGridFS(mongoServer, "Test", new MongoGridFSSettings());


            var mongoClient = new MongoClient(mongoClientSettings);

            _blobDataBase = mongoClient.GetDatabase("Test");
        }
Exemple #24
0
        /// <summary>
        ///     Create a MongoReaderPlugin from plug-in arguments
        /// </summary>
        /// <param name="args"></param>
        public MongoReaderPlugin(NameValueCollection args)
        {
            VirtualFilesystemPrefix = string.IsNullOrEmpty(args["prefix"]) ? "~/gridfs/" : args["prefix"];

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

            // Using new client, server database initialization. Wordy but recommended.
            var mongoClient = new MongoClient(mongoUrl);
            var mongoServer = mongoClient.GetServer();

            _db           = mongoServer.GetDatabase(mongoUrl.DatabaseName);
            _gridSettings = new MongoGridFSSettings();
            _grid         = _db.GetGridFS(_gridSettings);
        }
Exemple #25
0
        public MongoDbRepository(MongoDbInstance mongoInstance)
        {
            var    type           = typeof(T);
            string collectionName = type.Name;
            var    tbAttrObj      = type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault();
            var    tbAttr         = tbAttrObj as TableAttribute;

            if (tbAttr != null && !string.IsNullOrEmpty(tbAttr.Name))
            {
                collectionName = tbAttr.Name;
            }

            this._mongoCollection = mongoInstance._mongoDatabase.GetCollection <T>(collectionName);
            this._mongoGridFile   = mongoInstance._gridFs;
        }
Exemple #26
0
        public virtual void Setup()
        {
            collection = new MongoClient(ConfigurationManager.AppSettings["mongoQueueUrl"])
                         .GetServer()
                         .GetDatabase(ConfigurationManager.AppSettings["mongoQueueDb"])
                         .GetCollection(ConfigurationManager.AppSettings["mongoQueueCollection"]);

            collection.Drop();

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

            queue = new Queue();
        }
Exemple #27
0
        /// <summary>
        /// 读取报表结果
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="rootName"></param>
        /// <returns></returns>
        public string ReadFileFromMongoDb(string filename, string rootName)
        {
            string              tablestr;
            MongoGridFS         fs     = GetGridFs(Dbname, rootName);
            MongoGridFSFileInfo gfInfo = new MongoGridFSFileInfo(fs, filename);

            using (MongoGridFSStream gfs = gfInfo.OpenRead())
            {
                using (TextReader reader = new StreamReader(gfs, Encoding.UTF8))
                {
                    tablestr = reader.ReadToEnd();
                }
            }
            return(tablestr);
        }
Exemple #28
0
        /// <summary>
        /// 下载文档到本地
        /// </summary>
        /// <param name="localfile"></param>
        /// <param name="remoteFile"></param>
        public void Copy(string localfile, string remoteFile)
        {
            _logger.DebugFormat("Copy {0} to {1}.", localfile, remoteFile);

            try
            {
                MongoGridFS fs = new MongoGridFS(_context.DataBase);
                fs.Download(localfile, remoteFile);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
Exemple #29
0
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public bool Exist(string remoteFile)
        {
            _logger.DebugFormat("Exist, Id {0}.", remoteFile);

            try
            {
                MongoGridFS fs = new MongoGridFS(_context.DataBase);
                return(fs.Exists(remoteFile));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
        public ComputerContext()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MongoDb"].ConnectionString;
            var    con = new MongoUrlBuilder(connectionString);

            client   = new MongoClient(connectionString);
            database = client.GetDatabase(con.DatabaseName);
            gridFS   = new MongoGridFS(
                new MongoServer(
                    new MongoServerSettings {
                Server = con.Server
            }),
                con.DatabaseName,
                new MongoGridFSSettings()
                );
        }
Exemple #31
0
        /// <summary>
        /// 保存报表结果
        /// </summary>
        /// <param name="savsString"></param>
        /// <param name="rootName"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public void SaveFileToMongoDb(string fileName, string savsString, string rootName)
        {
            //BsonDocument doc = new BsonDocument();
            //doc.Add("UserID", 1L);
            //option.Metadata = doc;
            MongoGridFS gf = GetGridFs(Dbname, rootName);

            using (MongoGridFSStream gfs = gf.Create(fileName, new MongoGridFSCreateOptions()
            {
                UploadDate = DateTime.Now
            }))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(savsString);
                gfs.Write(bytes, 0, bytes.Length);
            }
        }
Exemple #32
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="remoteFile"></param>
        public void Delete(string remoteFile)
        {
            _logger.DebugFormat("Delete File, Id:{0}", remoteFile);

            try
            {
                MongoGridFS fs = new MongoGridFS(_context.DataBase);
                fs.Delete(remoteFile);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                _logger.Error(ex.StackTrace);
                throw;
            }
        }
Exemple #33
0
        /// <summary>
        /// 生成User测试数据
        /// </summary>
        /// <param name="mongosvr"></param>
        internal static void FillDataForUser(MongoServer mongosvr)
        {
            MongoDatabase mongodb = mongosvr.GetDatabase("mongodb");

            MongoCollection <BsonDocument> mongoJsCol = mongodb.GetCollection <BsonDocument>("system.js");

            mongoJsCol.RemoveAll();
            mongoJsCol.Insert <BsonDocument>(
                new BsonDocument().Add("_id", "sum")
                .Add("value", "function (x, y) { return x + y; }"));
            MongoGridFS            mongofs  = mongodb.GetGridFS(new MongoGridFSSettings());
            MongoCollection <User> mongoCol = mongodb.GetCollection <User>("User");

            mongoCol.RemoveAll();
            Random Ro = new Random();

            ///HugeData
            for (int i = 0; i < 1000; i++)
            {
                mongoCol.Insert(new User()
                {
                    ID      = i.ToString(),
                    Name    = "Tom",
                    Age     = (byte)Ro.Next(100),
                    Age2    = (byte)Ro.Next(100),
                    Age3    = (byte)Ro.Next(100),
                    address = new Address()
                    {
                        street = "123 Main St.",
                        City   = "Centerville",
                        state  = "PA",
                        Zip    = Ro.Next(20),
                        GeoObj = new GeoObject[] {
                            new GeoObject()
                            {
                                ID  = "aaaa",
                                Geo = new int[2] {
                                    1, 1
                                }
                            }
                        },
                    },
                    Pets = new string[] { "Cat", "Dog" },
                });
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoGridFSDataBus"/> class.
 /// </summary>
 /// <param name="mongoFactory">
 /// The MongoDB factory.
 /// </param>
 public MongoGridFSDataBus(MongoDatabaseFactory mongoFactory)
 {
     Contract.Requires<ArgumentNullException>(mongoFactory != null, "mongoFactory != null");
     this.gridFS = mongoFactory.GetDatabase().GridFS.AssumedNotNull();
 }