public void ThatReadingLinesWorks() { // Common setup var file = Substitute.For <IFile>(); var directory = Substitute.For <IDirectory>(); var systemio = Substitute.For <ISystemIO>(); systemio.File.Returns(file); systemio.Directory.Returns(directory); var underTest = new FileHandling(systemio); // Assume var testdir = "someNiceDirectory"; file.Exists(Arg.Is(testdir)).Returns(true); var expectedText = "The answer is 42"; file.ReadAllText(testdir).Returns(expectedText); // Act var txt = underTest.ReadAllLinesFromAFile(testdir); // Assert Assert.That(txt, Is.EqualTo(expectedText)); }
public void IsReadOnly() { if (!FileHandling.IsReadOnly("G:\\")) { Assert.Fail(); } }
private void ActivateEditMode() { //Erstelle einen FileDialog OpenFileDialog fileDialog = new OpenFileDialog { Multiselect = true, Filter = "Image files (*.png;*.jpeg)|*.png;*.jpeg;*.jpg;*.JPG;*.JPEG;*.PNG", InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }; //Oeffnen den Dialog und warte bis alle bilder ausgelesen sind if (fileDialog.ShowDialog() == true) { //Modus -> es werden Bilder neu zugewiesen newPictureMode = true; //Liste hat nun alle neuen Dateien eingelesen pictureList = fileDialog.FileNames.ToList(); //Variablen zuruecksetzen currentPicIndex = 1; //Label beschriften SetPictureLabels(); //Bild des Einlesen aendern SetButtonReadPicsImage("x"); //Bild setzen SetImage(0); //Neuen Ordner erstellen in den die Dateien kopiert werden FileHandling.CreateNewPictureFolder(); } }
private void button2_Click(object sender, EventArgs e) { thisCourse.classInfo = new ClassInfo.ClassInfo(); this.thisCourse.classInfo.comments = textBox1.Text; AppWideInfo.SetCourse(thisCourse, courseCode); FileHandling.Save(); }
private bool EditNextPicture() { //Nur ausfuehren wenn mindestens ein Filter aktiv ist if (TagControlHandling.IsAFilterActive(wrapPanelTags.Children) == true) { //Funktion beenden wenn man bereits am rechten Rand ist if (currentPicIndex >= pictureList.Count) { //Editiermodus beenden DeactivateEditMode(); return(false); } //Kopiere die Datei um string newFilePath = FileHandling.CopyFile(currentPicIndex, pictureList[currentPicIndex - 1]); //Lege ein XML-Eintrag fuer diese Datei an xmlHandling.InsertNewPictureWithTags(newFilePath, TagControlHandling.GetAllActiveTags(wrapPanelTags.Children)); //Alle Filter zuruecksetzen wrapPanelTags = TagControlHandling.ResetActiveFilter(wrapPanelTags); return(true); } else { return(false); } }
/// <summary> /// Playbacks the recorded input data loaded from a file path. /// </summary> /// <param name="path">The path to the file relative to Game.Filepath.</param> public void PlaybackFile(string path) { path = FileHandling.GetAbsoluteFilePath(Game.Instance.Filepath + path); byte[] b; using (FileStream f = new FileStream(path, FileMode.Open)) using (GZipStream gz = new GZipStream(f, CompressionMode.Decompress)) { int size = 4096; byte[] buffer = new byte[size]; using (MemoryStream memory = new MemoryStream()) { int count = 0; do { count = gz.Read(buffer, 0, size); if (count > 0) { memory.Write(buffer, 0, count); } }while (count > 0); b = memory.ToArray(); } } //string str = Encoding.Default.GetString(b); string dataString = Encoding.Default.GetString(b); PlaybackInternal(dataString); }
static void Main(string[] args) { Trace.Listeners.Add(new TextWriterTraceListener("Logs/errors.log")); Trace.AutoFlush = true; FileHandling.PrintMaterials(); }
public void IsNetworkPath() { if (!FileHandling.IsNetworkPath("\\\\LiamsNAS\\Downloads")) { Assert.Fail(); } }
public void IsNotNetworkPath() { if (FileHandling.IsNetworkPath("D:\\")) { Assert.Fail(); } }
/// <summary> /// Check if a Team Graph Configuration File exists, and create a default configuration file if not. /// </summary> internal static void CreateNewVdwConfigurationFile() { Event localEvent; var initialConfigurationFile = new StringBuilder(); initialConfigurationFile.AppendLine("/* Virtual Data Warehouse (VDW) Core Settings */"); initialConfigurationFile.AppendLine("TeamEnvironmentFilePath|" + FormBase.VdwConfigurationSettings.TeamEnvironmentFilePath); initialConfigurationFile.AppendLine("TeamConfigurationPath|" + FormBase.VdwConfigurationSettings.TeamConfigurationPath); initialConfigurationFile.AppendLine("TeamConnectionsPath|" + FormBase.VdwConfigurationSettings.TeamConnectionsPath); initialConfigurationFile.AppendLine("TeamSelectedEnvironment|" + "F3958C0634E41306A16639B9445CD0B3"); initialConfigurationFile.AppendLine("InputPath|" + FormBase.VdwConfigurationSettings.VdwExamplesPath); initialConfigurationFile.AppendLine("OutputPath|" + FormBase.VdwConfigurationSettings.VdwOutputPath); initialConfigurationFile.AppendLine("LoadPatternPath|" + FormBase.VdwConfigurationSettings.LoadPatternPath); initialConfigurationFile.AppendLine("VdwSchema|vdw"); initialConfigurationFile.AppendLine("/* End of file */"); var vdwConfigurationFileName = FormBase.GlobalParameters.VdwConfigurationPath + FormBase.GlobalParameters.VdwConfigurationFileName; localEvent = FileHandling.CreateConfigurationFile(vdwConfigurationFileName, initialConfigurationFile); if (localEvent.eventDescription != null) { FormBase.VdwConfigurationSettings.VdwEventLog.Add(localEvent); } }
public void DeleteFolder() { var testDir = Directories.TempPath + "TESTDIR_" + Misc.RandomString(); Directory.CreateDirectory(testDir); Assert.IsTrue(FileHandling.DeleteDirectory(testDir)); }
public static Func <Request, Response, Task> Upload(Configuration config) { return(async(req, res) => { var form = await req.GetFormDataAsync(); var unzip = form["unzip"] == "true"; var savePath = Path.Combine(config.PublicDirectory, "static"); foreach (var formFile in form.Files) { if (unzip && formFile.FileName.ToLowerInvariant().EndsWith(".zip")) { var tempPath = await FileHandling.SaveTempFile(config, formFile); await Task.Run(() => ZipFile.ExtractToDirectory(tempPath, savePath)); File.Delete(tempPath); } else { using (var publicFile = File.Create(Path.Combine(savePath, formFile.FileName))) { await formFile.CopyToAsync(publicFile); } } } await res.SendJson(GetPublicFiles(config)); }); }
public HttpStatusCode Upload(string securityID, FileUploadType fileType, HttpRequest httpRequest) { if (httpRequest.Files.Count != 1) { return(HttpStatusCode.BadRequest); } else { var postedFile = httpRequest.Files[0]; if (FileHandling.IsCSV(postedFile.FileName)) { return(HttpStatusCode.BadRequest); } filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName); postedFile.SaveAs(filePath); if (ProcessFile(securityID, fileType)) { return(HttpStatusCode.OK); } return(HttpStatusCode.InternalServerError); } }
private void ExportToPdfBtn_Clicked(object sender, EventArgs e) { string filename = "TEST.txt"; FileHandling file = new FileHandling(); file.WriteSpecifikLønPeriode(LønPeriode, App.Database.GetVariables().CurrentCompany); }
public static void StartProgram() { Console.Title = "My Classmates"; if (FileHandling.CheckFileFolderExistance() > 0) { Classmates.Populate(myClassmates); //Method for saving mockdata and user changes to a file. FileHandling.BinarySerializer(myClassmates); } // Else read the file else { myClassmates = FileHandling.BinaryDeSerializer(myClassmates); } Console.SetWindowSize(100, 40); FileHandling.CreateLogos(); //Runs the login method Login.UserLogin(); //If the program had to add any files, then populate that file with the standard classmates Menus.StartMenu(myClassmates); }
public void IsNotReadOnly() { if (FileHandling.IsReadOnly(Directories.Desktop)) { Assert.Fail(); } }
static void Main(string[] args) { var generator = new Generator(); var world = generator.GenerateWorld(80, 32, Random.Next(int.MaxValue)); byte[] jsonUtf8GZipped = world.ToJsonUTF8GZipped(true); // write to json if (FileHandling.TryWriteJsonUTF8GZipped(jsonUtf8GZipped)) { Console.WriteLine("Success Writing jsonUtf8"); } // build a texture if (TextureBuilder.TryGenerateBitmap(world, out Bitmap bitmap)) { Console.WriteLine("Success Building Bitmap"); // write to .bmp if (FileHandling.TryWriteImageToBitmap(bitmap)) { Console.WriteLine("Success Writing Bitmap"); } } }
public void ThatCheckFilesWorks() { // Common setup var file = Substitute.For <IFile>(); var directory = Substitute.For <IDirectory>(); var systemio = Substitute.For <ISystemIO>(); systemio.File.Returns(file); systemio.Directory.Returns(directory); var underTest = new FileHandling(systemio); // Assume var testdir = "someNiceDirectory"; directory.GetCurrentDirectory().Returns(testdir); directory.GetFiles(Arg.Is(testdir), Arg.Any <string>(), Arg.Is(SearchOption.AllDirectories)).Returns(new[] { "a", "b" }); // Act var resultA = underTest.CheckFilesInSomeDirectory(testdir).ToList(); // Assert Assert.That(resultA.Count, Is.EqualTo(2), "Count failed"); Assert.That(resultA[0], Is.EqualTo("a"), "First entry failed"); }
public async Task <string> InsertarVarios([FromForm] IFormFile file) { if (true && Data.grado > 2) { using var ContentMemory = new MemoryStream(); await file.CopyToAsync(ContentMemory); var content = Encoding.ASCII.GetString(ContentMemory.ToArray()); var nuevo = JsonConvert.DeserializeObject <List <Movie> >(content); FileHandling manejo = new FileHandling(); var meta = manejo.getMetadata(); foreach (var item in nuevo) { var movie = new Movie { director = item.director, imdbRating = item.imdbRating, genre = item.genre, releaseDate = item.releaseDate, rottenTomatoesRating = item.rottenTomatoesRating, title = item.title, nombre_año = Convert.ToInt32(meta[3]) }; Data.Instance.temp.Insertar(Convert.ToInt32(meta[3]), movie);//Modificar el aumentador } return("Valores insertados correctamente."); } else { throw new ArgumentException($"El grado {Data.grado} del árbol es incorrecto o el archivo no cuenta con estructura Json."); } }
private async Task HandleDropAsync(DragEventArgs e) { // thanks to https://stackoverflow.com/a/21707156/2023653 var files = (string[])e.Data.GetData(DataFormats.FileDrop); var resolvedFiles = ResolveFileList(files).ToArray(); //string basePath = resolvedFiles.First() DropStarted?.Invoke(resolvedFiles); int done = 0; var percentComplete = 0d; foreach (var file in resolvedFiles) { done++; percentComplete = done / (double)resolvedFiles.Length; try { var item = await FileHandling?.Invoke(new FileHandlingEventArgs(file, "oops", percentComplete)); if (item != null) { ListView.Items.Add(item); } } catch { } } DropCompleted?.Invoke(this, new EventArgs()); }
public void Test_MultiplePath_BlankFile(string value) { //Act bool actual = FileHandling.BlankFile(value); //Assert Assert.True(actual); }
public void Test_MultiplePath_CreateSecondFile(string value) { //Act bool actual = FileHandling.CreateSecondFile(value); //Assert Assert.True(actual); }
public void InitializeList() { AbstractSerialize serializeObj = new FileHandling(); BookList bookListObj = BookList.GetBookList(); serializeObj.ReadBookList(); Book.BookCount = bookListObj.ListOfBooks.Count; }
public void SerialiseJson(List <DXFLayerItem> listDXFLayerItems) { JsonSerializerOptions jsonOptions = new JsonSerializerOptions { WriteIndented = true }; FileHandling.SaveStringToFile(JsonSerializer.Serialize(listDXFLayerItems, jsonOptions), jsonFilePath, true); }
public void DeleteFile() { var testFile = Directories.TempPath + "TESTFILE_" + Misc.RandomString() + ".exe"; File.WriteAllLines(testFile, new string[0]); Assert.IsTrue(FileHandling.DeleteFile(testFile)); }
/* * --------------------------------------------------------------- * METHOD FOR USER LOGIN * --------------------------------------------------------------- */ public static bool UserLogin() { //Method that prints out the logo, checks the input password and log in the user if correct. bool loggedIn = default(bool); string error = default(string); int loginCount = default(int); int maxLoginTries = 3; do { Console.Clear(); FileHandling.LogoPrint("start"); //If wrong password, errormessage is printed in red as long as logincount is less than maxLoginTries. if (!string.IsNullOrEmpty(error) && loginCount < maxLoginTries) { Console.SetCursorPosition(15, 10); Print.Red(error); error = default(string); } Console.SetCursorPosition(15, 7); var pass = default(string); ConsoleKey key; Print.Yellow("Ange lösenordet (eller \"a\" för att avsluta)"); Console.SetCursorPosition(15, 8); Print.Blue(@"Lösenord \> "); Console.SetCursorPosition(26, 8); /* * If logincount is 3 or more, print out that the program will stop, and then exit the program after 3 seconds. */ if (loginCount >= 3) { Console.SetCursorPosition(15, 10); Print.Red("Du har skrivit fel lösenord för många gånger. Programmet avslutas"); Thread.Sleep(3000); Environment.Exit(0); } /*Do while that checks the keys that the user presses and overrides that key * and prints an * insted. Real password gets saved into pass variable and then checked in a switch case. */ do { //Overrids ReadKey so the typed Char is not displayed. This will be replaced further down. var keyInfo = Console.ReadKey(intercept: true); key = keyInfo.Key; //Check if backspace is pressed and string is longer than 1 char. if (key == ConsoleKey.Backspace && pass.Length > 0) { //Does 2 backspace and replaces the earlier saved password with everything in password until second last index Console.Write("\b \b"); pass = pass[0..^ 1]; }
public void GetMD5NotExist() { var testFile = Directories.TempPath + "TESTFILE_" + Misc.RandomString() + ".txt"; Options.GetMD5 = true; File.Delete(testFile); Assert.IsNull(FileHandling.GetMD5(testFile)); }
public void GetMD5() { var testFile = Directories.TempPath + "TESTFILE_" + Misc.RandomString() + ".txt"; File.WriteAllText(testFile, "This is a test string"); Options.GetMD5 = true; Assert.AreEqual("C639EFC1E98762233743A75E7798DD9C", FileHandling.GetMD5(testFile)); }
public void GetSizeFolder() { var size = FileHandling.GetSize("C:\\Windows\\Web"); if (size == 0) { Assert.Fail(); } }
public void ReadFileForeign() { var testFile = Directories.TempPath + "TESTFILE_" + Misc.RandomString() + ".txt"; File.WriteAllText(testFile, "This is a test stringÅ\n" + testFile); var readFile = FileHandling.ReadFile(testFile); Assert.AreEqual("This is a test stringÅ\n" + testFile, readFile); }
static void Main() { FileHandling fh = new FileHandling(); fh.createFolder(); fh.downloadIconFiles(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new KeyBoardLockerCore()); }
//osvježavanje liste datoteka koje se nalaze na lokalnom računalu private void refreshMyFiles_Click(object sender, EventArgs e) { FileHandling fh = new FileHandling(); dgvDownloads.DataSource = fh.fillMyFiles(); }