Пример #1
0
        public override File422 CreateFile(string fileName)
        {
            File422 memFile = null;

            if (!StdFSHelper.ContainsPathCharacters(fileName) ||
                string.IsNullOrEmpty(fileName))
            {
                //check if exists already
                if ((memFile = GetFile(fileName)) != null)
                {
                    using (Stream s = memFile.OpenReadWrite())
                    {
                        if (s != null)
                        {
                            //this 0's out the memory stream.
                            s.SetLength(0);
                        }
                    }
                }
                else
                {
                    memFile = new MemFSFile(fileName, this);
                    _childFiles.Add(memFile);
                }
            }

            return(memFile);
        }
Пример #2
0
        static int Main(string[] args)
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");

            //Assert.NotNull(dir1.CreateFile("hello.txt"));
            //Assert.NotNull(dir1.CreateFile("Test.txt"));

            dir1.CreateFile("A");
            string datastring = "new data";

            byte[] info = new UTF8Encoding(true).GetBytes(datastring);

            File422 a = dir1.GetFile("A");

            if (a is StdFSFile)
            {
                a = a as StdFSFile;

                FileStream fs = (FileStream)((StdFSFile)a).OpenReadWrite();
                fs.Write(info, 0, info.Length);
                fs.Close();
            }

            return(0);
        }
Пример #3
0
        public void StdFSDirCreateFileDupeTest()
        {
            File422 txt     = root.CreateFile("file.txt");
            File422 txtDupe = root.CreateFile("file.txt");

            Assert.AreEqual(txt.Name, txtDupe.Name);
        }
Пример #4
0
        void SendFile(File422 file, WebRequest req)
        {
            // check if request contains range header
            if (req.Headers.ContainsKey("Range"))
            {
                var   range = req.Headers ["Range"];
                Match match = Regex.Match(range, @".*bytes=([0-9]+)-([0-9]+).*");


                long start = long.Parse(match.Groups [1].Value);

                long end = 0;

                // if end match not found then value remains 0
                if (match.Groups.Count > 2)
                {
                    end = long.Parse(match.Groups [2].Value);
                }

                SendFileRange(file, start, end, 500, req);
                //
            }
            else
            {
                //replace old headers
                SendFileRange(file, 0, 0, 500, req);
            }
        }
Пример #5
0
        //used to build the files html
        private string BuildFileHTML(File422 file)
        {
            StringBuilder html = new StringBuilder();
            string        link = file.Name;

            //recurse through all parent directories until roo
            //also, all spaces are replaced with %20

            Dir422 parent = file.Parent;

            //since the root has a null parent, we iterate until we are there
            //once we are, we append the /files/ HTML request
            while (parent.Name != r_sys.GetRoot().Name)
            {
                link   = parent.Name + "/" + link;
                parent = parent.Parent;
            }

            link = "/files/" + link;


            html.AppendFormat(
                "<a href=\"{0}\">{1}</a><br>",
                link,
                file.Name
                );

            //get HREF for File422 object:
            //last part FILE422.Name
            //recurse through parent directories until hitting root
            //for each one, append directory name to FRONT of string

            return(html.ToString());
        }
Пример #6
0
        public void StandardFileSystemContainsFileTest()
        {
            Dir422  c   = root.GetDir("two").GetDir("a").GetDir("b").GetDir("c");
            File422 txt = c.CreateFile("dummy.txt");

            Assert.True(stdFS.Contains(txt));
        }
Пример #7
0
        public override File422 CreateFile(string fileName)
        {
            File422 stdFile = null;

            //if at root of filesystem, gets rid of extra '/'
            string path = (_path == "/") ? "" : _path;

            if (!StdFSHelper.ContainsPathCharacters(fileName) ||
                string.IsNullOrEmpty(fileName))
            {
                //if we are at /a/b/, makes /a/b/c.txt
                //where c.txt is fileName
                path = path + "/" + fileName;

                //if already exists clear existing data.
                if (File.Exists(path))
                {
                    File.WriteAllText(path, "");
                }

                //if exists and not read-only contents are overwritten
                using (FileStream fs = File.Create(path))
                {
                    //set length to 0.
                    fs.SetLength(0);

                    //this is the parent
                    stdFile = new StdFSFile(path, this);
                }
            }

            return(stdFile);
        }
Пример #8
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            Stream fs = file.OpenReadOnly();

            if (req.Headers.ContainsKey("range"))
            {
                WriteWithRangeHeader(file, fs, req);
                return;
            }

            // Send response code and headers
            string response = "HTTP/1.1 200 OK\r\n" +
                              "Content-Length: " + fs.Length + "\r\n" +
                              "Content-Type: " + file.GetContentType() + "\r\n\r\n";

            byte[] responseBytes = Encoding.ASCII.GetBytes(response);
            req.WriteResponse(responseBytes, 0, responseBytes.Length);

            while (true)
            {
                byte[] buf  = new byte[4096];
                int    read = fs.Read(buf, 0, buf.Length);
                if (read == 0)
                {
                    break;
                }
                req.WriteResponse(buf, 0, read);
            }
            fs.Close();
        }
Пример #9
0
        public void HandlePut(WebRequest req, Dir422 dir)
        {
            File422 file         = dir.CreateFile(req.URI.Split('/', '\\').Last());
            Stream  outputStream = file.OpenReadWrite();
            Stream  inputStream  = req._networkStream;

            inputStream.ReadTimeout = 1000;
            int BUFFER_SIZE = 8000;
            int bytesRead   = 0;

            byte[] bytes = new byte[BUFFER_SIZE];
            try
            {
                bytesRead = inputStream.Read(bytes, 0, bytes.Length);
            }
            catch { }

            while (bytesRead != 0)
            {
                // Translate data bytes to a ASCII string.
                outputStream.Write(bytes, 0, bytesRead);
                bytes = new byte[BUFFER_SIZE];
                try { bytesRead = inputStream.Read(bytes, 0, bytes.Length); }
                catch { break; }
                Console.WriteLine(bytesRead.ToString());
            }

            req.WriteHTMLResponse("Hello");
            outputStream.Close();
            inputStream.Close();
        }
Пример #10
0
        // 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)
        }
Пример #11
0
        public void MReadWriteFile()
        {
            MemoryFileSystem mfs   = new MemoryFileSystem();
            Dir422           dir1  = mfs.GetRoot().CreateDir("Dir1");
            File422          file1 = dir1.CreateFile("File1");

            string datastring = "new data";

            byte[] info = new UTF8Encoding(true).GetBytes(datastring);

            //Assert.NotNull(file1._stream);
            Stream open = file1.OpenReadWrite();

            Assert.True(true);
            Assert.NotNull(open);

            open.Write(info, 0, info.Length);

            open.Close();

            Stream read = file1.OpenReadWrite();

            byte[] readIn = new byte[256];
            read.Read(readIn, 0, 256);

            string str = System.Text.Encoding.Default.GetString(readIn).TrimEnd('\0');

            StringAssert.AreEqualIgnoringCase(str, datastring);
        }
Пример #12
0
        public virtual bool ContainsFile(string fileName, bool recursive)
        {
            File422 file = GetFile(fileName);

            if (file != null)
            {
                return(true);
            }

            if (!recursive)
            {
                return(false);
            }

            IList <Dir422> directories = GetDirs();

            for (int i = 0; i < directories.Count(); i++)
            {
                Dir422 dir = directories [i];

                if (dir.ContainsFile(fileName, true))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #13
0
        public void SDirTests()
        {
            StandardFileSystem sfs2 = StandardFileSystem.Create("/Users/drewm");

            Dir422 dir1 = sfs2.GetRoot().GetDir("Desktop");

            //Assert.NotNull(dir1.CreateFile("hello.txt"));
            //Assert.NotNull(dir1.CreateFile("Test.txt"));

            Assert.NotNull(dir1.CreateFile("A"));
            string datastring = "new data";

            byte[] info = new UTF8Encoding(true).GetBytes(datastring);

            File422 a = dir1.GetFile("A");

            if (a is StdFSFile)
            {
                Assert.NotNull(a);
                a = a as StdFSFile;

                FileStream fs = (FileStream)((StdFSFile)a).OpenReadWrite();
                fs.Write(info, 0, info.Length);
                fs.Close();
            }

            else
            {
                Assert.IsTrue(false);
            }
        }
Пример #14
0
        public void MemFSDirCreateFileDupeTest()
        {
            File422 txt     = root.CreateFile("file.txt");
            File422 txtDupe = root.CreateFile("file.txt");

            Assert.AreSame(txt, txtDupe);
        }
Пример #15
0
        private void RespondWithFile(File422 file, WebRequest req) //return a file
        {
            string contentType = "text/html";                      //default to text/html

            if (file.Name.Contains(".jpg") || file.Name.Contains(".jpeg"))
            {
                contentType = "image/jpeg";
            }
            else if (file.Name.Contains(".gif"))
            {
                contentType = "image/gif";
            }
            else if (file.Name.Contains(".png"))
            {
                contentType = "image/png";
            }
            else if (file.Name.Contains(".pdf"))
            {
                contentType = "application/pdf";
            }
            else if (file.Name.Contains(".mp4"))
            {
                contentType = "video/mp4";
            }
            else if (file.Name.Contains(".xml"))
            {
                contentType = "text/xml";
            }



            req.WriteHTMLResponse(file.OpenReadOnly(), contentType); //write a page as a file
        }
Пример #16
0
        public void StdFSDirGetFileNotNullTest()
        {
            root.CreateFile("root.txt");
            File422 file = root.GetFile("root.txt");

            Assert.NotNull(file);
        }
Пример #17
0
        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);
                }
            }
        }
Пример #18
0
        public void MemFSDirCreateFileTest()
        {
            Dir422  b     = root.GetDir("one").GetDir("a").GetDir("b");
            File422 bFile = b.CreateFile("bFile.txt");

            Assert.AreEqual("bFile.txt", bFile.Name);
            Assert.AreSame(b, bFile.Parent);
        }
Пример #19
0
        public void StdFSDirCreateFileTest()
        {
            Dir422  b     = root.GetDir("one").GetDir("a").GetDir("b");
            File422 bFile = b.CreateFile("bFile.txt");

            Assert.AreEqual("bFile.txt", bFile.Name);
            //references are different. Since not memory. we create new everytime.
        }
Пример #20
0
        public override IList <File422> GetFiles()
        {
            File422[] f = new File422[files.Values.Count];

            files.Values.CopyTo(f, 0);

            return(f);
        }
Пример #21
0
        public virtual bool Contains(File422 file)
        {
            if (file.Name.Contains("/") || file.Name.Contains("\\") || file == null)
            {
                return(false);
            }

            return(Contains(file.Parent));
        }
Пример #22
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;
            }
        }
Пример #23
0
        public override File422 CreateFile(string name)
        {
            File422 file = GetFile(name);

            if (file == null)
            {
                file = new MemFSFile(name, this);
                _files.Add(file);
            }
            return(file);
        }
Пример #24
0
        public virtual bool Contains(File422 file)
        {
            if (file.Parent != null)
            {
                return(Contains(file.Parent));
            }

            else
            {
                return(GetRoot().ContainsFile(file.Name, false));
            }
        }
Пример #25
0
        public void MemFSDirGetFilesTest()
        {
            Dir422  b     = root.GetDir("two").GetDir("a").GetDir("b");
            File422 file1 = b.CreateFile("file1.txt");
            File422 file2 = b.CreateFile("file2.txt");

            IList <File422> files = b.GetFiles();

            Assert.AreEqual(2, files.Count);
            Assert.AreSame(file1, files[files.IndexOf(file1)]);
            Assert.AreSame(file2, files[files.IndexOf(file2)]);
        }
Пример #26
0
        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));
        }
Пример #27
0
        public void WriteFileContents(File422 file)
        {
            Console.WriteLine("WriteFileContents(): ");
            // Generate Html
            string html = "";

            // Stream fileStream = file.OpenReadOnly();
            // byte[] buffer = new byte[8000];


            _request.WriteHTMLResponse(html);
        }
Пример #28
0
        public void MCreateFile()
        {
            MemoryFileSystem mfs   = new MemoryFileSystem();
            Dir422           dir1  = mfs.GetRoot().CreateDir("Dir1");
            File422          file1 = dir1.CreateFile("File1");

            Assert.NotNull(dir1);
            Assert.NotNull(mfs.Contains(dir1));

            Assert.False(mfs.GetRoot().ContainsFile("File1", false));
            Assert.True(mfs.GetRoot().ContainsFile("File1", true));
        }
Пример #29
0
        /// <summary>
        /// Writes the with range header.
        /// </summary>
        private void WriteWithRangeHeader(File422 file, Stream fs, WebRequest req)
        {
            String[] ranges = req.Headers["range"].Trim().Substring("byte= ".Length).Split('-');

            long from;

            Int64.TryParse(ranges[0], out from);
            if (fs.Length <= from)
            {
                string invalid = "HTTP/1.1 416 Requested Range Not Satisfiable\r\n\r\n";
                byte[] invalidResponseBytes = Encoding.ASCII.GetBytes(invalid);
                req.WriteResponse(invalidResponseBytes, 0, invalidResponseBytes.Length);
            }

            long to;

            if (ranges[1] != string.Empty)
            {
                Int64.TryParse(ranges[1], out to);
            }
            else
            {
                to = fs.Length - 1;
            }

            // Send response code and headers
            string response = "HTTP/1.1 206 Partial content\r\n" +
                              "Content-Range: bytes " + from.ToString() + "-" + to.ToString() + "/" + fs.Length.ToString() + "\r\n" +
                              "Content-Length: " + (to + 1 - from).ToString() + "\r\n" +
                              "Content-Type: " + file.GetContentType() + "\r\n\r\n";

            byte[] responseBytes = Encoding.ASCII.GetBytes(response);
            req.WriteResponse(responseBytes, 0, responseBytes.Length);


            fs.Seek(from, SeekOrigin.Begin);
            while (true)
            {
                byte[] buf  = new byte[4096];
                int    read = 0;
                read = fs.Read(buf, 0, buf.Length);
                if (read == 0)
                {
                    break;
                }
                req.WriteResponse(buf, 0, read);
                if (fs.Position >= to)
                {
                    break;
                }
            }
            fs.Close();
        }
Пример #30
0
        public void StdFSFileReadWriteSharedAccessTest()
        {
            File422 file = root.CreateFile("file.txt");

            Stream stream3 = file.OpenReadWrite();
            Stream stream1 = file.OpenReadOnly();
            Stream stream2 = file.OpenReadOnly();

            Assert.NotNull(stream3);
            Assert.Null(stream1);
            Assert.Null(stream2);
        }