Exemple #1
0
        public void TestAppendText()
        {
            Assert.IsFalse(_gridFS.Exists("HelloWorld.txt"));
            using (var writer = _gridFS.AppendText("HelloWorld.txt"))
            {
                Assert.IsFalse(writer.BaseStream.CanRead);
                Assert.IsTrue(writer.BaseStream.CanSeek);
                Assert.IsTrue(writer.BaseStream.CanWrite);
                writer.Write("Hello");
            }
            Assert.IsTrue(_gridFS.Exists("HelloWorld.txt"));
            using (var writer = _gridFS.AppendText("HelloWorld.txt"))
            {
                writer.Write(" World");
            }
            var memoryStream = new MemoryStream();

            _gridFS.Download(memoryStream, "HelloWorld.txt");
            var bytes = memoryStream.ToArray();

            Assert.AreEqual(0xEF, bytes[0]); // the BOM
            Assert.AreEqual(0xBB, bytes[1]);
            Assert.AreEqual(0xBF, bytes[2]);
            var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);

            Assert.AreEqual("Hello World", text);
        }
        public Tuple <byte[], byte[]> GetAssemblyBytes(string assemblyname)
        {
            string gridFileName = FormatGridFileName(assemblyname);

            if (m_grid.Exists(Query.Matches("filename", new BsonRegularExpression(new Regex("^" + Regex.Escape(gridFileName + ".dll") + "$", RegexOptions.IgnoreCase)))))
            {
                gridFileName = gridFileName + ".dll";
            }
            else
            {
                if (m_grid.Exists(Query.Matches("filename", new BsonRegularExpression(new Regex("^" + Regex.Escape(gridFileName + ".exe") + "$", RegexOptions.IgnoreCase)))))
                {
                    gridFileName = gridFileName + ".exe";
                }
                else
                {
                    Console.WriteLine("Assembly not found {0}", assemblyname);
                    return(null);
                }
            }

            byte[] asmBytes = ReadFile(gridFileName);
            byte[] pdbBytes = null;

            if (m_grid.Exists(Path.ChangeExtension(gridFileName, "pdb")))
            {
                pdbBytes = ReadFile(Path.ChangeExtension(gridFileName, "pdb"));
            }

            return(new Tuple <byte[], byte[]>(asmBytes, pdbBytes));
        }
Exemple #3
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;
            }
        }
Exemple #4
0
        /// <summary>
        /// 获取元数据信息
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public MetaInfo GetMeta(string remoteFile)
        {
            _logger.DebugFormat("GetMeta By Id{0}.", remoteFile);

            MongoGridFS fs = new MongoGridFS(_context.DataBase);

            if (!fs.Exists(remoteFile))
            {
                return(null);
            }

            var info = fs.FindOne(remoteFile);

            return(new MetaInfo
            {
                fileName = remoteFile,
                MD5 = info.MD5,
                MimeType = info.ContentType,
            });
        }
Exemple #5
0
        /// <summary>
        /// deletes file
        /// </summary>
        /// <param name="filepath"></param>
        public void Delete(string filepath)
        {
            if (string.IsNullOrWhiteSpace(filepath))
            {
                throw new ArgumentException("filepath cannot be null or empty");
            }

            //all filepaths are lowercase and all starts with folder separator
            filepath = filepath.ToLowerInvariant();
            if (!filepath.StartsWith(FOLDER_SEPARATOR))
            {
                filepath = FOLDER_SEPARATOR + filepath;
            }

            var sourceQuery = Query.EQ("filename", filepath);

            if (gfs.Exists(sourceQuery))
            {
                gfs.Delete(sourceQuery);
            }
        }
Exemple #6
0
        private static void Main()
        {
            var exit = false;

            _mongoClient = new MongoClient("mongodb://localhost");
            _db          = new MongoGridFS(_mongoClient.GetServer(), "Default",
                                           new MongoGridFSSettings());
            while (!exit)
            {
                Console.Write(GetPrepend());
                var command = Console.ReadLine();
                Debug.Assert(command != null, "command != null");
                if (command.Length == 0)
                {
                    continue;
                }
                //What the f**k?
                //Handles quotation marks in incoming commands
                var result = command.Split('"')
                             .Select((element, index) => index % 2 == 0
                        ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                        : new[] { element })
                             .SelectMany(element => element).ToList();
                switch (result[0].ToLower())
                {
                case "exit":
                    exit = true;
                    break;

                case "cd":
                    if (result.Count == 2)
                    {
                        if (result[1] == "..")
                        {
                            var sarray = _currentdirectory.Split('/').Where(x => x != "").ToArray();
                            var str    = "/";
                            for (var i = 0; i < sarray.Length - 1; i++)
                            {
                                str += sarray[i] + "/";
                            }
                            _currentdirectory = str;
                        }
                        else
                        {
                            _currentdirectory += result[1] + "/";
                        }
                    }
                    else
                    {
                        Console.WriteLine("  Usage: cd <dir>");
                    }
                    break;

                case "server":
                    _mongoClient = new MongoClient("mongodb://" + result[1]);
                    _db          = new MongoGridFS(_mongoClient.GetServer(), "Default",
                                                   new MongoGridFSSettings());
                    break;

                case "db":
                    _db = new MongoGridFS(_mongoClient.GetServer(), result[1],
                                          new MongoGridFSSettings());
                    break;

                case "ls":
                    if (_db != null)
                    {
                        var query = from file in _db.FindAll()
                                    where file.Name.StartsWith(_currentdirectory)
                                    select file;
                        foreach (var file in query)
                        {
                            Console.WriteLine("  " + file.Name);
                        }
                    }
                    break;

                case "put":
                    if (result.Count == 2)
                    {
                        var file = new FileInfo(result[1]);
                        if (!file.Exists)
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Uploading " + file.Name + "...");
                        Debug.Assert(_db != null, "_db != null");
                        _db.Upload(file.FullName, _currentdirectory + file.Name);
                        Console.WriteLine("Done!");
                    }
                    else if (result.Count == 3)
                    {
                        var file = new FileInfo(result[1]);
                        if (!file.Exists)
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Uploading " + file.Name + "...");
                        Debug.Assert(_db != null, "_db != null");
                        _db.Upload(file.FullName, result[2]);
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        Console.WriteLine("  Usage: put <src> [dest]");
                    }
                    break;

                case "get":
                    if (result.Count == 2)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Downloading " + result[1] + "...");
                        _db.Download(result[1], result[1]);
                        Console.WriteLine("Done!");
                    }
                    else if (result.Count == 3)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        Console.Write("  Downloading " + result[1] + "...");
                        _db.Download(result[2], result[1]);
                        Console.WriteLine("Done!");
                    }
                    else
                    {
                        Console.WriteLine("  Usage: get <src> [dest]");
                    }
                    break;

                case "del":
                    if (result.Count == 2)
                    {
                        Debug.Assert(_db != null, "_db != null");
                        if (!_db.Exists(result[1]))
                        {
                            Console.WriteLine("  File doesn't exist!");
                            break;
                        }
                        _db.Delete(result[1]);
                    }
                    else
                    {
                        Console.WriteLine("  Usage: del <filename>");
                    }
                    break;

                default:
                    Console.WriteLine("  Invalid Command");
                    break;
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <remarks>Mongo允许同名文件,因为id才是主键</remarks>
        /// <param name="strFileName"></param>
        public static UploadResult UpLoadFile(String strFileName, UpLoadFileOption Option)
        {
            MongoDatabase mongoDB    = SystemManager.GetCurrentDataBase();
            MongoGridFS   gfs        = mongoDB.GetGridFS(new MongoGridFSSettings());
            String        RemoteName = String.Empty;

            if (Option.FileNameOpt == enumGFSFileName.filename)
            {
                RemoteName = new FileInfo(strFileName).Name;
            }
            else
            {
                if (Option.DirectorySeparatorChar != Path.DirectorySeparatorChar)
                {
                    RemoteName = strFileName.Replace(Path.DirectorySeparatorChar, Option.DirectorySeparatorChar);
                }
                else
                {
                    RemoteName = strFileName;
                }
            }
            try
            {
                OnActionDone(new ActionDoneEventArgs(RemoteName + " Uploading "));
                if (!gfs.Exists(RemoteName))
                {
                    gfs.Upload(strFileName, RemoteName);
                    return(UploadResult.Complete);
                }
                else
                {
                    switch (Option.AlreadyOpt)
                    {
                    case enumGFSAlready.JustAddIt:
                        gfs.Upload(strFileName, RemoteName);
                        return(UploadResult.Complete);

                    case enumGFSAlready.RenameIt:
                        String ExtendName = new FileInfo(strFileName).Extension;
                        String MainName   = RemoteName.Substring(0, RemoteName.Length - ExtendName.Length);
                        int    i          = 1;
                        while (gfs.Exists(MainName + i.ToString() + ExtendName))
                        {
                            i++;
                        }
                        gfs.Upload(strFileName, MainName + i.ToString() + ExtendName);
                        return(UploadResult.Complete);

                    case enumGFSAlready.SkipIt:
                        return(UploadResult.Skip);

                    case enumGFSAlready.OverwriteIt:
                        gfs.Delete(RemoteName);
                        gfs.Upload(strFileName, RemoteName);
                        return(UploadResult.Complete);

                    case enumGFSAlready.Stop:
                        return(UploadResult.Skip);
                    }
                    return(UploadResult.Skip);
                }
            }
            catch (Exception ex)
            {
                SystemManager.ExceptionDeal(ex);
                return(UploadResult.Exception);
            }
        }
Exemple #8
0
        public void AppendTextTest()
        {
            Assert.IsFalse(gridFS.Exists("HelloWorld.txt"));
            using (var writer = gridFS.AppendText("HelloWorld.txt")) {
                Assert.IsFalse(writer.BaseStream.CanRead);
                Assert.IsTrue(writer.BaseStream.CanSeek);
                Assert.IsTrue(writer.BaseStream.CanWrite);
                writer.Write("동해물과");
            }

            Assert.IsTrue(gridFS.Exists("HelloWorld.txt"));
            using (var writer = gridFS.AppendText("HelloWorld.txt")) {
                writer.Write(" 백두산이");
            }
            var memoryStream = new MemoryStream();

            gridFS.Download(memoryStream, "HelloWorld.txt");
            var bytes = memoryStream.ToArray();

            // 2-byte 문자열임을 나타내는 헤더값
            StringTool.IsMultiByteString(bytes).Should().Be.True();

            //Assert.AreEqual(0xEF, bytes[0]); // the BOM
            //Assert.AreEqual(0xBB, bytes[1]);
            //Assert.AreEqual(0xBF, bytes[2]);

            // Header 값을 빼고, 한다.
            // var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
            var text = memoryStream.ToText(Encoding.UTF8);

            Assert.AreEqual("동해물과 백두산이", text);
        }