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); }
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); }
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(); }
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); }
public void g_GetFileWrite() { //Dir422 dir = new StdFSDir(rootDir, true); //File422 fooFile = dir.GetFile("fooFile"); //Stream fs = fooFile.OpenReadWrite(); //string s = "Hello World"; //fs.Write(Encoding.ASCII.GetBytes(s), 0, s.Length); File422 fooFile = root.GetFile("fooFile"); Stream fs = fooFile.OpenReadWrite(); string s = "Hello World"; fs.Write(Encoding.ASCII.GetBytes(s), 0, s.Length); }
public void f_ReadFileManyWriteOpen() { File422 testFile = root.GetFile("testFile"); Stream fs = testFile.OpenReadWrite(); string text = "This is a test for MemFileSystem."; fs.Write(Encoding.ASCII.GetBytes(text), 0, text.Length); Stream fs1 = testFile.OpenReadOnly(); Stream fs2 = testFile.OpenReadOnly(); Assert.AreEqual(null, fs1); Assert.AreEqual(null, fs2); fs.Dispose(); Stream fs3 = testFile.OpenReadOnly(); byte[] buf = new byte[Encoding.ASCII.GetBytes(text).Length]; fs3.Read(buf, 0, Encoding.ASCII.GetBytes(text).Length); Stream fs4 = testFile.OpenReadOnly(); fs3.Close(); fs4.Close(); Assert.AreEqual(Encoding.ASCII.GetBytes(text), buf); fs = testFile.OpenReadWrite(); string blah = "This is added Text."; fs.Seek(Encoding.ASCII.GetBytes(text).Length, SeekOrigin.Begin); fs.Write(Encoding.ASCII.GetBytes(blah), 0, blah.Length); fs.Dispose(); fs3 = testFile.OpenReadOnly(); buf = new byte[Encoding.ASCII.GetBytes(text + blah).Length]; fs3.Read(buf, 0, Encoding.ASCII.GetBytes(text + blah).Length); //string s = Encoding.ASCII.GetString(buf); Assert.AreEqual(Encoding.ASCII.GetBytes(text + blah), buf); }
/* * 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!"); } }
public void MemFSFileReadWriteSharedAccessTest() { 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); Assert.AreEqual(1, ((MemFSFile)file).RefCount); stream3.Dispose(); Assert.AreEqual(0, ((MemFSFile)file).RefCount); }
private void PUTHandler(WebRequest req, string name, Dir422 dir) { if (dir.ContainsFile(name, false) || name.Contains("\\") || name.Contains("/")) { string bodyMessage = "Invalid: File already exists or filename is invalid"; string template = "HTTP/1.1 400 Bad Request\r\n" + "Content-Type: text/html\r\n" + "Content-Length: {0}\r\n\r\n" + "{1}"; string response = string.Format(template, Encoding.ASCII.GetBytes(bodyMessage).Length, bodyMessage); byte[] responseBytes = Encoding.ASCII.GetBytes(response); req.WriteResponse(responseBytes, 0, responseBytes.Length); return; } File422 file = dir.CreateFile(name); FileStream fs = (FileStream)file.OpenReadWrite(); long fileSize = 0; Int64.TryParse(req.BodySize, out fileSize); int totalread = 0; while (true) { byte[] buf = new byte[4096]; int read = req.Body.Read(buf, 0, buf.Length); fs.Write(buf, 0, read); totalread += read; if ((read == 0) || read < buf.Length && totalread >= fileSize) { break; } } fs.Dispose(); fs.Close(); req.WriteHTMLResponse("Successfully uploaded file: " + name); }
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); }
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; }
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; }