コード例 #1
0
ファイル: FilesWebService.cs プロジェクト: jakeknott/CS422
        public override void Handler(WebRequest req)
        {
            if (!req.URI.StartsWith(this.ServiceURI))
            {
                throw new InvalidOperationException();
            }

            // Percent-decode our filename
            string percenDecoded = Uri.UnescapeDataString(req.URI);

            //If we want the root folder
            if (percenDecoded == ServiceURI)
            {
                RespondWithList(r_sys.GetRoot(), req);
                return;
            }

            // The pluse one is the '/' after the '/files' so we remove '/files/'
            string[] peices = percenDecoded.Substring(ServiceURI.Length + 1).Split('/');

            Dir422 dir = r_sys.GetRoot();

            for (int i = 0; i < peices.Length - 1; i++)
            {
                dir = dir.GetDir(peices[i]);

                if (dir == null)
                {
                    //This wants a response?
                    req.WriteNotFoundResponse(string.Empty);
                    return;
                }
            }

            string lastPeice = peices [peices.Length - 1];


            File422 file = dir.GetFile(lastPeice);

            if (file != null)
            {
                //Send back the file to them.
                RespondWithFile(file, req);
            }
            else
            {
                //Send the dir contents (if it is a dir to send back)
                dir = dir.GetDir(lastPeice);
                if (dir != null)
                {
                    //Respond with the list of files and dirs
                    RespondWithList(dir, req);
                }
                else
                {
                    req.WriteNotFoundResponse(string.Empty);
                }
            }
        }
コード例 #2
0
        public void d_CreateContainFileRecursive()
        {
            Dir422 TestDir = root.GetDir("TestDir");
            Dir422 BlahDir = TestDir.CreateDir("BlahDir");

            BlahDir.CreateFile("blahFile");
            Assert.AreEqual(true, root.ContainsFile("blahFile", true));
        }
コード例 #3
0
        public void c_CreateContainsDirectoryRecursive()
        {
            //Dir422 dir = new StdFSDir(rootDir + "/FooDir");
            //dir.CreateDir("BarDir");
            //Dir422 dirParent = dir.Parent;
            Dir422 FooDir = root.GetDir("FooDir");

            FooDir.CreateDir("BarDir");
            Assert.AreEqual(true, root.ContainsDir("BarDir", true));
        }
コード例 #4
0
ファイル: FilesWebService.cs プロジェクト: genewlee/CS422
        public override void Handler(WebRequest req)
        {
            if (!req.RequestURI.StartsWith(ServiceURI, StringComparison.CurrentCulture))
            {
                throw new InvalidOperationException();
            }

            if (req.RequestURI == "/files" || req.RequestURI == "/files/")
            {
                RespondWithList(m_fs.GetRoot(), req);
                return;
            }

            string[] pieces = req.RequestURI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (pieces == null || pieces.Length == 0)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            Dir422 dir = m_fs.GetRoot();

            for (int i = 0; i < pieces.Length - 1; i++)
            {
                string piece = pieces[i];
                dir = dir.GetDir(piece);
                if (dir == null)
                {
                    req.WriteNotFoundResponse("404: Path error.");
                    return;
                }
            }

            string name = PercentDecoding(pieces[pieces.Length - 1]);

            File422 file = dir.GetFile(name);

            if (file != null)
            {
                RespondWithFile(file, req);
                return;
            }

            dir = dir.GetDir(name);
            if (dir == null)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            RespondWithList(dir, req);
        }
コード例 #5
0
ファイル: FilesWebService.cs プロジェクト: StoopMoss/422Repo
        // Methods
        public override void Handler(WebRequest request)
        {
            Console.WriteLine("Service Handler: OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
            _request = request;

            // Parse the URI and determine which of the 3 is the case:
            string[]      parsedURI = request.URI.Split('/');
            List <string> dirNames  = new List <string>();
            int           count     = 0;

            foreach (string s in parsedURI)
            {
                if (count > 1)// so we only have traversable dirnames
                {
                    Console.WriteLine("adding: " + parsedURI[count]);
                    dirNames.Add(parsedURI[count]);
                }
                Console.WriteLine("s: " + s);
                Console.WriteLine("c: " + count);
                count++;
            }
            Console.WriteLine("dirNames.Count: " + dirNames.Count);

            Dir422  currentDir = _fs.GetRoot();
            Dir422  lastDir;
            File422 file = null;

            foreach (string s in dirNames)
            {
                if (!String.IsNullOrEmpty(s))
                {
                    Console.WriteLine("locating: " + s);
                    lastDir    = currentDir;
                    currentDir = currentDir.GetDir(s);
                    if (null == currentDir) // check to see if a file
                    {
                        Console.WriteLine("Null Dir");
                        file = lastDir.GetFile(s);
                        if (null == file)
                        {
                            Console.WriteLine("Null File");
                            //requested Resource does not exist
                            // so 404 write to network and return
                            request.WriteNotFoundResponse("Could not find file: " + s + ".");
                            return;
                        }
                        // otherwise write file contents as html
                        WriteFileContents(file);
                        return;
                    }
                }
            }

            // If this point is reached then we should have a dir and
            // we must write its file listing to the network
            WriteDirListing(currentDir);

            // Provide support for partial content responses
            // (i.e. support the Range header)
        }
コード例 #6
0
        public void StdFSDirParentTest()
        {
            Dir422 two = root.GetDir("one");
            Dir422 a   = two.GetDir("a");

            Assert.AreSame(two, a.Parent);
        }
コード例 #7
0
        private void PutHandler(WebRequest req)
        {
            //NOTE use Uri.UnescapeDataString to convert the escaped string
            //to it's unescaped representation.
            //i.e if we get http://localhost:4220/%20test/
            //would become http://localhost:4220/ test/
            string[] names = Uri.UnescapeDataString(req.RequestTarget).Split(new char[] { '/' },
                                                                             StringSplitOptions.RemoveEmptyEntries);

            //first name is files.
            string currString = "";

            Dir422 currNode = _fs.GetRoot(); //root is what we chose, the client knows it as "files".
            Dir422 nextNode = null;

            for (int i = 1; i < names.Length; i++)
            {
                currString = names[i];
                if (i == names.Length - 1) // the c in /a/b/c
                //put the file.
                {
                    byte[] buffer       = new byte[1024];
                    Stream concatStream = req.Body;
                    int    read         = 0;

                    string path = _fs.GetRoot().Name + BuildPath(currNode) + "/" + names[i];

                    //Don't allow overwriting existing files or files with \ character
                    if (currNode.ContainsFile(names[i], false) || names[i].Contains("\\"))
                    {
                        return;
                    }

                    using (FileStream newFile = File.OpenWrite(path))
                    {
                        while ((read = concatStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            newFile.Write(buffer, 0, read);
                            Array.Clear(buffer, 0, buffer.Length); //reset buffer for next read.
                        }
                    }
                }
                else if ((nextNode = currNode.GetDir(currString)) != null)
                {
                    //go to next dir to repeat iteration.
                    currNode = nextNode;
                }
                else
                {
                    return;
                }
            }

            string htmlString = BuildDirHTML(currNode);

            //req.WriteHTMLResponse(htmlString);
            req.WriteRegularResponse(htmlString);
        }
コード例 #8
0
        private void GetHandler(WebRequest req)
        {
            //NOTE use Uri.UnescapeDataString to convert the escaped string
            //to it's unescaped representation.
            //i.e if we get http://localhost:4220/%20test/
            //would become http://localhost:4220/ test/
            string[] names = Uri.UnescapeDataString(req.RequestTarget).Split(new char[] { '/' },
                                                                             StringSplitOptions.RemoveEmptyEntries);

            //first name is files.
            string currString = "";

            Dir422  currNode = _fs.GetRoot(); //root is what we chose, the client knows it as "files".
            Dir422  nextNode = null;
            File422 file     = null;

            int uriCase = 1;

            for (int i = 1; i < names.Length; i++)
            {
                currString = names[i];
                if ((nextNode = currNode.GetDir(currString)) != null)
                {
                    //go to next dir to repeat iteration.
                    currNode = nextNode;
                }
                else if ((file = currNode.GetFile(currString)) != null)
                {
                    uriCase = 2;
                    break;
                }
                else
                {
                    uriCase = 3;
                    break;
                }
            }

            switch (uriCase)
            {
            //URI maps to an existing directory in the file system.
            case 1:
                string htmlString = BuildDirHTML(currNode);
                req.WriteHTMLResponse(htmlString);
                break;

            //The URI maps to an existing file in the file system
            case 2:
                SendFileContent(file, req);
                break;

            //The URI maps to something that doesn’t exist in the file system
            case 3:
                req.WriteNotFoundResponse(errorHtml);
                break;
            }
        }
コード例 #9
0
        public override void Handler(WebRequest req)
        {
            if (!req.URI.StartsWith(ServiceURI, StringComparison.Ordinal))
            {
                throw new InvalidOperationException();
            }

            //split the path
            string[] places = req.URI.Substring(ServiceURI.Length).Split('/');
            Dir422   dir    = r_sys.GetRoot();

            for (int i = 0; i < places.Length - 1; i++)
            {
                dir = dir.GetDir(places[i]);
                if (dir == null)
                {
                    req.WriteNotFoundResponse("");
                    return;
                }
            }

            File422 file = dir.GetFile(places[places.Length - 1]);

            if (file != null)
            {
                RespondWithFile(file, req);
            }

            else
            {
                dir = dir.GetDir(places[places.Length - 1]);
                if (dir != null)
                {
                    RespondWithList(dir, req);
                }

                else
                {
                    req.WriteNotFoundResponse("");
                }
            }
        }
コード例 #10
0
ファイル: Utility.cs プロジェクト: z-mohamed/CS422
        public static Dir422 TraverseToDir(Dir422 Root, string path)
        {
            Dir422 directory = Root;

            string[] pathPieces = path.Split('/');

            for (int i = 2; i < pathPieces.Count(); i++)
            {
                directory = directory.GetDir(pathPieces[i]);
            }
            return(directory);
        }
コード例 #11
0
        public void f_GetDirMakeFile()
        {
            //Dir422 dir = new StdFSDir(rootDir + "/FooDir");
            //Dir422 BarDir = dir.GetDir("BarDir");
            //BarDir.CreateFile("barFile2");
            //Assert.AreEqual(true, BarDir.ContainsFile("barFile2", true));
            Dir422 FooDir = root.GetDir("FooDir");
            Dir422 BarDir = FooDir.GetDir("BarDir");

            BarDir.CreateFile("barFile2");
            Assert.AreEqual(true, BarDir.ContainsFile("barFile2", true));
        }
コード例 #12
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SSysContains()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");
            Dir422 dir2 = dir1.GetDir("Ableton");
            Dir422 dir3 = dir2.GetDir("wav files");

            File422 f = dir3.GetFile("Cloud.wav");

            Assert.IsTrue(sfs2.Contains(f));
        }
コード例 #13
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SFileTests()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");
            Dir422 dir2 = dir1.GetDir("Ableton");
            Dir422 dir3 = dir2.GetDir("wav files");

            File422 f = dir3.GetFile("Cloud.wav");

            StringAssert.AreEqualIgnoringCase(f.Name, "Cloud.wav");
            StringAssert.AreEqualIgnoringCase(f.Parent.Name, "wav files");
        }
コード例 #14
0
        /*
         * Don’t allow overwriting existing files
         * Allow all (non-existing-file-overwriting) uploads provided the file name doesn’t contain reserve characters (/ and \)
         * Files can be uploaded to any directory that the service shares
         * Files must be uploaded into the current directory that the user is seeing the listing for within the browser
         * There is no limit on file sizes or content
         * You only need to support uploading 1 file at a time (1 per page refresh, as described below)
         * You do NOT need to support cross-origin requests or the OPTIONS method, which will have been discussed in class
         *
         */
        void handlePUT(WebRequest req)
        {
            string[] path = req.URI.Split('/');

            // The file already exists
            if (fileSystem.GetRoot().ContainsFile(path[path.Length - 1], true))
            {
                req.WriteNotFoundResponse("File exists");
            }
            // Make file
            else
            {
                Dir422 currentDir = fileSystem.GetRoot();

                // Don't include last element because thats the file name
                for (int i = 2; i < path.Length - 1; i++)
                {
                    // Fix '/' at end of URI
                    if (path[i] != "")
                    {
                        currentDir = currentDir.GetDir(path[i]);
                    }
                }

                File422 file = currentDir.CreateFile(path[path.Length - 1]);

                using (Stream stream = file.OpenReadWrite())
                {
                    byte[] buffer = new byte[1024 * 8];
                    int    bytesRead = 0, size = int.Parse(req.Headers["content-length"]), totalRead = 0;

                    while (totalRead < size)
                    {
                        bytesRead = req.Body.Read(buffer, 0, (size - totalRead > buffer.Length) ? buffer.Length : size - totalRead);

                        totalRead += bytesRead;
                        Console.WriteLine(totalRead < size);

                        stream.Write(buffer, 0, (bytesRead < size) ? bytesRead : size);
                    }
                }

                Console.WriteLine("File uploaded");
                req.WriteHTMLResponse("file uploaded!");
            }
        }
コード例 #15
0
ファイル: FilesWebService.cs プロジェクト: genewlee/CS422
        private void GETHandler(WebRequest req, string name, Dir422 dir)
        {
            File422 file = dir.GetFile(name);

            if (file != null)
            {
                RespondWithFile(file, req);
                return;
            }

            dir = dir.GetDir(name);
            if (dir == null)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }
            RespondWithList(dir, req);
        }
コード例 #16
0
ファイル: tests.cs プロジェクト: Drew-Miller/CS422
        public void SgetDir_File()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");
            Dir422             dir1 = sfs2.GetRoot().GetDir("Desktop");

            Assert.NotNull(dir1);


            Dir422 dir2 = dir1.GetDir("Ableton");

            Assert.NotNull(dir2);


            Dir422 dir3 = dir2.GetDir("wav files");

            Assert.NotNull(dir3);


            Assert.NotNull(dir3.GetFile("Cloud.wav"));
        }
コード例 #17
0
        void handleGET(WebRequest req)
        {
            try
            {
                string[] path = req.URI.Split('/');

                // To handle '/files' request
                if (path.Length == 2)
                {
                    req.WriteHTMLResponse(BuildDirHTML(fileSystem.GetRoot()));

                    return;
                }

                // This handles '/files/**'
                // The URI maps to an existing directory in the file system
                if (fileSystem.GetRoot().ContainsDir(path[path.Length - 1], true))
                {
                    // Imidiately set the content-type to html since we are returning html code
                    req.Headers["content-type"] = "text/html";

                    Dir422 currentDir = fileSystem.GetRoot();
                    for (int i = 2; i < path.Length; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    req.WriteHTMLResponse(BuildDirHTML(currentDir));
                }
                // The URI maps to an existing file in the file system
                else if (fileSystem.GetRoot().ContainsFile(path[path.Length - 1], true))
                {
                    // Get the file type and set the content-type to the file type
                    string filename = path[path.Length - 1];

                    int    dot  = filename.LastIndexOf('.');
                    string type = (dot >= 0) ? filename.Substring(dot).ToLower() : "";

                    switch (type)
                    {
                    case ".txt":
                        req.Headers["content-type"] = "text/plain";
                        break;

                    case ".xml":
                        req.Headers["content-type"] = "text/xml";
                        break;

                    case ".jpg":
                        req.Headers["content-type"] = "image/jpg";
                        break;

                    case ".jpeg":
                        req.Headers["content-type"] = "image/jpeg";
                        break;

                    case ".png":
                        req.Headers["content-type"] = "image/png";
                        break;

                    case ".mp4":
                        req.Headers["content-type"] = "video/mp4";
                        break;

                    case ".pdf":
                        req.Headers["content-type"] = "application/pdf";
                        break;

                    default:
                        req.Headers["content-type"] = "text/html";
                        break;
                    }

                    Dir422 currentDir = fileSystem.GetRoot();

                    // Don't include last element because thats the file name
                    for (int i = 2; i < path.Length - 1; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    File422 file = currentDir.GetFile(path[path.Length - 1]);

                    // Get the file stuff
                    int bytesRead;

                    // Did the client send us a range header
                    string rangeValue;
                    if (req.Headers.TryGetValue("range", out rangeValue))
                    {
                        byte[] buffer;

                        // Send the chunk they want. Only works for bytes=%d-%d
                        rangeValue = rangeValue.Replace(" ", "");
                        rangeValue = rangeValue.Remove(0, "bytes=".Length);
                        string[] bytes = rangeValue.Split('-');
                        int      start = int.Parse(bytes[0]), end = int.Parse(bytes[1]), totalRead = 0;
                        buffer = new byte[end - start];

                        using (BufferedStream reader = new BufferedStream(file.OpenReadOnly()))
                        {
                            // Add header = content-range: bytes %d-%d/%d
                            req.Headers["content-range"] = "bytes " + rangeValue + "/" + reader.Length;

                            req.WritePreBody(206, buffer.Length);

                            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                req.WriteFile(buffer, totalRead, bytesRead);

                                totalRead += bytesRead;
                            }
                        }
                    }
                    else
                    {
                        // Send the entire thing
                        BufferedStream reader = new BufferedStream(file.OpenReadOnly());
                        byte[]         buffer = new byte[8 * 1024];

                        req.WritePreBody(200, reader.Length);

                        while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            req.WriteFile(buffer, 0, bytesRead);
                        }

                        reader.Close();
                    }
                }
                else
                {
                    // The URI maps to something that doesn’t exist in the file system
                    req.WriteNotFoundResponse("<h1>404</h1><br><b>Content not found</b>");
                }
            }
            catch (Exception)
            {
                return;
            }
        }
コード例 #18
0
        public override void Handler(WebRequest req)
        {
            //Every request should start with /files/
            if (!req.URI.StartsWith(this.ServiceURI))
            {
                throw new InvalidOperationException();
            }

            //percent-decode URI
            string uri = req.URI;

            string[] pieces = req.URI.Substring(ServiceURI.Length).Split('/', '\\');
            Dir422   dir    = _fs.GetRoot();
            //Grabs all the parts but the last part, which could be a file or a dir
            string piece = "";

            for (int i = 1; i < pieces.Length - 1; i++)
            {
                piece = pieces[i];
                //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
                dir = dir.GetDir(piece);

                //Check if directory exists
                if (dir == null)
                {
                    req.WriteNotFoundResponse();
                    return;
                }
            }


            //Check if the last part is a file or a directory
            piece = pieces[pieces.Length - 1];
            //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
            File422 file = dir.GetFile(piece); //TODO: This is returning Null and is not supposed to.

            if (file == null && req.Method == "PUT")
            {
                HandlePut(req, dir);
                return;
            }
            if (file != null)
            {
                //If it's a file, then return the file.
                Console.WriteLine("It's a file!");

                RespondWithFile(file, req);
            }
            else
            {
                piece = pieces[pieces.Length - 1];
                //if (piece.Contains("%20")) piece = piece.Replace("%20", " ");
                if (piece != "")
                {
                    dir = dir.GetDir(piece);
                }

                if (dir != null)
                {
                    //If it's a dir, return the dir
                    RespondWithList(dir, req);
                }
                else
                {
                    //Else return that nothing was found.
                    req.WriteNotFoundResponse();
                }
            }
        }
コード例 #19
0
        public void StandardFileSystemContainsDirTest()
        {
            Dir422 c = root.GetDir("two").GetDir("a").GetDir("b").GetDir("c");

            Assert.True(stdFS.Contains(c));
        }
コード例 #20
0
ファイル: FilesWebService.cs プロジェクト: jakeknott/CS422
        private void DoUpload(WebRequest req, string percenDecoded)
        {
            string fileName = "";

            Dir422 currentDir = null;

            if (percenDecoded == ServiceURI)
            {
                currentDir = r_sys.GetRoot();
            }
            else
            {
                // The pluse one is the '/' after the '/files' so we remove '/files/'
                string[] pathPeices = percenDecoded.Substring(ServiceURI.Length + 1).Split('/');

                currentDir = r_sys.GetRoot();
                for (int i = 0; i < pathPeices.Length - 1; i++)
                {
                    currentDir = currentDir.GetDir(pathPeices[i]);

                    if (currentDir == null)
                    {
                        req.WriteNotFoundResponse(string.Empty);
                        return;
                    }
                }

                fileName = pathPeices [pathPeices.Length - 1];
            }

            File422 newFile = currentDir.CreateFile(fileName);

            if (newFile == null)
            {
                // We could not create a new file
                return;
            }

            Stream s = newFile.OpenReadWrite();

            if (s == null)
            {
                return;
            }

            byte[] bodyBytes = new byte[1024];

            long bytesRead = 0;

            //Read all that we can.
            while (bytesRead < req.BodyLength)
            {
                // We need to read chuncks at a time since read wants an int
                // as the count, and we may loose data if we cast a long to an int.
                int read = req.Body.Read(bodyBytes, 0, 1024);
                bytesRead += read;
                if (read == 0)
                {
                    break;
                }

                s.Write(bodyBytes, 0, read);
                Array.Clear(bodyBytes, 0, bodyBytes.Length);
            }

            s.Close();

            req.WriteHTMLResponse("");
            return;
        }
コード例 #21
0
        public void MemoryFileSystemContainsDirTest()
        {
            Dir422 c = root.GetDir("two").GetDir("a").GetDir("b").GetDir("c");

            Assert.True(memFS.Contains(c));
        }
コード例 #22
0
        private void UploadFile(WebRequest req)
        {
            string[] pieces = req.URI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (pieces == null || pieces.Length == 0)
            {
                req.WriteNotFoundResponse("404: Path error.");
                return;
            }

            Dir422 dir = r_fs.GetRoot();

            for (int i = 0; i < pieces.Length - 1; i++)
            {
                string piece = pieces[i];
                dir = dir.GetDir(piece);

                if (dir == null)
                {
                    req.WriteNotFoundResponse("404: Path error.");
                    return;
                }
            }

            File422 file = dir.GetFile(PercentDecoding(pieces[pieces.Length - 1]));

            if (file != null)
            {
                req.WriteHTMLResponse("<html> File Already Exists! </html>");
                return;
            }

            File422    newFile = dir.CreateFile(PercentDecoding(pieces[pieces.Length - 1]));
            FileStream str     = (newFile.OpenReadWrite() as FileStream);
            Stream     reqStr  = req.Body;

            byte[] buf = new byte[4096];
            long   len = req.Len;

            if (len < 4096)
            {
                reqStr.Read(buf, 0, (int)len);
                str.Write(buf, 0, (int)len);
                str.Close();
                return;
            }

            int count     = reqStr.Read(buf, 0, 4096);
            int totalRead = count;

            while (count != 0 && totalRead < len)
            {
                str.Write(buf, 0, count);
                buf        = new byte[4096];
                count      = reqStr.Read(buf, 0, 4096);
                totalRead += count;
            }

            // If bytes were read last time, trim zeroes and write last bit
            if (count != 0)
            {
                str.Write(buf, 0, count);
            }

            str.Close();

            req.WriteHTMLResponse("<html> Upload Successful! </html>");

            return;
        }
コード例 #23
0
ファイル: NUnitTests.cs プロジェクト: jakeknott/CS422
        public void RunTest(FileSys422 mySys)
        {
            Dir422 root = mySys.GetRoot();

            //We should not be able to go above our root.
            Assert.IsNull(root.Parent);

            // Checking that we do not have a file
            Assert.IsFalse(root.ContainsFile("NewFile.txt", false));
            //create the file
            root.CreateFile("NewFile.txt");
            // Check that we can find it.
            Assert.IsTrue(root.ContainsFile("NewFile.txt", false));

            // Same with directory
            Assert.IsFalse(root.ContainsDir("SubDir", false));
            Dir422 subDir = root.CreateDir("SubDir");

            Assert.IsTrue(root.ContainsDir("SubDir", false));

            //Creating a file in a sub dir
            subDir.CreateFile("subText.txt");

            // Testing the recursive methods on files
            Assert.IsFalse(root.ContainsFile("subText.txt", false));
            Assert.IsTrue(root.ContainsFile("subText.txt", true));

            //Testing recurcive method on dirs
            subDir.CreateDir("newSubDir");

            Assert.IsFalse(root.ContainsDir("newSubDir", false));
            Assert.IsTrue(root.ContainsDir("newSubDir", true));

            //Checking getDir
            Dir422 recivedDir = root.GetDir("InvalidDir");

            Assert.IsNull(recivedDir);
            recivedDir = root.GetDir("SubDir");
            Assert.AreEqual("SubDir", recivedDir.Name);

            // Checking that if a file does not exist we return null,
            // otherwise we recived the file we wanted.
            File422 recidedFile = root.GetFile("InvalidFile");

            Assert.IsNull(recidedFile);
            recidedFile = root.GetFile("NewFile.txt");
            Assert.AreEqual("NewFile.txt", recidedFile.Name);

            //Checking the name validation function.
            // All of these methods use the same Validate Name method.
            Assert.IsNull(subDir.CreateFile("file/New.txt"));
            Assert.IsNull(subDir.CreateDir("file/New"));

            string bufString = "hello world";

            byte[] buff        = ASCIIEncoding.ASCII.GetBytes(bufString);
            var    writeStream = recidedFile.OpenReadWrite();

            writeStream.Write(buff, 0, 11);

            var readStream = recidedFile.OpenReadOnly();

            Assert.IsNull(readStream);

            writeStream.Dispose();

            readStream = recidedFile.OpenReadOnly();
            Assert.IsNotNull(readStream);

            //First read 'hello ' from each stream
            byte[] readBuf = new byte[6];
            readStream.Read(readBuf, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf));

            //Having two streams open for read
            var readStream2 = recidedFile.OpenReadOnly();

            Assert.IsNotNull(readStream2);

            byte[] readBuf2 = new byte[6];
            readStream2.Read(readBuf2, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf2));

            //Next read 'world' from each stream
            readBuf = new byte[5];
            readStream.Read(readBuf, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf));

            readBuf2 = new byte[5];
            readStream2.Read(readBuf2, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf2));

            //try to open a stream to write while there are streams open for read
            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNull(writeStream);

            //Close streams and try again
            readStream.Close();
            readStream2.Close();

            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNotNull(writeStream);
        }