Inheritance: TreeBase, ITreeViewItem
コード例 #1
0
        public void OpenDirectory(string path)
        {
            this.directory = null;
            BeginUpdate();
            Items.Clear();
            try

            {
                foreach (string fileName in Directory.GetFiles(path))
                {
                    string ext = Path.GetExtension(fileName).ToLower();
                    if (supportedExtensions.Contains(ext))
                    {
                        FileNode node = new FileNode(fileName);
                        node.ImageIndex = GetIconName(fileName);
                        Items.Add(node);
                    }

                }
            }
            catch (Exception)
            {

            }
            finally
            {
                EndUpdate();
            }
        }
コード例 #2
0
        public OAVSProjectItem(FileNode fileNode)
        {
            if (fileNode == null)
                throw new ArgumentNullException("fileNode");

            this._fileNode = fileNode;
        }
コード例 #3
0
ファイル: FilterService.cs プロジェクト: sk8tz/LogViewer
        public void ApplyLogRecordsFilter(FileNode fileNode = null)
        {
            var selectedNodes = _fileBrowser.SelectedItems.OfType<FileNode>().ToArray();
            if (fileNode != null && !selectedNodes.Contains(fileNode))
            {
                return;
            }

            var logRecords = _logTableService.LogTable.Records;

            var oldRecords = logRecords.ToArray();

            var filteredRecords = FilterRecords(Filter, selectedNodes).ToArray();

            _dispatcherService.Invoke(() =>
            {
                using (logRecords.SuspendChangeNotifications())
                {
                    logRecords.ReplaceRange(filteredRecords);
                }

                foreach (var record in logRecords.Except(oldRecords))
                {
                    record.FileNode.IsExpanded = true;
                }
            }, true);
        }
コード例 #4
0
        public void ShouldListEntireTree()
        {
            // arrange
            IFile childFile;
            IFile rootFile;
            IFile folder = mockWalker.MockFolder("2", "folder",
                childFile = Utils.MockFile("3", "file.txt", "text/plain")
                );
            IFile rootFolder = mockWalker.MockFolder("root", "root",
                rootFile = Utils.MockFile("4", "hello.png", "image/png"),
                folder);

            IFileNode expected = new FileNode(
                Utils.MockFolder("root", "root"),  new[]
            {
                new FileNode(rootFile),
                new FileNode(folder, new List<IFileNode>
                {
                    new FileNode(childFile)
                })
            });

            // act
            var result = walker.ListRecurse("root");

            // assert
            Assert.AreEqual(expected, result);
        }
コード例 #5
0
        public void TestMetadata()
        {
            Dictionary<string, string> metadata = new Dictionary<string, string>();
            metadata.Add(FileOp.NextCIdentifierString(random), FileOp.NextNormalString(random));
            metadata.Add(FileOp.NextCIdentifierString(random), FileOp.NextNormalString(random));

            Test.Info("Metadata is =====================");
            foreach (var keyValue in metadata)
            {
                Test.Info("name:{0}  value:{1}", keyValue.Key, keyValue.Value);
            }

            DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);
            FileNode fileNode = new FileNode(DMLibTestBase.FileName)
            {
                SizeInByte = DMLibTestBase.FileSizeInKB * 1024L,
                Metadata = metadata
            };
            sourceDataInfo.RootNode.AddFileNode(fileNode);

            var result = this.ExecuteTestCase(sourceDataInfo, new TestExecutionOptions<DMLibDataInfo>());

            Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
            Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
        }
コード例 #6
0
ファイル: MainWindow.cs プロジェクト: pbalint/Playground
        private void RefreshDevices()
        {
            tv_dirs.Nodes.Clear();
            lv_files.Clear();

            if ( devices != null )
            {
                foreach ( Device dev in devices ) dev.Close();
            }

            devices = Device.GetPhysicalDevices();

            foreach ( Device dev in devices )
            {
                TreeNode root_node = new TreeNode( dev.DeviceName );
                root_node.ImageIndex = 0;
                root_node.SelectedImageIndex = 0;
                tv_dirs.Nodes.Add( root_node );
                List< FileSystem > filesystems = dev.GetFileSystems();

                foreach ( FileSystem fs in filesystems )
                {
                    FileNode node = new FileNode( fs.GetRootDir(), true );
                    root_node.Nodes.Add( node );
                }

                root_node.Expand();
            }
        }
コード例 #7
0
ファイル: WinFS.cs プロジェクト: Softsurve/Silver-Iodide
    public override FileNode read(string path, string flags, int offset, int length)
    {
        if (path == "")
        {
            return this.myroot;
        }
        else if (getWorkPathArray(path)[1] == "ctl")
        {
            return null;
        }
        else if (getWorkPathArray(path)[1] == "new")
        {
            return null;
        }
        else
        {
            int count = 0;

            while(count < this.myWindows.Count && this.myWindows[count].Name != getWorkPathArray(path)[1])
            {
                count++;
            }

            if(this.myWindows[count].Name == getWorkPathArray(path)[1])
            {
                FileNode winNode = new FileNode(getWorkPathArray(path)[1], fileTypes.Directory);
                return winNode;
            }
            else
                return null;
        }
    }
コード例 #8
0
 private void LoadImage(FileNode node, ListView targetListView)
 {
     var key = node.File.FullName;
     var item = targetListView.Items.Add(key, node.File.Name, DefaultImageKey);
     node.BlockingLoadImage();
     ImageList.Images.Add(key, node.Image);
     item.ImageKey = key;
 }
コード例 #9
0
 private void DoValidation(FileNode fileNode, int expectedErrors)
 {
     PropertyInfo fileNameInfo = typeof(FileNode).GetProperty("FileName");
     FileValidationAttribute attr = new FileValidationAttribute();
     List<ValidationError> errors = new List<ValidationError>();
     attr.Validate(fileNode, fileNameInfo, errors, ServiceProvider);
     Assert.AreEqual(expectedErrors, errors.Count);
 }
コード例 #10
0
        public static void WaitUntilFileCreated(string rootPath, FileNode fileNode, DataAdaptor<DMLibDataInfo> dataAdaptor, DMLibDataType dataType, int timeoutInSec = 300)
        {
            Func<bool> checkFileCreated = null;

            if (dataType == DMLibDataType.Local)
            {
                string filePath = dataAdaptor.GetAddress() + fileNode.GetLocalRelativePath();
                checkFileCreated = () =>
                {
                    return File.Exists(filePath);
                };
            }
            else if (dataType == DMLibDataType.PageBlob ||
                     dataType == DMLibDataType.AppendBlob)
            {
                CloudBlobDataAdaptor blobAdaptor = dataAdaptor as CloudBlobDataAdaptor;

                checkFileCreated = () =>
                {
                    CloudBlob cloudBlob = blobAdaptor.GetCloudBlobReference(rootPath, fileNode);
                    return cloudBlob.Exists(options: HelperConst.DefaultBlobOptions);
                };
            }
            else if (dataType == DMLibDataType.BlockBlob)
            {
                CloudBlobDataAdaptor blobAdaptor = dataAdaptor as CloudBlobDataAdaptor;

                checkFileCreated = () =>
                {
                    CloudBlockBlob blockBlob = blobAdaptor.GetCloudBlobReference(rootPath, fileNode) as CloudBlockBlob;
                    try
                    {
                        return blockBlob.DownloadBlockList(BlockListingFilter.All, options: HelperConst.DefaultBlobOptions).Any();
                    }
                    catch (StorageException)
                    {
                        return false;
                    }
                };
            }
            else if (dataType == DMLibDataType.CloudFile)
            {
                CloudFileDataAdaptor fileAdaptor = dataAdaptor as CloudFileDataAdaptor;

                checkFileCreated = () =>
                {
                    CloudFile cloudFile = fileAdaptor.GetCloudFileReference(rootPath, fileNode);
                    return cloudFile.Exists(options: HelperConst.DefaultFileOptions);
                };
            }
            else
            {
                Test.Error("Unexpected data type: {0}", DMLibTestContext.SourceType);
            }

            MultiDirectionTestHelper.WaitUntil(checkFileCreated, timeoutInSec);
        }
コード例 #11
0
 public void EnsureCanWriteToAValidFile()
 {
     string fileName = Path.GetTempFileName();
     FileNode fileNode = new FileNode(fileName);
     using (File.Create(fileName))
     {
     }
     DoValidation(fileNode, 0);
     if (File.Exists(fileName)) File.Delete(fileName);
 }
コード例 #12
0
ファイル: RARC.cs プロジェクト: pho/WindViewer
        public static void printAllFileEntries(FileNode Root)
        {
            Console.WriteLine("Node: " + Root.NodeName);
            foreach (RARC.FileEntry f in Root.Files) {
                Console.WriteLine("  Entry:" + f.FileName);
            }

            foreach (RARC.FileNode n in Root.ChildNodes)
                printAllFileEntries(n);
        }
コード例 #13
0
        public void FileCount_FolderWithOneFile()
        {
            IFileBase fileInfo = Utils.MockFolder("root", "root");
            IFileBase childFileInfo = Utils.MockFile("file", "file", "text/plain");
            IFileNode fileNode = new FileNode(fileInfo, new List<IFileNode>
            {
                new FileNode(childFileInfo)
            });

            Assert.AreEqual(1, fileNode.FileCount());
        }
コード例 #14
0
        public void ShouldCopyChildren()
        {
            IFileBase fileInfo = Mock.Of<IFileBase>(f => f.Id == "parent");
            IFileBase childFileInfo = Mock.Of<IFileBase>(f => f.Id == "child");
            FileNode fileNode = new FileNode(fileInfo, new List<IFileNode>
            {
                new FileNode(childFileInfo)
            });

            Assert.AreEqual("child", fileNode.Children[0].Id);
        }
コード例 #15
0
        public static void AddOneFileInBytes(DirNode dirNode, string fileName, long fileSizeInB, FileAttributes? fa = null, DateTime? lmt = null)
        {
            FileNode fileNode = new FileNode(fileName)
            {
                SizeInByte = fileSizeInB,
                FileAttr = fa,
                LastModifiedTime = lmt,
            };

            dirNode.AddFileNode(fileNode);
        }
コード例 #16
0
        public static void AddMultipleFilesDifferentSize(DirNode dirNode, string filePrefix, int[] fileSizes)
        {
            for (int i = 0; i < fileSizes.Length; ++i)
            {
                FileNode fileNode = new FileNode(filePrefix + "_" + i)
                {
                    SizeInByte = fileSizes[i] * 1024
                };

                dirNode.AddFileNode(fileNode);
            }
        }
コード例 #17
0
        public void ShouldListEmptyFolder()
        {
            // arrange
            mockWalker.MockFolder("root", "root");
            var expected = new FileNode(Utils.MockFolder("root", "root"));

            // act
            var result = walker.ListRecurse("root");

            // assert
            Assert.AreEqual(expected, result);
            Assert.AreEqual(0, result.Children.Count);
        }
コード例 #18
0
        public void ShouldListSingleFile()
        {
            // arrange
            var mockFile = Utils.MockFile("fileId", "file.txt", "text/plain");
            var expected = new FileNode(mockFile);

            // act
            var result = walker.ListRecurse(mockFile);

            // assert
            Assert.AreEqual(expected, result);
            Assert.AreEqual(0, result.Children.Count);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: epdumitru/mysqlib
		public static void Start()
		{
			AppDomain.CurrentDomain.UnhandledException += LogException;
			URL url = new URL(ConfigurationManager.AppSettings["URL"]);
			fileNodeImpl = new FileNodeImpl(url);
			fileNodeImpl.Create();
			isStop = false;
			while (!isStop)
			{
				Thread.Sleep(10000);
			}
			Log.WriteDebug("File server started.");
		}
コード例 #20
0
ファイル: BEdit.cs プロジェクト: Softsurve/Silver-Iodide
        public BEdit(bitboardWorld world, string path)
        {
            this.myWorld = world;

            InitializeComponent();

            if (path != "" && path != null)
            {
                this.currentPath = path;
                this.Name = path;
                editFile = myWorld.agi.read(path, "", 0, 0);
                if (editFile != null && editFile.getType() == fileTypes.Text)
                    richTextBox1.Text = editFile.getData();
            }
        }
コード例 #21
0
ファイル: HomeFS.cs プロジェクト: Softsurve/Silver-Iodide
    public HomeFS()
        : base()
    {
        this.myroot = base.init();
        this.sysHomePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

        if (Directory.Exists(sysHomePath))
        {
            string[] fileEntries = Directory.GetFiles(sysHomePath);

            foreach (string fileName in fileEntries)
                this.myroot.addChild(new FileNode(getFileNameFromPath(fileName), fileTypes.Text));

            string[] subdirectoryEntries = Directory.GetDirectories(sysHomePath);
            foreach (string subdirectory in subdirectoryEntries)
                this.myroot.addChild(new FileNode(getFileNameFromPath(subdirectory), fileTypes.Directory));
        }
    }
コード例 #22
0
        public void FileCount_TwoFoldersThreeFiles()
        {
            IFileBase rootFolder = Utils.MockFolder("root", "root");
            IFileBase childFolder = Utils.MockFolder("folder", "folder");
            IFileBase rootFile = Utils.MockFile("file", "file", "text/plain");
            IFileBase childFile1 = Utils.MockFile("file1", "file1", "text/plain");
            IFileBase childFile2 = Utils.MockFile("file2", "file2", "text/plain");
            IFileNode fileNode = new FileNode(rootFolder, new List<IFileNode>
            {
                new FileNode(rootFile),
                new FileNode(childFolder, new List<IFileNode>
                {
                    new FileNode(childFile1),
                    new FileNode(childFile2)
                })
            });

            Assert.AreEqual(3, fileNode.FileCount());
        }
コード例 #23
0
ファイル: TimeFS.cs プロジェクト: Softsurve/Silver-Iodide
 public override FileNode read(string path, string flags, int offset, int length)
 {
     if(path == "")
     {
         return this.myroot;
     }
     else if (getWorkPathArray(path)[1] == "time")
     {
         FileNode timeNode = new FileNode(getNewfileName(path), fileTypes.Text);
         timeNode.putData(DateTime.Now.ToLongTimeString());
         return timeNode;
     }
     else if (getWorkPathArray(path)[1] == "date")
     {
         FileNode dateNode = new FileNode(getNewfileName(path), fileTypes.Text);
         dateNode.putData(DateTime.Now.ToLongDateString());
         return dateNode;
     }
     else
         return null;
 }
コード例 #24
0
ファイル: HomeFS.cs プロジェクト: Softsurve/Silver-Iodide
    public override FileNode read(string path, string flags, int offset, int length)
    {
        Console.WriteLine("path = " + path);
        if (path == "")
        {
            return this.myroot;
        }
        else
        {
            string loadPath = sysHomePath + buildWindowsFilePath(path);

            if (Directory.Exists(loadPath))
            {
                Console.WriteLine("loading Directory");
                string[] fileEntries = Directory.GetFiles(loadPath);

                FileNode tempNode = new FileNode(path, fileTypes.Directory);

                foreach (string fileName in fileEntries)
                    tempNode.addChild(new FileNode(getFileNameFromPath(fileName), fileTypes.Text));

                string[] subdirectoryEntries = Directory.GetDirectories(loadPath);
                foreach (string subdirectory in subdirectoryEntries)
                    tempNode.addChild(new FileNode(getFileNameFromPath(subdirectory), fileTypes.Directory));

                return tempNode;

            }
            else if (File.Exists(loadPath))
            {
                FileNode tempNode = new FileNode(getFileNameFromPath(path), fileTypes.Text);

                string filebuffer = File.ReadAllText(loadPath);
                tempNode.putData(filebuffer);
                return tempNode;
            }
            else
                return null;
        }
    }
コード例 #25
0
ファイル: FileNodeService.cs プロジェクト: sk8tz/LogViewer
        public void LoadFileNode(FileNode fileNode)
        {
            Log.Debug("Loading file node '{0}'", fileNode);

            try
            {
                _dispatcherService.Invoke(() =>
                {
                    var fileRecords = _logReaderService.LoadRecordsFromFileAsync(fileNode).Result;

                    var logRecords = fileNode.Records;
                    using (logRecords.SuspendChangeNotifications())
                    {
                        logRecords.ReplaceRange(fileRecords);
                    }
                }, true);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to load file node '{0}'", fileNode);
            }
        }
コード例 #26
0
    public static Node Create(string path, Node parent)
    {
        var node = new Node();

        if (IsDirectory(path))
        {
            node.Name = GetDirectoryName(path);
            node.Path = GetDirectoryPath(path);
            node.Parent = parent;
            node.Type = Node.DirectoryTypeName;
        }
        else
        {
            node = new FileNode();
            node.Parent = parent;
            node.Name = Path.GetFileName(path);
            node.Path = path;
            node.Type = Node.FileTypeName;
        }

        return node;
    }
コード例 #27
0
		public override void Run()
		{
			WebReferenceNode node = Owner as WebReferenceNode;
			if (node != null && node.Project != null && node.ProjectItem != null) {
				WebReferenceUrl url = (WebReferenceUrl)node.ProjectItem;
				try {
					// Discover web services at url.
					DiscoveryClientProtocol protocol = DiscoverWebServices(url.UpdateFromURL);
					if (protocol != null) {
						// Save web services.
						WebReference webReference = new WebReference(url.Project, url.UpdateFromURL, node.Text, url.Namespace, protocol);
						webReference.Save();
						
						// Update project.
						WebReferenceChanges changes = webReference.GetChanges(url.Project);
						if (changes.Changed) {
							foreach (ProjectItem itemRemoved in changes.ItemsRemoved) {
								ProjectService.RemoveProjectItem(url.Project, itemRemoved);
								FileService.RemoveFile(itemRemoved.FileName, false);
							}
							foreach (ProjectItem newItem in changes.NewItems) {
								ProjectService.AddProjectItem(url.Project, newItem);
								FileNode fileNode = new FileNode(newItem.FileName, FileNodeStatus.InProject);
								fileNode.InsertSorted(node);
							}
							ProjectBrowserPad.Instance.ProjectBrowserControl.TreeView.Sort();
							url.Project.Save();
						}
						
						// Update code completion.
						SD.ParserService.ParseFileAsync(FileName.Create(webReference.WebProxyFileName), parentProject: url.Project).FireAndForget();
					}
				} catch (WebException ex) {
					LoggingService.Debug(ex);
					MessageService.ShowError(GetRefreshWebReferenceErrorMessage(ex, url.UpdateFromURL));
				}
			}
		}
コード例 #28
0
ファイル: FileNodeService.cs プロジェクト: sk8tz/LogViewer
        public FileNode CreateFileNode(string fileName)
        {
            Argument.IsNotNullOrEmpty(() => fileName);

            //Log.Debug("Creating file node '{0}'", fileName);

            var fileNode = new FileNode(new FileInfo(fileName));

            fileNode.Name = fileNode.FileInfo.Name;
            fileNode.IsUnifyNamed = _fileNameMask.IsMatch(fileNode.FileInfo.Name);
            if (!fileNode.IsUnifyNamed)
            {
                fileNode.Name = fileNode.FileInfo.Name;
            }
            else
            {
                fileNode.Name = fileNode.FileInfo.Name;
                var dateTimeString = Regex.Match(fileNode.FileInfo.Name, @"(\d{4}-\d{2}-\d{2})").Value;
                fileNode.DateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd", null, DateTimeStyles.None);
            }

            return fileNode;
        }
コード例 #29
0
		public override void Run()
		{
			WebReferenceNode node = Owner as WebReferenceNode;
			if (node != null && node.Project != null && node.ProjectItem != null) {
				WebReferenceUrl url = (WebReferenceUrl)node.ProjectItem;
				try {
					// Discover web services at url.
					DiscoveryClientProtocol protocol = DiscoverWebServices(url.UpdateFromURL);
					if (protocol != null) {
						// Save web services.
						WebReference webReference = new WebReference(url.Project, url.UpdateFromURL, node.Text, url.Namespace, protocol);
						webReference.Save();
						
						// Update project.
						WebReferenceChanges changes = webReference.GetChanges(url.Project);
						if (changes.Changed) {
							foreach (ProjectItem itemRemoved in changes.ItemsRemoved) {
								ProjectService.RemoveProjectItem(url.Project, itemRemoved);
								FileService.RemoveFile(itemRemoved.FileName, false);
							}
							foreach (ProjectItem newItem in changes.NewItems) {
								ProjectService.AddProjectItem(url.Project, newItem);
								FileNode fileNode = new FileNode(newItem.FileName, FileNodeStatus.InProject);
								fileNode.InsertSorted(node);
							}
							ProjectBrowserPad.Instance.ProjectBrowserControl.TreeView.Sort();
							url.Project.Save();
						}
						
						// Update code completion.
						ParserService.ParseFile(webReference.WebProxyFileName);
					}
				} catch (WebException ex) {
					MessageService.ShowException(ex, String.Format(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.ProjectBrowser.RefreshWebReference.ReadServiceDescriptionError}"), url.UpdateFromURL));
				}
			}
		}
コード例 #30
0
		public static void ExcludeFileNode(FileNode fileNode)
		{
			List<FileNode> dependentNodes = new List<FileNode>();
			foreach (TreeNode subNode in fileNode.Nodes) {
				// exclude dependent files
				if (subNode is FileNode)
					dependentNodes.Add((FileNode)subNode);
			}
			dependentNodes.ForEach(ExcludeFileNode);
			
			bool isLink = fileNode.IsLink;
			if (fileNode.ProjectItem != null) { // don't try to exclude same node twice
				ProjectService.RemoveProjectItem(fileNode.Project, fileNode.ProjectItem);
			}
			if (isLink) {
				fileNode.Remove();
			} else {
				fileNode.ProjectItem = null;
				fileNode.FileNodeStatus = FileNodeStatus.None;
				if (fileNode.Parent is ExtTreeNode) {
					((ExtTreeNode)fileNode.Parent).UpdateVisibility();
				}
			}
		}
コード例 #31
0
 public abstract object GetTransferObject(FileNode fileNode);
コード例 #32
0
 public RoslynUstCommonConverterVisitor(SyntaxNode root, FileNode fileNode)
 {
     Root     = root;
     FileNode = fileNode;
 }
コード例 #33
0
 public RoslynUstCommonConverterVisitor(SyntaxTree syntaxTree, string filePath)
 {
     Root     = syntaxTree.GetRoot();
     FileNode = new FileNode(filePath, syntaxTree.GetText().ToString());
 }
コード例 #34
0
 protected override void InternalDelete(FileNode path)
 {
     File.Delete(path.AbosolutePath);
 }
コード例 #35
0
 protected EntityDeclaration(IdToken name, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Name = name;
 }
コード例 #36
0
 public OAComposeStarFileItem(OAProject project, FileNode node)
     : base(project, node)
 {
 }
コード例 #37
0
ファイル: ArgsNode.cs プロジェクト: Yikez978/PT.PM
 public ArgsNode(IEnumerable <Expression> args, TextSpan textSpan, FileNode fileNode)
     : base(args, textSpan, fileNode)
 {
 }
コード例 #38
0
        public Stream Open(ResourcePath path, FileMode fileMode, FileAccess access, FileShare share)
        {
            if (!path.IsRooted)
            {
                throw new ArgumentException("Path must be rooted", nameof(path));
            }

            path = path.Clean();

            var parentPath = path.Directory;

            if (!TryGetNodeAt(parentPath, out var parent) || !(parent is DirectoryNode parentDir))
            {
                throw new ArgumentException("Parent directory does not exist.");
            }

            var fileName = path.Filename;

            if (parentDir.Children.TryGetValue(fileName, out var maybeFileNode) && maybeFileNode is DirectoryNode)
            {
                throw new ArgumentException("There is a directory at that location.");
            }

            var fileNode = (FileNode)maybeFileNode !;

            switch (fileMode)
            {
            case FileMode.Append:
            {
                if (fileNode == null)
                {
                    fileNode = new FileNode();
                    parentDir.Children.Add(fileName, fileNode);
                }

                return(new VirtualFileStream(fileNode.Contents, false, true, fileNode.Contents.Length));
            }

            case FileMode.Create:
            {
                if (fileNode == null)
                {
                    fileNode = new FileNode();
                    parentDir.Children.Add(fileName, fileNode);
                }
                else
                {
                    // Clear contents if it already exists.
                    fileNode.Contents.SetLength(0);
                }

                return(new VirtualFileStream(fileNode.Contents, true, true, 0));
            }

            case FileMode.CreateNew:
            {
                if (fileNode != null)
                {
                    throw new IOException("File already exists.");
                }

                fileNode = new FileNode();
                parentDir.Children.Add(fileName, fileNode);

                return(new VirtualFileStream(fileNode.Contents, true, true, 0));
            }

            case FileMode.Open:
            {
                if (fileNode == null)
                {
                    throw new FileNotFoundException();
                }

                return(new VirtualFileStream(fileNode.Contents, true, true, 0));
            }

            case FileMode.OpenOrCreate:
            {
                if (fileNode == null)
                {
                    fileNode = new FileNode();
                    parentDir.Children.Add(fileName, fileNode);
                }

                return(new VirtualFileStream(fileNode.Contents, true, true, 0));
            }

            case FileMode.Truncate:
            {
                if (fileNode == null)
                {
                    throw new FileNotFoundException();
                }

                fileNode.Contents.SetLength(0);

                return(new VirtualFileStream(fileNode.Contents, true, true, 0));
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(fileMode), fileMode, null);
            }
        }
コード例 #39
0
 internal XSharpEventBindingProvider(FileNode xsFile)
 {
     _xsFile  = xsFile;
     _project = xsFile.ProjectMgr;
 }
コード例 #40
0
 internal OAFileItem(OAProject project, FileNode node)
     : base(project, node)
 {
 }
コード例 #41
0
 protected CollectionNode(IEnumerable <TUstNode> collection, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Collection = collection as List <TUstNode> ?? collection.ToList();
 }
コード例 #42
0
 public ModifierLiteral(Modifier modifier, TextSpan textSpan, FileNode fileNode)
     : base(textSpan, fileNode)
 {
     Modifier = modifier;
 }
コード例 #43
0
        private void ServersTreeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            LabelEditAction EditAction = this.EditAction;

            this.EditAction = LabelEditAction.None;
            if (e.Label == null || e.Label == "")
            {
                if (EditAction == LabelEditAction.Rename)
                {
                    if (OldLabelEditName != null)
                    {
                        e.Node.Text = OldLabelEditName;
                    }
                }
                else if (EditAction == LabelEditAction.NewFile || EditAction == LabelEditAction.NewDirectory)
                {
                    e.Node.Remove();
                }
                e.CancelEdit = true;
                return;
            }

            if (EditAction == LabelEditAction.Rename)
            {
                #region ActionRename
                if (e.Node is FileNode)
                {
                    FileNode node = (FileNode)e.Node;
                    FileInfo file = node.GetFile();
                    string   path = file.DirectoryName + Path.DirectorySeparatorChar + e.Label;

                    if (File.Exists(path))
                    {
                        Error.Show("ErrorFileExists");
                        e.CancelEdit = true; return;
                    }
                    try { file.MoveTo(path); }
                    catch (IOException)
                    {
                        Error.Show("ErrorFileInvalidName");
                        e.CancelEdit = true; return;
                    }
                }

                else if (e.Node is ServerNode)
                {
                    ServerNode    node      = (ServerNode)e.Node;
                    DirectoryInfo directory = node.GetDirectory();
                    string        path      = directory.Parent.FullName + Path.DirectorySeparatorChar + e.Label;

                    if (Directory.Exists(path))
                    {
                        Error.Show("ErrorServerExists");
                    }
                    else
                    {
                        try
                        {
                            directory.MoveTo(path);
                            node.GetServerData().name = e.Label;
                            node.GetServerData().Save();
                        }
                        catch (IOException)
                        {
                            Error.Show("ErrorServerInvalidName");
                        }
                    }
                    node.Text    = node.GetServerData().ToString();
                    e.CancelEdit = true;
                }

                else if (e.Node is DirectoryNode)
                {
                    DirectoryNode node      = (DirectoryNode)e.Node;
                    DirectoryInfo directory = node.GetDirectory();
                    string        path      = directory.Parent.FullName + Path.DirectorySeparatorChar + e.Label;

                    if (Directory.Exists(path))
                    {
                        Error.Show("ErrorDirectoryExists");
                        e.CancelEdit = true; return;
                    }
                    try
                    {
                        directory.MoveTo(path);
                    }
                    catch (IOException)
                    {
                        Error.Show("ErrorDirectoryInvalidName");
                        e.CancelEdit = true; return;
                    }
                }

                else if (e.Node is RemoteServerNode)
                {
                    RemoteServerNode  node = (RemoteServerNode)e.Node;
                    Data.RemoteServer data = new Data.RemoteServer();
                    data.name = e.Label;
                    if (!Directory.Exists(data.GetDirectory()))
                    {
                        Directory.Move(node.GetServerData().GetDirectory(), data.GetDirectory());
                        node.GetServerData().name = e.Label;
                        node.GetServerData().Save();
                    }
                    node.Text    = node.GetServerData().ToString();
                    e.CancelEdit = true;
                }

                else if (e.Node is RemoteDirectoryNode)
                {
                    RemoteDirectoryNode node = (RemoteDirectoryNode)e.Node;
                    Ftp.rename(node.data, node.directory, e.Label);
                    ((RemoteDirectoryNode)e.Node.Parent).Refresh();
                    e.CancelEdit = true;
                }

                else if (e.Node is RemoteFileNode)
                {
                    RemoteFileNode node = (RemoteFileNode)e.Node;
                    Ftp.rename(node.data, node.GetFile(), e.Label);
                    ((RemoteDirectoryNode)e.Node.Parent).Refresh();
                    e.CancelEdit = true;
                }
                #endregion
            }

            else if (EditAction == LabelEditAction.NewFile)
            {
                #region ActionNewFile
                if (e.Node.Parent is DirectoryNode)
                {
                    DirectoryNode node = (DirectoryNode)e.Node.Parent;
                    string        path = node.GetDirectory().FullName + Path.DirectorySeparatorChar + e.Label;
                    if (File.Exists(path))
                    {
                        Error.Show("ErrorFileExists");
                    }
                    else
                    {
                        try
                        {
                            File.Create(path).Close();
                        }
                        catch (IOException)
                        {
                            Error.Show("ErrorFileInvalidName");
                        }
                    }
                    e.Node.Remove();
                }
                else if (e.Node.Parent is RemoteDirectoryNode)
                {
                    RemoteDirectoryNode node = (RemoteDirectoryNode)e.Node.Parent;
                    File.Create(Main.TempDirectory + e.Label).Close();
                    Ftp.upload(node.data, node.directory + e.Label, Main.TempDirectory + e.Label);
                    e.Node.Remove();
                    node.Refresh();
                }
                #endregion ;
            }

            else if (EditAction == LabelEditAction.NewDirectory)
            {
                #region ActionNewDirectory
                if (e.Node.Parent is DirectoryNode)
                {
                    DirectoryNode node = (DirectoryNode)e.Node.Parent;
                    string        path = node.GetDirectory().FullName + Path.DirectorySeparatorChar + e.Label;
                    if (Directory.Exists(path))
                    {
                        Error.Show("ErrorDirectoryExists");
                    }
                    else
                    {
                        try
                        {
                            Directory.CreateDirectory(path);
                        }
                        catch (IOException)
                        {
                            Error.Show("ErrorDirectoryInvalidName");
                        }
                    }
                    e.Node.Remove();
                }
                else if (e.Node.Parent is RemoteDirectoryNode)
                {
                    RemoteDirectoryNode node = (RemoteDirectoryNode)e.Node.Parent;
                    Ftp.createDirectory(node.data, node.directory + e.Label);
                    e.Node.Remove();
                    node.Refresh();
                }
                #endregion
            }
        }
コード例 #44
0
        public override PlatformData Create(string path, Game game, ProgressIndicator progress)
        {
            PlatformData data = new PlatformData(this, game);

            DirectoryNode dir = data.GetDirectoryStructure(path);

            data.Game = Platform.DetermineGame(data);

            try {
                FileNode qbpak = dir.Navigate("pak/qb.pak.ngc") as FileNode;
                if (qbpak == null)
                {
                    throw new FormatException("Couldn't find qb.pak on Guitar Hero Wii disc.");
                }

                FileNode qspak = dir.Navigate("pak/qs.pak.ngc") as FileNode;
                if (qspak == null)
                {
                    throw new FormatException("Couldn't find qs.pak on Guitar Hero Wii disc.");
                }

                Pak qs = new Pak(new EndianReader(qspak.Data, Endianness.BigEndian));

                StringList strings = new StringList();
                foreach (Pak.Node node in qs.Nodes)
                {
                    strings.ParseFromStream(node.Data);
                }

                Pak      qb           = new Pak(new EndianReader(qbpak.Data, Endianness.BigEndian));
                FileNode songlistfile = qb.FindFile(@"scripts\guitar\songlist.qb.ngc");
                if (songlistfile == null)
                {
                    songlistfile = qb.FindFile(@"scripts\guitar\songlist.qb");
                }

                if (songlistfile == null)
                {
                    throw new FormatException("Couldn't find the songlist on the Guitar Hero Wii disc pak.");
                }
                QbFile songlist = new QbFile(songlistfile.Data, PakFormat);

                data.Session["rootdir"] = dir;

                List <QbKey> listkeys = new List <QbKey>();
                foreach (uint songlistkey in NeversoftMetadata.SonglistKeys)
                {
                    QbKey        key  = QbKey.Create(songlistkey);
                    QbItemStruct list = songlist.FindItem(key, true) as QbItemStruct;
                    if (list != null && list.Items.Count > 0)
                    {
                        listkeys.Add(key);
                    }
                }

                progress.NewTask(listkeys.Count);
                List <string> songsadded = new List <string>();
                foreach (QbKey songlistkey in listkeys)
                {
                    QbItemStruct list = songlist.FindItem(songlistkey, true) as QbItemStruct;

                    progress.NewTask(list.Items.Count);

                    foreach (QbItemArray item in list.Items.OfType <QbItemArray>())
                    {
                        item.Items[0].ItemQbKey = item.ItemQbKey;
                        SongData song = NeversoftMetadata.GetSongData(data, item.Items[0] as QbItemStruct, strings);

                        progress.Progress();

                        if (songsadded.Contains(song.ID))
                        {
                            continue;
                        }

                        try {
                            if (AddSong(data, song, progress))
                            {
                                songsadded.Add(song.ID);
                            }
                        } catch (Exception exception) {
                            Exceptions.Warning(exception, "Unable to properly parse " + song.Name);
                        }
                    }

                    progress.EndTask();
                    progress.Progress();
                }
                progress.EndTask();

                qbpak.Data.Close();
                qspak.Data.Close();
            } catch (Exception exception) {
                Exceptions.Error(exception, "An error occurred while parsing the Guitar Hero Wii disc.");
            }

            return(data);
        }
コード例 #45
0
        /// <summary>
        /// process the http request
        /// </summary>
        /// <param name="context">http context</param>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            response.StatusCode = (int)HttpStatusCode.BadRequest;

            try
            {
                // Make sure that there is a session.
                if (context.Session != null)
                {
                    //HttpService service = Session[ serviceTag ];
                    response.Cache.SetCacheability(HttpCacheability.NoCache);

                    string method = request.HttpMethod.ToLower();

                    log.Debug("Simias.HttpFile.Handler.ProcessRequest called");
                    log.Debug("  method: " + method);

                    //SyncMethod method = (SyncMethod)Enum.Parse(typeof(SyncMethod), Request.Headers.Get(SyncHeaders.Method), true);
                    if (method == "get")
                    {
                        // Must a query string which contains the domainid and the
                        // filenodeid for the file caller is attempting to download.
                        if (request.QueryString.Count > 0)
                        {
                            Collection collection;
                            Domain     domain;
                            FileNode   fileNode;
                            Node       node;
                            Store      store = Store.GetStore();

                            string domainID = request.QueryString["did"];
                            if (domainID == null)
                            {
                                domainID = store.DefaultDomain;
                            }

                            string fileID = request.QueryString["fid"];
                            if (fileID != null)
                            {
                                log.Debug("  domainID: " + domainID);
                                log.Debug("  fileID: " + fileID);
                                domain = Store.GetStore().GetDomain(domainID);

                                node = domain.GetNodeByID(fileID);
                                if (node != null)
                                {
                                    Property cid = node.Properties.GetSingleProperty("CollectionId");
                                    collection = store.GetCollectionByID(cid.Value as string);
                                    fileNode   = new FileNode(node);
                                    string fullPath = fileNode.GetFullPath(collection);
                                    string fileName = fileNode.GetFileName();

                                    log.Debug("  nodename: " + fileNode.Name);
                                    log.Debug("  filename: " + fileName);
                                    log.Debug("  fullpath: " + fullPath);

                                    response.StatusCode = (int)HttpStatusCode.OK;

                                    Property lastModified = node.Properties.GetSingleProperty("LastModified");
                                    if (lastModified != null)
                                    {
                                        DateTime dt = (DateTime)lastModified.Value;
                                        response.AddHeader(
                                            "Last-Modified",
                                            Util.GetRfc822Date((DateTime)lastModified.Value));
                                    }

                                    response.AddHeader(
                                        "Content-length",
                                        fileNode.Length.ToString());

                                    response.ContentType =
                                        Simias.HttpFile.Response.GetMimeType(fileName).ToLower();

                                    if (response.ContentType.Equals("text/plain"))
                                    {
                                        response.AddHeader(
                                            "Content-Disposition",
                                            "inline; filename=\"" + fileName + "\"");
                                    }
                                    else
                                    if (response.ContentType.Equals("text/xml"))
                                    {
                                        response.AddHeader(
                                            "Content-Disposition",
                                            "inline; filename=\"" + fileName + "\"");
                                    }
                                    else
                                    if (response.ContentType.StartsWith("image"))
                                    {
                                        response.AddHeader(
                                            "Content-Disposition",
                                            "inline; filename=\"" + fileName + "\"");
                                    }
                                    else
                                    {
                                        response.AddHeader(
                                            "Content-Disposition",
                                            "attachment; filename=\"" + fileName + "\"");
                                    }

                                    response.TransmitFile(fullPath);

                                    /*
                                     * response.
                                     * FileStream stream =
                                     *      File.Open(
                                     *              fullPath,
                                     *              System.IO.FileMode.Open,
                                     *              System.IO.FileAccess.Read,
                                     *              System.IO.FileShare.Read );
                                     */
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                log.Error(ex.StackTrace);

                response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            finally
            {
                response.End();
            }
        }
コード例 #46
0
 void FileNode_OnFileNodeRefresh(FileNode node)
 {
     UpdateNodeStatus(node);
 }
コード例 #47
0
 protected override Stream InternalGetFileStream(FileNode node)
 {
     return(File.Open(node.AbosolutePath, FileMode.Open));
 }
コード例 #48
0
ファイル: Extensions.cs プロジェクト: vitorcamp/PTVS
 internal static AnalysisEntry GetAnalysisEntry(this FileNode node)
 {
     return(((PythonProjectNode)node.ProjectMgr).GetAnalyzer().GetAnalysisEntryFromPath(node.Url));
 }
コード例 #49
0
 protected override void InternalMove(FileNode source, FileNode dist)
 {
     File.Move(source.AbosolutePath, dist.AbosolutePath);
 }
コード例 #50
0
        void AddFileNodeTo(TreeNode node)
        {
            var fileNode = new FileNode(newFileAddedToProject.FileName, FileNodeStatus.InProject);

            fileNode.InsertSorted(node);
        }
コード例 #51
0
        private static void AddChild(MenuItem parent, FileNode path)
        {
            var item = new FileButton(path);

            parent.AddChild(item);
        }
コード例 #52
0
 bool FileNodeMatchesNewFileAdded(FileNode fileNode)
 {
     return(FileUtility.IsEqualFileName(fileNode.FileName, newFileAddedToProject.FileName));
 }
コード例 #53
0
 public RoslynUstCommonConverterVisitor(SyntaxTree syntaxTree, FileNode fileNode)
 {
     Root     = syntaxTree.GetRoot();
     FileNode = fileNode;
 }
コード例 #54
0
 public static async Task ReloadFileNodeAsync(this IFileNodeService fileNodeService, FileNode fileNode)
 {
     await Task.Factory.StartNew(() => fileNodeService.ReloadFileNode(fileNode));
 }
コード例 #55
0
ファイル: NodejsFileNode.cs プロジェクト: girish/nodejstools
 protected override void RenameChildNodes(FileNode parentNode)
 {
     base.RenameChildNodes(parentNode);
     this.ProjectMgr.Analyzer.ReloadComplete();
 }
コード例 #56
0
ファイル: SiteMapEditorPane.cs プロジェクト: Tyler-Zhou/SHFB
        /// <summary>
        /// Add new topics from all files in a selected folder
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void cmdAddAllFromFolder_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            FileNode           thisNode = this.FileNode;
            TocEntryCollection parent, newTopics = new TocEntryCollection(null);
            TocEntry           selectedTopic = base.UIControl.CurrentTopic;
            string             projectPath   = Path.GetDirectoryName(siteMapFile.Project.Filename);
            int idx;

            using (WinFormsFolderBrowserDialog dlg = new WinFormsFolderBrowserDialog())
            {
                dlg.Description  = "Select a folder to add all of its content";
                dlg.SelectedPath = (selectedTopic != null && selectedTopic.SourceFile.Path.Length != 0) ?
                                   Path.GetDirectoryName(selectedTopic.SourceFile) : projectPath;

                if (dlg.ShowDialog() == WinFormsDialogResult.OK)
                {
                    Utility.GetServiceFromPackage <IVsUIShell, SVsUIShell>(true).SetWaitCursor();

                    newTopics.AddTopicsFromFolder(dlg.SelectedPath, dlg.SelectedPath, siteMapFile.Project);

                    if (thisNode != null)
                    {
                        thisNode.ProjectMgr.RefreshProject();
                    }
                }

                if (newTopics.Count != 0)
                {
                    if (e.Parameter == null || selectedTopic == null)
                    {
                        // Insert as siblings
                        if (selectedTopic == null)
                        {
                            parent = base.UIControl.Topics;
                            idx    = 0;
                        }
                        else
                        {
                            parent = selectedTopic.Parent;
                            idx    = parent.IndexOf(selectedTopic) + 1;
                        }

                        foreach (TocEntry t in newTopics)
                        {
                            parent.Insert(idx++, t);
                        }
                    }
                    else
                    {
                        // Insert as children
                        parent = selectedTopic.Children;

                        foreach (TocEntry t in newTopics)
                        {
                            parent.Add(t);
                        }

                        selectedTopic.IsExpanded = true;
                    }
                }
            }
        }
コード例 #57
0
        public void TestDirectoryWithSpecialCharNamedBlobs()
        {
#if DNXCORE50
            // TODO: There's a known issue that signature for URI with '[' or ']' doesn't work.
            string specialChars = "~`!@#$%()-_+={};?.^&";
#else
            string specialChars = "~`!@#$%()-_+={}[];?.^&";
#endif
            DMLibDataInfo sourceDataInfo = new DMLibDataInfo(string.Empty);

            var subDirWithDot = new DirNode(DMLibTestBase.FolderName + "." + DMLibTestBase.FolderName);

            for (int i = 0; i < specialChars.Length; ++i)
            {
                string fileName = DMLibTestBase.FileName + specialChars[i] + DMLibTestBase.FileName;

                if (random.Next(2) == 0)
                {
                    if ((specialChars[i] != '.') &&
                        (random.Next(2) == 0))
                    {
                        string folderName = DMLibTestBase.FolderName + specialChars[i] + DMLibTestBase.FolderName;

                        var subDir = new DirNode(folderName);
                        DMLibDataHelper.AddOneFileInBytes(subDir, fileName, 1024);
                        FileNode fileNode1 = subDir.GetFileNode(fileName);
                        fileNode1.SnapshotsCount = 1;

                        sourceDataInfo.RootNode.AddDirNode(subDir);
                    }
                    else
                    {
                        DMLibDataHelper.AddOneFileInBytes(subDirWithDot, fileName, 1024);
                        FileNode fileNode1 = subDirWithDot.GetFileNode(fileName);
                        fileNode1.SnapshotsCount = 1;
                    }
                }
                else
                {
                    DMLibDataHelper.AddOneFileInBytes(sourceDataInfo.RootNode, fileName, 1024);
                    FileNode fileNode1 = sourceDataInfo.RootNode.GetFileNode(fileName);
                    fileNode1.SnapshotsCount = 1;
                }
            }

            sourceDataInfo.RootNode.AddDirNode(subDirWithDot);

            var options = new TestExecutionOptions <DMLibDataInfo>();
            options.IsDirectoryTransfer = true;

            // transfer with IncludeSnapshots = true
            options.TransferItemModifier = (fileNode, transferItem) =>
            {
                dynamic dirOptions = DefaultTransferDirectoryOptions;
                dirOptions.Recursive        = true;
                dirOptions.IncludeSnapshots = true;
                transferItem.Options        = dirOptions;
            };

            var result = this.ExecuteTestCase(sourceDataInfo, options);

            // verify that snapshots are transferred
            Test.Assert(result.Exceptions.Count == 0, "Verify no exception is thrown.");
            Test.Assert(DMLibDataHelper.Equals(sourceDataInfo, result.DataInfo), "Verify transfer result.");
        }
コード例 #58
0
        private static void AddFolderForFile(Dictionary <FileNode, List <CommonFolderNode> > directoryPackages, FileNode rootFile, CommonFolderNode folderChild)
        {
            List <CommonFolderNode> folders;

            if (!directoryPackages.TryGetValue(rootFile, out folders))
            {
                directoryPackages[rootFile] = folders = new List <CommonFolderNode>();
            }
            folders.Add(folderChild);
        }
コード例 #59
0
        protected IEnumerable <FileProjectItem> AddExistingItems()
        {
            DirectoryNode node = ProjectBrowserPad.Instance.ProjectBrowserControl.SelectedDirectoryNode;

            if (node == null)
            {
                return(null);
            }
            node.Expanding();
            node.Expand();

            List <FileProjectItem> addedItems = new List <FileProjectItem>();

            using (OpenFileDialog fdiag = new OpenFileDialog()) {
                fdiag.AddExtension = true;
                var fileFilters = ProjectService.GetFileFilters();

                fdiag.InitialDirectory = node.Directory;
                fdiag.FilterIndex      = GetFileFilterIndex(node.Project, fileFilters);
                fdiag.Filter           = String.Join("|", fileFilters);
                fdiag.Multiselect      = true;
                fdiag.CheckFileExists  = true;
                fdiag.Title            = StringParser.Parse("${res:ProjectComponent.ContextMenu.AddExistingFiles}");

                if (fdiag.ShowDialog(SD.WinForms.MainWin32Window) == DialogResult.OK)
                {
                    List <KeyValuePair <string, string> > fileNames = new List <KeyValuePair <string, string> >(fdiag.FileNames.Length);
                    foreach (string fileName in fdiag.FileNames)
                    {
                        fileNames.Add(new KeyValuePair <string, string>(fileName, ""));
                    }
                    bool addedDependentFiles = false;
                    foreach (string fileName in fdiag.FileNames)
                    {
                        foreach (string additionalFile in FindAdditionalFiles(fileName))
                        {
                            if (!fileNames.Exists(delegate(KeyValuePair <string, string> pair) {
                                return(FileUtility.IsEqualFileName(pair.Key, additionalFile));
                            }))
                            {
                                addedDependentFiles = true;
                                fileNames.Add(new KeyValuePair <string, string>(additionalFile, Path.GetFileName(fileName)));
                            }
                        }
                    }



                    string copiedFileName = Path.Combine(node.Directory, Path.GetFileName(fileNames[0].Key));
                    if (!FileUtility.IsEqualFileName(fileNames[0].Key, copiedFileName))
                    {
                        int res = MessageService.ShowCustomDialog(
                            fdiag.Title, "${res:ProjectComponent.ContextMenu.AddExistingFiles.Question}",
                            0, 2,
                            "${res:ProjectComponent.ContextMenu.AddExistingFiles.Copy}",
                            "${res:ProjectComponent.ContextMenu.AddExistingFiles.Link}",
                            "${res:Global.CancelButtonText}");
                        if (res == 1)
                        {
                            // Link
                            foreach (KeyValuePair <string, string> pair in fileNames)
                            {
                                string          fileName        = pair.Key;
                                string          relFileName     = FileUtility.GetRelativePath(node.Project.Directory, fileName);
                                FileNode        fileNode        = new FileNode(fileName, FileNodeStatus.InProject);
                                FileProjectItem fileProjectItem = new FileProjectItem(node.Project, node.Project.GetDefaultItemType(fileName), relFileName);
                                fileProjectItem.SetEvaluatedMetadata("Link", Path.Combine(node.RelativePath, Path.GetFileName(fileName)));
                                fileProjectItem.DependentUpon = pair.Value;
                                addedItems.Add(fileProjectItem);
                                fileNode.ProjectItem = fileProjectItem;
                                fileNode.InsertSorted(node);
                                ProjectService.AddProjectItem(node.Project, fileProjectItem);
                            }
                            node.Project.Save();
                            if (addedDependentFiles)
                            {
                                node.RecreateSubNodes();
                            }
                            return(addedItems.AsReadOnly());
                        }
                        if (res == 2)
                        {
                            // Cancel
                            return(addedItems.AsReadOnly());
                        }
                        // only continue for res==0 (Copy)
                    }
                    bool replaceAll = false;
                    foreach (KeyValuePair <string, string> pair in fileNames)
                    {
                        copiedFileName = Path.Combine(node.Directory, Path.GetFileName(pair.Key));
                        if (!replaceAll && File.Exists(copiedFileName) && !FileUtility.IsEqualFileName(pair.Key, copiedFileName))
                        {
                            ReplaceExistingFile res = ShowReplaceExistingFileDialog(fdiag.Title, Path.GetFileName(pair.Key), true);
                            if (res == ReplaceExistingFile.YesToAll)
                            {
                                replaceAll = true;
                            }
                            else if (res == ReplaceExistingFile.No)
                            {
                                continue;
                            }
                            else if (res == ReplaceExistingFile.Cancel)
                            {
                                break;
                            }
                        }
                        FileProjectItem item = CopyFile(pair.Key, node, true);
                        if (item != null)
                        {
                            addedItems.Add(item);
                            item.DependentUpon = pair.Value;
                        }
                    }
                    node.Project.Save();
                    if (addedDependentFiles)
                    {
                        node.RecreateSubNodes();
                    }
                }
            }

            return(addedItems.AsReadOnly());
        }
コード例 #60
0
        private void removeMenu_Click(object sender, EventArgs e)
        {
            if (base.SelectedNode is FileNode)
            {
                FileNode     node   = (FileNode)base.SelectedNode;
                FileInfo     file   = node.GetFile();
                DialogResult result = MessageBox.Show(
                    String.Format(Language.GetString("DialogFileRemove"), file.Name),
                    Language.GetString("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    file.Delete();
                    node.Remove();
                }
            }
            else if (base.SelectedNode is DirectoryNode)
            {
                DirectoryNode node      = (DirectoryNode)base.SelectedNode;
                DirectoryInfo directory = node.GetDirectory();
                string        message;
                if (base.SelectedNode is ServerNode)
                {
                    message = String.Format(Language.GetString("DialogDirectoryRemove"), directory.Name);
                }
                else
                {
                    message = String.Format(Language.GetString("DialogServerRemove"), directory.Name);
                }
                DialogResult result = MessageBox.Show(message, Language.GetString("Warning"),
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    try
                    {
                        if (directory.Exists)
                        {
                            new Computer().FileSystem.DeleteDirectory(directory.FullName, UIOption.AllDialogs, RecycleOption.SendToRecycleBin);
                        }
                        if (base.SelectedNode is ServerNode && ((ServerNode)base.SelectedNode).GetServerData().isImported)
                        {
                            File.Delete(((ServerNode)base.SelectedNode).GetServerData().GetFile());
                        }
                        node.Destroy();
                    }
                    catch (OperationCanceledException) { }
                }
            }
            else if (base.SelectedNode is RemoteServerNode)
            {
                RemoteServerNode node   = (RemoteServerNode)base.SelectedNode;
                DialogResult     result = MessageBox.Show(
                    String.Format(Language.GetString("DialogRemoteServerRemove"), node.GetServerData().name),
                    Language.GetString("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (result == DialogResult.Yes)
                {
                    Directory.Delete(Main.RemoteDirectory + node.GetServerData().name, true);
                    node.Destroy();
                }
            }
            else if (base.SelectedNode is RemoteDirectoryNode)
            {
                RemoteDirectoryNode node = (RemoteDirectoryNode)base.SelectedNode;
                DialogResult        dr   = MessageBox.Show(
                    String.Format(Language.GetString("DialogDirectoryRemove"), node.Text),
                    Language.GetString("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                if (dr == DialogResult.Yes)
                {
                    Ftp.deleteDirectory(node.data, node.directory);
                    node.Destroy();
                }
            }
            else if (base.SelectedNode is RemoteFileNode)
            {
                RemoteFileNode node = (RemoteFileNode)base.SelectedNode;
                DialogResult   dr   = MessageBox.Show(
                    String.Format(Language.GetString("DialogFileRemove"), node.Text),
                    Language.GetString("Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                if (dr == DialogResult.Yes)
                {
                    Ftp.deleteFile(node.data, node.GetFile());
                    node.Remove();
                }
            }
        }