public void Should_Get_folders_by_parentID() { var folder = new Mock<IFolder>(); var folder2 = new Mock<IFolder>(); folder.SetupProperty(p => p.ID, (uint) 100); folder2.SetupProperty(p => p.ID, (uint) 101) .SetupProperty(p => p.ParentID, (uint) 100) .SetupProperty(p => p.ParentFolder, folder.Object ); var userInfo = Make_UserInfo(); var folderInfo = new FolderInfo(101, 1, null, new Guid("e9a9581d-1f51-4de2-844e-4088698da28b"), "folder name", new DateTime(2005, 05, 05), 1, 6); PortalRequest.SetupGet(p => p.User).Returns(userInfo); folder2.Setup(m => m.DoesUserOrGroupHavePermission(userInfo.Guid, new List<Guid>(), FolderPermission.Read)).Returns(true); folder.Setup(m => m.GetSubFolders()).Returns(new[] {folder2.Object}); PermissionManager.Setup(m => m.GetFolders(folder.Object.ID)).Returns(folder.Object); McmRepository.Setup(m => m.FolderInfoGet(new[] { folder2.Object.ID })).Returns(new[] { folderInfo }); var module = Make_FolderExtension(); var result = module.Get(null, null, 100, null).ToList(); Assert.AreEqual(1, result.Count); Assert.AreEqual(101, result[0].ID); }
/// <summary> /// This is a recursive method to display contents of a folder /// </summary> /// <param name="folderInfo"></param> /// <param name="pst"></param> private static void DisplayFolderContents(FolderInfo folderInfo, PersonalStorage pst) { // ExStart:GetMessageInformationDisplayFolderContents // Display the folder name Console.WriteLine("Folder: " + folderInfo.DisplayName); Console.WriteLine("=================================="); // Display information about messages inside this folder MessageInfoCollection messageInfoCollection = folderInfo.GetContents(); foreach (MessageInfo messageInfo in messageInfoCollection) { Console.WriteLine("Subject: " + messageInfo.Subject); Console.WriteLine("Sender: " + messageInfo.SenderRepresentativeName); Console.WriteLine("Recipients: " + messageInfo.DisplayTo); Console.WriteLine("------------------------------"); } // Call this method recursively for each subfolder if (folderInfo.HasSubFolders == true) { foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders()) { DisplayFolderContents(subfolderInfo, pst); } } // ExEnd:GetMessageInformationDisplayFolderContents }
/// <summary> /// This is a recursive method to display contents of a folder /// </summary> /// <param name="folderInfo"></param> /// <param name="pst"></param> private static void ExtractMsgFiles(FolderInfo folderInfo, PersonalStorage pst) { // ExStart:ExtractMessagesFromPSTFileExtractMsgFiles // display the folder name Console.WriteLine("Folder: " + folderInfo.DisplayName); Console.WriteLine("=================================="); // loop through all the messages in this folder MessageInfoCollection messageInfoCollection = folderInfo.GetContents(); foreach (MessageInfo messageInfo in messageInfoCollection) { Console.WriteLine("Saving message {0} ....", messageInfo.Subject); // get the message in MapiMessage instance MapiMessage message = pst.ExtractMessage(messageInfo); // save this message to disk in msg format message.Save(message.Subject.Replace(":", " ") + ".msg"); // save this message to stream in msg format MemoryStream messageStream = new MemoryStream(); message.Save(messageStream); } // Call this method recursively for each subfolder if (folderInfo.HasSubFolders == true) { foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders()) { ExtractMsgFiles(subfolderInfo, pst); } } // ExEnd:ExtractMessagesFromPSTFileExtractMsgFiles }
private string DirectoriesInformationToString(FolderInfo[] dirs) { string result = ""; foreach (FolderInfo dir in dirs) result += dir.ToString() + Environment.NewLine; return result; }
public FolderItemControl(FolderInfo info) { if (info == null) throw new ArgumentNullException("info"); m_Info = info; Text = info.Name; Icon = info.IsCustom ? UriResources.Images.FolderOpen16 : UriResources.Images.Folder16; }
// Walk the folder structure recursively private static void WalkFolders(FolderInfo folder, string parentFolderName, IList<string> folderData) { //ExStart:ParseSearchableFolders-WalkFolders string displayName = (string.IsNullOrEmpty(folder.DisplayName)) ? "ROOT" : folder.DisplayName; string folderNames = string.Format("DisplayName = {0}; Parent.DisplayName = {1}", displayName, parentFolderName); folderData.Add(folderNames); if (displayName == "Finder") { Console.WriteLine("Test this case"); } if (!folder.HasSubFolders) { return; } FolderInfoCollection coll = folder.GetSubFolders(FolderKind.Search | FolderKind.Normal); foreach (FolderInfo subfolder in coll) { WalkFolders(subfolder, displayName, folderData); } //ExEnd:ParseSearchableFolders-WalkFolders }
public virtual bool CanViewFolder(FolderInfo dnnFolder) { return(UserFolders.ContainsKey(dnnFolder.FolderPath)); }
void ScanFolder( FolderInfo folder, string path ) { try { //..record current location string s = MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ); status.scan.current = folder.Name + ":" + s; if( debug ) { Log( ".s.scan path [{0}]", s ); } Interlocked.Increment( ref status.scan.folders ); //..check if cancelled if( IsCancelRequested ) { throw new Exception( "Scan cancelled." ); } if( ! folder.IsIncludedFolder( path ) ) { if( debug ) { Log( " .s.not included" ); } return; } //..find out if folder path exists string fp = PathCombine( folder.Root, path ); if( debug ) { Log( ".s.folder path [{0}]", fp ); } try { #if __MonoCS__ { Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fp ); if( ! i.Exists || ! i.IsDirectory ) { return; } } #endif if( ! DirectoryExists( fp ) ) { throw new DirectoryNotFoundException( "Folder path does not exist." ); } //..find out if path exists in current string cp = PathCombine( current, folder.Name, path ); if( debug ) { Log( ".s.current path [{0}]", cp ); } try { if( ! DirectoryExists( cp ) ) { if( debug ) { Log( ".s.current path absent, copy everything" ); } //..when the folder does not exist in current, copy everything without comparing ScanQueue( ActionType.Copy, folder, path, null ); return; } List<string> a; //..scan files first if( debug ) { Log( ".s.-----> files [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } a = new List<string>( Ctrl.ListFiles( cp ) ); foreach( string n in Ctrl.ListFiles( fp ) ) { try { if( IsCancelRequested ) { throw new Exception( "Scan cancelled." ); } Interlocked.Increment( ref status.scan.files ); string pn = PathCombine( path, n ); if( debug ) { Log( ".s.file [{0}]", pn ); } if( folder.IsIncludedFile( pn ) ) { if( debug ) { Log( ".s.is included" ); } string fpn = PathCombine( fp, n ); try { #if __MonoCS__ Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fpn ); if( i.Exists && i.IsRegularFile ) #endif { string cpn = PathCombine( cp, n ); try { FileInfo fi = new FileInfo( fpn ); FileInfo ci = new FileInfo( cpn ); if( debug ) { Log( ".s.compare folder file [{0}]\n with current [{1}]", fpn, cpn ); } if( ! ci.Exists || ! ctrl.FileDateMatches( fi.LastWriteTimeUtc, ci.LastWriteTimeUtc ) || (fi.Length != ci.Length) ) { if( debug ) { Log( ".s.file has changed" ); } ScanQueue( ActionType.Copy, folder, path, n ); } ListFilenameRemove( a, n ); } catch( Exception ex ) { ex.Data[ExFolderFilename ] = fpn; ex.Data[ExCurrentFilename] = cpn; Log( "Scan {0}", Except.ToString( ex, debug ) ); Interlocked.Increment( ref status.update.skipped ); LogStatus( StatusType.Skipped, folder.Name, path, n ); } } } catch( Exception ex ) { ex.Data[ExFolderFilename] = fpn; throw; } } } catch( Exception ex ) { ex.Data[ExFilename] = n; throw; } } if( a.Count > 0 ) { if( debug ) { Log( ".s.flag deleted files for removal" ); } foreach( string n in a ) { if( debug ) { Log( ".s.deleted file [{0}]", n ); } ScanQueue( ActionType.Delete, folder, path, n ); } } //..scan folders second if( debug ) { Log( ".s.-----> directories [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } a = new List<string>( Ctrl.ListDirectories( cp ) ); foreach( string n in Ctrl.ListDirectories( fp ) ) { if( IsCancelRequested ) { throw new Exception( "Scan cancelled." ); } string pn = PathCombine( path, n ); if( debug ) { Log( ".s.directory [{0}]", pn ); } ScanFolder( folder, pn ); ListFilenameRemove( a, n ); } if( a.Count > 0 ) { if( debug ) { Log( ".s.flag deleted directories for removal" ); } foreach( string n in a ) { if( debug ) { Log( ".s.deleted directory [{0}]", n ); } ScanQueue( ActionType.Delete, folder, PathCombine( path, n ), null ); } } } catch( Exception ex ) { ex.Data[ExCurrentPath] = cp; throw; } } catch( Exception ex ) { ex.Data[ExFolderPath] = fp; throw; } } catch( Exception ex ) { ex.Data[ExPath] = path; Msg( "Scan: {0}", Except.ToString( ex, debug ) ); } }
private string ChooseFileMainMethod( string directory, bool _isFolderChooserDialog, bool _isSaveFileDialog, string _saveFileName, string fileFilterExtensionString, string windowTitle, ImVec2?windowSize, ImVec2?windowPos, float windowAlpha ) { //----------------------------------------------------------------------------- Internal I = _internal; string rv = I.chosenPath = ""; //----------------------------------------------------- bool isSelectFolderDialog = I.isSelectFolderDialog = _isFolderChooserDialog; bool isSaveFileDialog = I.isSaveFileDialog = _isSaveFileDialog; bool allowDirectoryCreation = I.allowDirectoryCreation = I.forbidDirectoryCreation ? false : (isSelectFolderDialog || isSaveFileDialog); //---------------------------------------------------------- //---------------------------------------------------------- ImGuiStyle style = ImGui.GetStyle(); ImVec4 dummyButtonColor = new ImVec4(0.0f, 0.0f, 0.0f, 0.5f); // Only the alpha is twickable from here // Fill ColorSet above and fix dummyButtonColor here { for (int i = 0, sz = (int)Internal.Color.ImGuiCol_Dialog_Directory_Text; i <= sz; i++) { ImVec4 r = style.GetColor(i < sz ? (ImGuiCol.Button + i) : ImGuiCol.Text); Internal.ColorCombine(ref ColorSet[i], r, df); } for (int i = (int)Internal.Color.ImGuiCol_Dialog_File_Background, sz = (int)Internal.Color.ImGuiCol_Dialog_File_Text; i <= sz; i++) { ImVec4 r = style.GetColor(i < sz ? (ImGuiCol.Button - (int)Internal.Color.ImGuiCol_Dialog_File_Background + i) : ImGuiCol.Text); Internal.ColorCombine(ref ColorSet[i], r, ff); } if (dummyButtonColor.w > 0) { ImVec4 bbc = style.GetColor(ImGuiCol.Button); dummyButtonColor.x = bbc.x; dummyButtonColor.y = bbc.y; dummyButtonColor.z = bbc.z; dummyButtonColor.w *= bbc.w; } } if (I.rescan) { string validDirectory = "."; if (directory != null && directory.Length > 0) { if (Directory.Exists(directory)) { validDirectory = directory; } else { validDirectory = Path.GetDirectoryName(directory); if (!Directory.Exists(validDirectory)) { validDirectory = "."; } } } I.currentFolder = Path.GetFullPath(validDirectory); I.editLocationCheckButtonPressed = false; I.history.reset(); // reset history I.history.switchTo(I.currentFolder); // init history I.dirs.Clear(); I.files.Clear(); I.dirNames.Clear(); I.fileNames.Clear(); I.currentSplitPath.Clear(); I.newDirectoryName = "New Folder"; if (_saveFileName != null) { //&I.saveFileName[0] = _saveFileName; I.saveFileName = Path.GetFileName(_saveFileName); // Better! } else { I.saveFileName = ""; } isSelectFolderDialog = _isFolderChooserDialog; isSaveFileDialog = _isSaveFileDialog; allowDirectoryCreation = I.forbidDirectoryCreation? false : (isSelectFolderDialog || isSaveFileDialog); if (isSelectFolderDialog && I.sortingMode > (int)Sorting.SORT_ORDER_LAST_MODIFICATION_INVERSE) { I.sortingMode = 0; } I.forceRescan = true; I.open = true; I.filter.Clear(); if (windowTitle == null || windowTitle.Length == 0) { if (isSelectFolderDialog) { I.wndTitle = "Please select a folder"; } else if (isSaveFileDialog) { I.wndTitle = "Please choose/create a file for saving"; } else { I.wndTitle = "Please choose a file"; } } else { I.wndTitle = windowTitle; } I.wndTitle += "##"; // char[] tmpWndTitleNumber = new char[12]; // ImFormatString(tmpWndTitleNumber,11,"%d", I.uniqueNumber); string tmpWndTitleNumber = I.uniqueNumber.ToString(); I.wndTitle += tmpWndTitleNumber; I.wndPos = windowPos ?? new ImVec2(); I.wndSize = windowSize ?? new ImVec2(); if (I.wndSize.x <= 0) { I.wndSize.x = 400; } if (I.wndSize.y <= 0) { I.wndSize.y = 400; } ImVec2 mousePos = ImGui.GetMousePos();// ImGui.GetCursorPos(); if (I.wndPos.x <= 0) { I.wndPos.x = mousePos.x - I.wndSize.x * 0.5f; } if (I.wndPos.y <= 0) { I.wndPos.y = mousePos.y - I.wndSize.y * 0.5f; } ImVec2 screenSize = ImGui.GetIO().DisplaySize; if (I.wndPos.x > screenSize.x - I.wndSize.x) { I.wndPos.x = screenSize.x - I.wndSize.x; } if (I.wndPos.y > screenSize.y - I.wndSize.y) { I.wndPos.y = screenSize.y - I.wndSize.y; } if (I.wndPos.x < 0) { I.wndPos.x = 0; } if (I.wndPos.y < 0) { I.wndPos.y = 0; } //fprintf(stderr,"screenSize = %f,%f mousePos = %f,%f wndPos = %f,%f wndSize = %f,%f\n",screenSize.x,screenSize.y,mousePos.x,mousePos.y,wndPos.x,wndPos.y,wndSize.x,wndSize.y); if (I.detectKnownDirectoriesAtEveryOpening) { pUserKnownDirectories = Directory_GetUserKnownDirectories(ref pUserKnownDirectoryDisplayNames, ref pNumberKnownUserDirectoriesExceptDrives, true); } } if (!I.open) { return(rv); } if (I.forceRescan) { I.forceRescan = false; int sortingModeForDirectories = (I.sortingMode <= (int)Sorting.SORT_ORDER_LAST_MODIFICATION_INVERSE) ? I.sortingMode : (I.sortingMode % 2); Directory_GetDirectories(I.currentFolder, ref I.dirs, ref I.dirNames, (Sorting)sortingModeForDirectories); // this is because directories don't return their size or their file extensions (so if needed we sort them alphabetically) //I.dirNames.resize(I.dirs.size());for (int i=0,sz=I.dirs.size();i<sz;i++) Path.GetFileName(I.dirs[i],(char*)I.dirNames[i]); if (!isSelectFolderDialog) { if (fileFilterExtensionString == null || fileFilterExtensionString.Length == 0) { Directory_GetFiles(I.currentFolder, ref I.files, ref I.fileNames, (Sorting)I.sortingMode); } else { Directory_GetFiles(I.currentFolder, ref I.files, fileFilterExtensionString, ref I.fileNames, (Sorting)I.sortingMode); } //I.fileNames.resize(I.files.size());for (int i=0,sz=I.files.size();i<sz;i++) Path.GetFileName(I.files[i],(char*)I.fileNames[i]); } else { I.files.Clear(); I.fileNames.Clear(); I.saveFileName = ""; string currentFolderName = Path.GetFileName(I.currentFolder); int currentFolderNameSize = currentFolderName.Length; if (currentFolderNameSize == 0 || currentFolderName[currentFolderNameSize - 1] == ':') { currentFolderName += "/"; } I.saveFileName += currentFolderName; } I.history.getCurrentSplitPath(ref I.currentSplitPath); const int approxNumEntriesPerColumn = 20;//(int) (20.f / browseSectionFontScale);// tweakable I.totalNumBrowsingEntries = (int)(I.dirs.Count + I.files.Count); I.numBrowsingColumns = I.totalNumBrowsingEntries / approxNumEntriesPerColumn; if (I.numBrowsingColumns <= 0) { I.numBrowsingColumns = 1; } if (I.totalNumBrowsingEntries % approxNumEntriesPerColumn > (approxNumEntriesPerColumn / 2)) { ++I.numBrowsingColumns; } if (I.numBrowsingColumns > 6) { I.numBrowsingColumns = 6; } I.numBrowsingEntriesPerColumn = I.totalNumBrowsingEntries / I.numBrowsingColumns; if (I.totalNumBrowsingEntries % I.numBrowsingColumns != 0) { ++I.numBrowsingEntriesPerColumn; } //# define DEBUG_HISTORY #if DEBUG_HISTORY if (I.history.getInfoSize() > 0) { fprintf(stderr, "\nHISTORY: currentFolder:\"%s\" history.canGoBack=%s history.canGoForward=%s currentHistory:\n", I.currentFolder, I.history.canGoBack()?"true":"false", I.history.canGoForward()?"true":"false"); } if (I.history.getCurrentFolderInfo()) { I.history.getCurrentFolderInfo()->display(); } #endif //DEBUG_HISTORY } if (I.rescan) { I.rescan = false; // Mandatory ImGui.Begin(I.wndTitle, ref I.open, I.wndSize, windowAlpha); ImGui.SetWindowPos(I.wndPos); ImGui.SetWindowSize(I.wndSize); //fprintf(stderr,"\"%s\" wndPos={%1.2f,%1.2f}\n",wndTitle.c_str(),wndPos.x,wndPos.y); } else { ImGui.Begin(I.wndTitle, ref I.open, new ImVec2(0, 0), windowAlpha); } ImGui.Separator(); //------------------------------------------------------------------------------------ // History (=buttons: < and >) { bool historyBackClicked = false; bool historyForwardClicked = false; // history ----------------------------------------------- ImGui.PushID("historyDirectoriesID"); bool historyCanGoBack = I.history.canGoBack(); bool historyCanGoForward = I.history.canGoForward(); if (!historyCanGoBack) { ImGui.PushStyleColor(ImGuiCol.Button, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonActive, dummyButtonColor); } historyBackClicked = ImGui.Button("<") & historyCanGoBack; ImGui.SameLine(); if (!historyCanGoBack) { ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); } if (!historyCanGoForward) { ImGui.PushStyleColor(ImGuiCol.Button, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonActive, dummyButtonColor); } historyForwardClicked = ImGui.Button(">") & historyCanGoForward; ImGui.SameLine(); if (!historyCanGoForward) { ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); } ImGui.PopID(); // ------------------------------------------------------- if (historyBackClicked || historyForwardClicked) { ImGui.End(); if (historyBackClicked) { I.history.goBack(); } else if (historyForwardClicked) { I.history.goForward(); } I.forceRescan = true; I.currentFolder = I.history.getCurrentFolder(); I.editLocationInputText = I.currentFolder; #if DEBUG_HISTORY if (historyBackClicked) { fprintf(stderr, "\nPressed BACK to\t"); } else { fprintf(stderr, "\nPressed FORWARD to\t"); } fprintf(stderr, "\"%s\" (%d)\n", I.currentFolder, (int)*I.history.getCurrentSplitPathIndex()); #undef DEBUG_HISTOTY #endif //DEBUG_HISTORY return(rv); } } //------------------------------------------------------------------------------------ // Edit Location CheckButton bool editLocationInputTextReturnPressed = false; { bool mustValidateInputPath = false; ImGui.PushStyleColor(ImGuiCol.Button, I.editLocationCheckButtonPressed? dummyButtonColor : style.GetColor(ImGuiCol.Button)); if (ImGui.Button("L##EditLocationCheckButton")) { I.editLocationCheckButtonPressed = !I.editLocationCheckButtonPressed; if (I.editLocationCheckButtonPressed) { I.editLocationInputText = I.currentFolder; ImGui.SetKeyboardFocusHere(); } //if (!I.editLocationCheckButtonPressed) mustValidateInputPath = true; // or not ? I mean: the user wants to quit or to validate in this case ? } ImGui.PopStyleColor(); if (I.editLocationCheckButtonPressed) { ImGui.SameLine(); Encoding.UTF8.GetBytes(I.editLocationInputText, 0, I.editLocationInputText.Length, tmpPathBytes, 0); editLocationInputTextReturnPressed = ImGui.InputText("##EditLocationInputText", tmpPathBytes, MaxPathBytes, ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.EnterReturnsTrue); I.editLocationInputText = Encoding.UTF8.GetString(tmpPathBytes); if (editLocationInputTextReturnPressed) { mustValidateInputPath = true; } else { ImGui.Separator(); } } if (mustValidateInputPath) { // it's better to clean the input path here from trailing slashes: StringBuilder cleanEnteredPathB = new StringBuilder(I.editLocationInputText); int len = cleanEnteredPathB.Length; while (len > 0 && (cleanEnteredPathB[len - 1] == '/' || cleanEnteredPathB[len - 1] == '\\')) { cleanEnteredPathB.Remove(len - 1, 1); len = cleanEnteredPathB.Length; } string cleanEnteredPath = cleanEnteredPathB.ToString(); if (len == 0 || I.currentFolder == cleanEnteredPath) { I.editLocationCheckButtonPressed = false; } else if (Directory.Exists(cleanEnteredPath)) { I.editLocationCheckButtonPressed = false; // Optional (return to split-path buttons) //---------------------------------------------------------------------------------- I.history.switchTo(cleanEnteredPath); I.currentFolder = cleanEnteredPath; I.forceRescan = true; } //else fprintf(stderr,"mustValidateInputPath NOOP: \"%s\" \"%s\"\n",I.currentFolder,cleanEnteredPath); } else { ImGui.SameLine(); } } //------------------------------------------------------------------------------------ // Split Path control if (!I.editLocationCheckButtonPressed && !editLocationInputTextReturnPressed) { bool mustSwitchSplitPath = false; FolderInfo fi = I.history.getCurrentFolderInfo(); ImVec2 framePadding = ImGui.GetStyle().FramePadding; float originalFramePaddingX = framePadding.x; framePadding.x = 0; // Split Path // Tab: { //----------------------------------------------------- // TAB LABELS //----------------------------------------------------- { int numTabs = (int)I.currentSplitPath.Count; int newSelectedTab = fi.splitPathIndex; for (int t = 0; t < numTabs; t++) { if (t > 0) { ImGui.SameLine(0, 0); } if (t == fi.splitPathIndex) { ImGui.PushStyleColor(ImGuiCol.Button, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, dummyButtonColor); ImGui.PushStyleColor(ImGuiCol.ButtonActive, dummyButtonColor); } ImGui.PushID(I.currentSplitPath[t]); bool pressed = ImGui.Button(I.currentSplitPath[t]); ImGui.PopID(); if (pressed) { if (fi.splitPathIndex != t && !mustSwitchSplitPath) { mustSwitchSplitPath = true; } newSelectedTab = t; } if (t == fi.splitPathIndex) { ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); } } if (mustSwitchSplitPath) { FolderInfo mfi = null; fi.getFolderInfoForSplitPathIndex(newSelectedTab, ref mfi); I.history.switchTo(mfi); I.forceRescan = true; I.currentFolder = I.history.getCurrentFolder(); I.editLocationInputText = I.currentFolder; //fprintf(stderr,"%s\n",I.currentFolder); } } } framePadding.x = originalFramePaddingX; } //------------------------------------------------------------------------------------ // Start collapsable regions---------------------------------------------------------- // User Known directories------------------------------------------------------------- if (I.allowKnownDirectoriesSection && pUserKnownDirectories.Count > 0) { ImGui.Separator(); if (ImGui.CollapsingHeader("Known Directories##UserKnownDirectories")) { ImGui.PushID(id); ImGui.PushStyleColor(ImGuiCol.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Text]); ImGui.PushStyleColor(ImGuiCol.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Background]); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Hover]); ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Pressed]); for (int i = 0, sz = (int)pUserKnownDirectories.Count; i < sz; i++) { string userKnownFolder = pUserKnownDirectories[i]; string userKnownFolderDisplayName = pUserKnownDirectoryDisplayNames[i]; if (ImGui.SmallButton(userKnownFolderDisplayName) && userKnownFolder != I.currentFolder) { I.currentFolder = userKnownFolder; I.editLocationInputText = I.currentFolder; I.history.switchTo(I.currentFolder); I.forceRescan = true; //------------------------------------------------------------------------------------------------------------------------------ } if (i != sz - 1 && (i >= pNumberKnownUserDirectoriesExceptDrives || i % 7 != 6)) { ImGui.SameLine(); } } ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopID(); } } // End User Known directories--------------------------------------------------------- // Allow directory creation ---------------------------------------------------------- if (allowDirectoryCreation) { ImGui.Separator(); bool mustCreate = false; if (ImGui.CollapsingHeader("New Directory##allowDirectoryCreation")) { ImGui.PushID(id); Encoding.UTF8.GetBytes(I.newDirectoryName, 0, I.newDirectoryName.Length, tmpPathBytes, 0); ImGui.InputText("##createNewFolderName", tmpPathBytes, MaxFilenameBytes); I.newDirectoryName = Encoding.UTF8.GetString(tmpPathBytes); ImGui.SameLine(); mustCreate = ImGui.Button("CREATE"); ImGui.PopID(); } if (mustCreate && I.newDirectoryName.Length > 0) { string newDirPath = Path.Combine(I.currentFolder, I.newDirectoryName); if (!Directory.Exists(newDirPath)) { //# define SIMULATING_ONLY #if SIMULATING_ONLY fprintf(stderr, "creating: \"%s\"\n", newDirPath); #undef SIMULATING_ONLY #else //SIMULATING_ONLY Directory.CreateDirectory(newDirPath); if (!Directory.Exists(newDirPath)) { Console.Error.WriteLine("Error creating new folder: \"{0}\"\n", newDirPath); } else { I.forceRescan = true; // Just update } #endif //SIMULATING_ONLY } } } // End allow directory creation ------------------------------------------------------ // Filtering entries ----------------------------------------------------------------- if (I.allowFiltering) { ImGui.Separator(); if (ImGui.CollapsingHeader("Filtering##fileNameFiltering")) { ImGui.PushID(id); I.filter.Draw(); ImGui.PopID(); } } // End filtering entries ------------------------------------------------------------- // End collapsable regions------------------------------------------------------------ // Selection field ------------------------------------------------------------------- if (isSaveFileDialog || isSelectFolderDialog) { ImGui.Separator(); bool selectionButtonPressed = false; ImGui.PushID(id); if (isSaveFileDialog) { ImGui.AlignFirstTextHeightToWidgets(); ImGui.Text("File:"); ImGui.SameLine(); Encoding.UTF8.GetBytes(I.saveFileName, 0, I.saveFileName.Length, tmpPathBytes, 0); ImGui.InputText("##saveFileName", tmpPathBytes, MaxFilenameBytes); I.saveFileName = Encoding.UTF8.GetString(tmpPathBytes); ImGui.SameLine(); } else { ImGui.AlignFirstTextHeightToWidgets(); ImGui.Text("Folder:"); ImGui.SameLine(); ImVec4 r = style.GetColor(ImGuiCol.Text); Internal.ColorCombine(ref ColorSet[(int)Internal.Color.ImGuiCol_Dialog_SelectedFolder_Text], r, sf); ImGui.TextColored(ColorSet[(int)Internal.Color.ImGuiCol_Dialog_SelectedFolder_Text], I.saveFileName); ImGui.SameLine(); } if (isSelectFolderDialog) { selectionButtonPressed = ImGui.Button("Select"); } else { selectionButtonPressed = ImGui.Button("Save"); } ImGui.PopID(); if (selectionButtonPressed) { if (isSelectFolderDialog) { rv = I.currentFolder; I.open = true; } else if (isSaveFileDialog) { if (I.saveFileName.Length > 0) { bool pathOk = true; if (I.mustFilterSaveFilePathWithFileFilterExtensionString && fileFilterExtensionString != null && fileFilterExtensionString.Length > 0) { pathOk = false; string saveFileNameExtension = Path.GetExtension(I.saveFileName); bool saveFileNameHasExtension = saveFileNameExtension.Length > 0; //------------------------------------------------------------------- string[] wExts = fileFilterExtensionString.Split(';'); int wExtsSize = wExts.Length; if (!saveFileNameHasExtension) { if (wExtsSize == 0) { pathOk = true; // Bad situation, better allow this case } else { I.saveFileName += wExts[0]; } } else { // saveFileNameHasExtension for (int i = 0; i < wExtsSize; i++) { string ext = wExts[i]; if (ext == saveFileNameExtension) { pathOk = true; break; } } if (!pathOk && wExtsSize > 0) { I.saveFileName += wExts[0]; } } } if (pathOk) { string savePath = Path.Combine(I.currentFolder, I.saveFileName); rv = savePath; I.open = true; } } } } //ImGui.Spacing(); } // End selection field---------------------------------------------------------------- ImGui.Separator(); // sorting -------------------------------------------------------------------- ImGui.Text("Sorting by: "); ImGui.SameLine(); { int oldSortingMode = I.sortingMode; int oldSelectedTab = I.sortingMode / 2; //----------------------------------------------------- // TAB LABELS //----------------------------------------------------- { int newSortingMode = oldSortingMode; int numUsedTabs = isSelectFolderDialog ? 2 : numTabs; for (int t = 0; t < numUsedTabs; t++) { if (t > 0) { ImGui.SameLine(); } if (t == oldSelectedTab) { ImGui.PushStyleColor(ImGuiCol.Button, dummyButtonColor); } ImGui.PushID(names[t]); bool pressed = ImGui.SmallButton(names[t]); ImGui.PopID(); if (pressed) { if (oldSelectedTab == t) { newSortingMode = oldSortingMode; if (newSortingMode % 2 == 0) { ++newSortingMode; // 0,2,4 } else { --newSortingMode; } } else { newSortingMode = t * 2; } } if (t == oldSelectedTab) { ImGui.PopStyleColor(); } } if (newSortingMode != oldSortingMode) { I.sortingMode = newSortingMode; //printf("sortingMode = %d\n",sortingMode); I.forceRescan = true; } //-- Browsing per row ----------------------------------- if (I.allowDisplayByOption && I.numBrowsingColumns > 1) { ImGui.SameLine(); ImGui.Text(" Display by:"); ImGui.SameLine(); ImGui.PushStyleColor(ImGuiCol.Button, dummyButtonColor); if (ImGui.SmallButton(!Internal.BrowsingPerRow? "Column##browsingPerRow" : "Row##browsingPerRow")) { Internal.BrowsingPerRow = !Internal.BrowsingPerRow; } ImGui.PopStyleColor(); } //-- End browsing per row ------------------------------- } } //----------------------------------------------------------------------------- ImGui.Separator(); //----------------------------------------------------------------------------- // MAIN BROWSING FRAME: //----------------------------------------------------------------------------- { ImGui.BeginChild("BrowsingFrame"); // ImGui.SetScrollPosHere(); // possible future ref: while drawing to place the scroll bar ImGui.Columns(I.numBrowsingColumns); ImGui.PushID(id); int cntEntries = 0; // Directories -------------------------------------------------------------- if (I.dirs.Count > 0) { ImGui.PushStyleColor(ImGuiCol.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Text]); ImGui.PushStyleColor(ImGuiCol.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Background]); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Hover]); ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Pressed]); for (int i = 0, sz = (int)I.dirs.Count; i < sz; i++) { string dirName = I.dirNames[i]; if (I.filter.PassFilter(dirName)) { if (ImGui.SmallButton(dirName)) { I.currentFolder = I.dirs[i]; I.editLocationInputText = I.currentFolder; I.history.switchTo(I.currentFolder); I.forceRescan = true; //------------------------------------------------------------------------------------------------------------------------------ } ++cntEntries; if (Internal.BrowsingPerRow) { ImGui.NextColumn(); } else if (cntEntries == I.numBrowsingEntriesPerColumn) { cntEntries = 0; ImGui.NextColumn(); } } } ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); } // Files ---------------------------------------------------------------------- if (!isSelectFolderDialog && I.files.Count > 0) { ImGui.PushStyleColor(ImGuiCol.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Text]); ImGui.PushStyleColor(ImGuiCol.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Background]); ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Hover]); ImGui.PushStyleColor(ImGuiCol.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Pressed]); for (int i = 0, sz = (int)I.files.Count; i < sz; i++) { string fileName = I.fileNames[i]; if (I.filter.PassFilter(fileName)) { if (ImGui.SmallButton(fileName)) { if (!isSaveFileDialog) { rv = I.files[i]; I.open = true; } else { I.saveFileName = Path.GetFileName(I.files[i]); } } ++cntEntries; if (Internal.BrowsingPerRow) { ImGui.NextColumn(); } else if (cntEntries == I.numBrowsingEntriesPerColumn) { cntEntries = 0; ImGui.NextColumn(); } } } ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); ImGui.PopStyleColor(); } //----------------------------------------------------------------------------- ImGui.PopID(); ImGui.EndChild(); } //----------------------------------------------------------------------------- ImGui.End(); return(rv); }
/// <summary> /// Returns a flag indicating whether the current user can manage a folder's settings /// </summary> /// <param name="folder">The page</param> /// <returns>A flag indicating whether the user has permission</returns> public virtual bool CanManageFolder(FolderInfo folder) { return(HasFolderPermission(folder, ManageFolderPermissionKey)); }
public bool isEqual(FolderInfo fi) { return(fullFolder == fi.fullFolder && currentFolder == fi.currentFolder); }
public UpdateRequest( ActionType action, FolderInfo folder, string path, string filename ) { this.action = action; this.folder = folder; this.path = path; this.filename = filename; }
void RecursiveCopy( FolderInfo folder, string path ) { try { string s = folder.Name + ":" + MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ); status.update.current = s; if( debug ) { Log( ".u.recursive copy [{0}]", s ); } //..check if cancelled if( IsCancelRequested ) { throw new Exception( "Update cancelled." ); } if( ! folder.IsIncludedFolder( path ) ) { if( debug ) { Log( ".u.not included", path ); } return; } string fp = PathCombine( folder.Root, path ); if( debug ) { Log( ".u.folder path [{0}]", fp ); } try { #if __MonoCS__ { Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fp ); if( ! i.Exists || ! i.IsDirectory ) { return; } } #endif if( ! DirectoryExists( fp ) ) { throw new Exception( "Folder path does not exist." ); } string cp = PathCombine( current, folder.Name, path ); if( debug ) { Log( ".u.current path [{0}]", cp ); } try { if( debug ) { Log( ".u.create current directory" ); } DirectoryCreate( cp ); //..copy all included files at this level if( debug ) { Log( ".u.-----> files [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } foreach( string n in Ctrl.ListFiles( fp ) ) { try { status.update.current = folder.Name + ":" + MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) + n; if( IsCancelRequested ) { throw new Exception( "Update cancelled." ); } string pn = PathCombine( path, n ); if( debug ) { Log( ".u.file [{0}]", pn ); } if( folder.IsIncludedFile( pn ) ) { if( debug ) { Log( ".u.is included" ); } string fpn = PathCombine( fp, n ); try { #if __MonoCS__ Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( fpn ); if( i.Exists && i.IsRegularFile ) #endif { string cpn = PathCombine( cp, n ); try { if( debug ) { Log( ".u.copy folder file to current" ); } FileCopy( fpn, cpn ); LogStatus( StatusType.Created, folder.Name, path, n ); Interlocked.Increment( ref status.update.created ); } catch( Exception ex ) { ex.Data[ExCurrentFilename] = cpn; Log( "Update {0}", Except.ToString( ex, debug ) ); Interlocked.Increment( ref status.update.skipped ); LogStatus( StatusType.Skipped, folder.Name, path, n ); } } } catch( Exception ex ) { ex.Data[ExFolderFilename] = fpn; throw; } } } catch( Exception ex ) { ex.Data[ExFilename] = n; throw; } } //..recursively copy all subdirectories at this level if( debug ) { Log( ".u.-----> directories [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } foreach( string n in Ctrl.ListDirectories( fp ) ) { string pn = PathCombine( path, n ); if( debug ) { Log( ".u.directory [{0}]", pn ); } RecursiveCopy( folder, pn ); } } catch( Exception ex ) { ex.Data[ExCurrentPath] = cp; throw; } } catch( Exception ex ) { ex.Data[ExFolderPath] = fp; throw; } } catch( Exception ex ) { ex.Data[ExPath] = path; Msg( "Update: {0}", Except.ToString( ex, debug ) ); } }
public override void AddFolder(FolderInfo objFolderInfo) { FolderManager.Instance.AddFolder(FolderMappingController.Instance.GetFolderMapping(objFolderInfo.PortalID, objFolderInfo.FolderMappingID), objFolderInfo.FolderPath); }
private async Task SaveDirectoriesChangesAsync(FolderInfo[] dirs) { // // All Directories in String form. string strDirectories = DirectoriesInformationToString(dirs); // // Save Directory Information's await Transaction.TransformPhysicalDisk.SecureDataSaverAsync(strDirectories, StorePath, Password); }
public override void Execute() { foreach (SiteCollInfo siteCollInfo in Owner.WorkingSiteCollections) { using (var siteColl = Owner.ObjectsFactory.GetSite(siteCollInfo.URL)) { foreach (SiteInfo siteInfo in siteCollInfo.Sites) { using (var web = siteColl.OpenWeb(siteInfo.ID)) { foreach (ListInfo listInfo in siteInfo.Lists) { if (listInfo.isLib) { for (int counter = 1; counter <= WorkingDefinition.MaxNumberOfFoldersToGenerate; counter++) { try { Log.Write("Creating folders in '" + web.Url + "/" + listInfo.Name); var list = web.GetList(listInfo.Name); string folderName = findAvailableFolderName(list); var folder = list.RootFolder.AddFolder(folderName); folder.Update(); FolderInfo folderInfo = new FolderInfo(); folderInfo.Name = folderName; folderInfo.URL = folder.Url; listInfo.Folders.Add(folderInfo); Owner.IncrementCurrentTaskProgress("Folder created '" + folderInfo.Name + "'"); for (int l = 0; l < WorkingDefinition.MaxNumberOfNestedFolderLevelPerLibrary; l++) { counter++; if (counter >= WorkingDefinition.MaxNumberOfFoldersToGenerate) { break; } folderName = findAvailableFolderName(list); folder = folder.AddFolder(folderName); //folder.Name = "Folder" + folderNumber; folder.Update(); FolderInfo folderInfo2 = new FolderInfo(); folderInfo2.Name = folderName; folderInfo2.URL = folder.Url; listInfo.Folders.Add(folderInfo2); Owner.IncrementCurrentTaskProgress("Folder created '" + folderInfo2.Name + "'"); } } catch (Exception ex) { Errors.Log(ex); } } } } } } } } }
private FolderInfo GetFolderInfo(DataFileInfo info) { if (_folders.ContainsKey(info.ParentName)) return _folders[info.ParentName]; else { // make new folder info var folder = new FolderInfo(info.ParentName); _folders[info.ParentName] = folder; if (info.ParentName.Contains("\\")) { // add folder to its parent subfolder var folderParentName = info.ParentName.Substring(0, info.ParentName.LastIndexOf("\\", System.StringComparison.Ordinal)); if (_folders.ContainsKey(folderParentName)) { var parent = _folders[folderParentName]; parent.SubFolder.Add(folder); } } return folder; } }
private string GenerateClass(FolderInfo folder, bool isStatic, int indentLevel) { var indent = ""; for (int i = 0; i < indentLevel; i++) { indent += "\t"; } var attribs = indent + "public " + (isStatic? "static " : ""); _text.Append(attribs); _text.Append("class "); _text.Append(folder.Name + "\n"); _text.Append(indent + "{\n"); // generate sub classes foreach (var subfolder in folder.SubFolder) { GenerateClass(subfolder, true, indentLevel + 1); } // generate properties var files = folder.Files; foreach (var file in files) { var length = file.PropertyName.LastIndexOf('.'); var propName = file.PropertyName.Substring(0, 1).ToUpper() + file.PropertyName.Substring(0, length).Substring(1); _text.Append(indent + "\tpublic static " + file.ExtensionInfo.ReturnType + " "); _text.Append(propName); _text.Append(" { get { return " + file.ExtensionInfo.Method + "(@\""); _text.Append(file.ExtensionInfo.UseExtension ? file.RelativePath : file.RelativePath.Replace(file.ExtensionInfo.Extension, "")); _text.Append("\"); } }\n"); } _text.Append(indent + "}\n"); _text.Append("\n"); // mark class as generated _generatedClasses.Add(folder.FullName); return _text.ToString(); }
/// <summary> /// Returns a flag indicating whether the current user can manage a folder's settings /// </summary> /// <param name="folder">The page</param> /// <returns>A flag indicating whether the user has permission</returns> public static bool CanManageFolder(FolderInfo folder) { return(provider.CanManageFolder(folder)); }
public void Should_Create_Sub_Folder() { var folder = new Mock<IFolder>().SetupProperty(p => p.ID, (uint)100); var userInfo = Make_UserInfo(); var folderInfo = new FolderInfo { ID = 1001 }; var module = Make_FolderExtension(); PermissionManager.Setup(m => m.GetFolders(folder.Object.ID)).Returns(folder.Object); folder.Setup(m => m.DoesUserOrGroupHavePermission(userInfo.Guid, new Guid[0], FolderPermission.Write)).Returns(true); McmRepository.Setup(m => m.FolderCreate(userInfo.Guid, null, "name", 100, 1)).Returns(folderInfo.ID); McmRepository.Setup(m => m.FolderInfoGet(new[] { folderInfo.ID })).Returns(new[] { folderInfo }); PortalRequest.SetupGet(p => p.User).Returns(userInfo); var result = module.Create(null, "name", 100, 1); Assert.AreEqual(1001, result.ID); }
/// <summary> /// SaveFolderPermissions updates a Folder's permissions /// </summary> /// <param name="folder">The Folder to update</param> public virtual void SaveFolderPermissions(FolderInfo folder) { SaveFolderPermissions((IFolderInfo)folder); }
void ScanQueue( ActionType action, FolderInfo folder, string path, string filename ) { queue.Add( new UpdateRequest( action, folder, path, filename ), cancel.Token ); }
public override FileInfo GetFile(FolderInfo objfolderInfo, string filename) { return((FileInfo)FileManager.Instance.GetFile(objfolderInfo, filename)); }
public void MakeSureYouReadSameStuffFromTwoStreamsLinkingToTheSameFile() { VirtualFileSystem fileSystem = VirtualFileSystemFactory.CreateDefaultFileSystem(); FolderInfo folder1Node = fileSystem.CreateFolder(@"\folder1"); FileInfo newFile = fileSystem.CreateFile(@"\folder1\file1"); var relativelyInterestingData = new List <byte>(); for (int i = 0; i < 1000; i++) { relativelyInterestingData.AddRange(Guid.NewGuid().ToByteArray()); } using (DataStreamReadableWritable dataStream = fileSystem.OpenFileForWriting(newFile.FullPath)) { dataStream.Write(relativelyInterestingData.ToArray(), 0, relativelyInterestingData.Count); } DataStreamReadable dataStream1 = fileSystem.OpenFileForReading(newFile.FullPath); DataStreamReadable dataStream2 = fileSystem.OpenFileForReading(newFile.FullPath); Exception anyThreadException = null; var bytesReadByThreadOne = new List <byte>(); var thread1 = new Thread(delegate() { try { var buffer = new byte[1]; while (dataStream1.Read(buffer, 0, 1) == 1) { bytesReadByThreadOne.Add(buffer[0]); } } catch (Exception exception) { anyThreadException = new InvalidOperationException("", exception); } }); var bytesReadByThreadTwo = new List <byte>(); var thread2 = new Thread(delegate() { try { while (dataStream2.Position != dataStream2.Length) { var buffer = new byte[1]; dataStream2.Read(buffer, 0, 1); bytesReadByThreadTwo.Add(buffer[0]); } } catch (Exception exception) { anyThreadException = new InvalidOperationException("Возникло исключение в одном из тестовых потоков. Детали и стэк вызова - в обернутом исключении.", exception); } }); thread1.Start(); thread2.Start(); thread2.Join(); thread1.Join(); if (anyThreadException != null) { throw anyThreadException; } CollectionAssert.AreEqual(relativelyInterestingData, bytesReadByThreadOne); CollectionAssert.AreEqual(relativelyInterestingData, bytesReadByThreadTwo); }
void Scan( CtrlFolder folder ) { try { FolderInfo f = new FolderInfo( folder, ctrl.IsCaseSensitive ); Log( string.Empty ); Msg( "Folder: {0} : {1}", f.Name, f.Root ); if( string.IsNullOrEmpty( f.Name ) ) { throw new Exception( "Folder name is empty." ); } if( f.Name.IndexOfAny( InvalidFilenameCharacters ) >= 0 ) { throw new Exception( "Folder name contains invalid characters." ); } if( string.IsNullOrEmpty( f.Root ) ) { throw new Exception( "Folder path is empty." ); } if( f.Root.IndexOfAny( InvalidPathCharacters ) >= 0 ) { throw new Exception( "Folder path contains invalid characters." ); } ScanFolder( f, string.Empty ); } catch( Exception ex ) { ex.Data[ExArchiveRoot] = ctrl.Path; ex.Data[ExCurrentRoot] = current; ex.Data[ExHistoryRoot] = history; ex.Data[ExFolderName] = folder.Name; ex.Data[ExFolderRoot] = folder.Path; throw; } }
private void Process(FolderInfo folderInfo) { folderInfo.Files.AsParallel().ForAll(f => { ProcessFile(folderInfo, f); }); }
public void set(FolderInfo o) { currentFolder = o.currentFolder; fullFolder = o.fullFolder; splitPathIndex = o.splitPathIndex; }
internal FolderFullException(FolderInfo fi) : base($"Folderinfo[id:{fi.Id}] is full!") { }
/// <summary> /// Returns a flag indicating whether the current user can delete a folder or file /// </summary> /// <param name="folder">The page</param> /// <returns>A flag indicating whether the user has permission</returns> public virtual bool CanDeleteFolder(FolderInfo folder) { return(HasFolderPermission(folder, DeleteFolderPermissionKey)); }
protected void Save_OnClick(object sender, EventArgs e) { try { if (FolderList.Items.Count == 0) { return; } DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current; string fileContents = htmlText2.Text.Trim(); string newFileName = FileName.Text; if (!(newFileName.EndsWith(".html"))) { newFileName = newFileName + ".html"; } string rootFolder = portalSettings.HomeDirectoryMapPath; string dbFolderPath = FolderList.SelectedValue; string virtualFolder = (string)(string)FileSystemValidation.ToVirtualPath(dbFolderPath); rootFolder = rootFolder + FolderList.SelectedValue; rootFolder = rootFolder.Replace("/", "\\"); string errorMessage = string.Empty; FolderController folderCtrl = new FolderController(); FolderInfo folder = folderCtrl.GetFolder(portalSettings.PortalId, dbFolderPath, false); if ((folder == null)) { ShowSaveTemplateMessage(GetString("msgFolderDoesNotExist.Text")); return; } // Check file name is valid FileSystemValidation dnnValidator = new FileSystemValidation(); errorMessage = dnnValidator.OnCreateFile(virtualFolder + newFileName, fileContents.Length); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } FileController fileCtrl = new FileController(); DotNetNuke.Services.FileSystem.FileInfo existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); // error if file exists if (!Overwrite.Checked && existingFile != null) { ShowSaveTemplateMessage(GetString("msgFileExists.Text")); return; } FileInfo newFile = existingFile; if ((newFile == null)) { newFile = new FileInfo(); } newFile.FileName = newFileName; newFile.ContentType = "text/plain"; newFile.Extension = "html"; newFile.Size = fileContents.Length; newFile.FolderId = folder.FolderID; errorMessage = FileSystemUtils.CreateFileFromString(rootFolder, newFile.FileName, fileContents, newFile.ContentType, string.Empty, false); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); if (newFile.FileId != existingFile.FileId) { newFile.FileId = existingFile.FileId; } if (newFile.FileId != Null.NullInteger) { fileCtrl.UpdateFile(newFile.FileId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID); } else { fileCtrl.AddFile(portalSettings.PortalId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID, true); } ShowSaveTemplateMessage(string.Empty); } catch (Exception ex) { DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); throw ex; } }
/// <summary> /// Returns a flag indicating whether the current user can view a folder or file /// </summary> /// <param name="folder">The page</param> /// <returns>A flag indicating whether the user has permission</returns> public virtual bool CanViewFolder(FolderInfo folder) { return(HasFolderPermission(folder, ViewFolderPermissionKey)); }
private void LockFolderCommandExecute(FolderInfo folderInfo) { if (!VersionHelper.CheckPaidFeature()) { return; } bool isLocking = false; string title = string.Empty; if (string.IsNullOrEmpty(folderInfo.Passcode)) { isLocking = false; title = ResourceLoader.GetForCurrentView().GetString("Message/Confirm/Create/Password"); } else { isLocking = true; title = ResourceLoader.GetForCurrentView().GetString("Message/Confirm/Remove/Password"); } StackPanel contentPanel = new StackPanel(); contentPanel.Children.Add(new TextBlock { Text = title, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 12, 0, 12) }); PasswordBox pbox = new PasswordBox { MaxLength = 8, Margin = new Thickness(0, 12, 0, 12) }; contentPanel.Children.Add(pbox); ContentDialog contentDlg = new ContentDialog { Content = contentPanel, IsPrimaryButtonEnabled = false, PrimaryButtonText = ResourceLoader.GetForCurrentView().GetString("Ok"), SecondaryButtonText = ResourceLoader.GetForCurrentView().GetString("Cancel") }; pbox.PasswordChanged += (sender, args) => { if (isLocking) { contentDlg.IsPrimaryButtonEnabled = folderInfo.Passcode == pbox.Password; } else { contentDlg.IsPrimaryButtonEnabled = !string.IsNullOrEmpty(pbox.Password); } }; //메세지 창 출력 App.ContentDlgOp = contentDlg.ShowAsync(); //후처리기 등록 App.ContentDlgOp.Completed = new AsyncOperationCompletedHandler <ContentDialogResult>(async(op, status) => { var result = await op; if (result == ContentDialogResult.Primary) { if (isLocking) { if (folderInfo.Passcode == pbox.Password) { //잠금 해제 folderInfo.Passcode = string.Empty; folderDAO.Update(folderInfo); //전체 비디오에서 추가 요청 MessengerInstance.Send <Message>(new Message("FolderAdded", folderInfo), AllVideoViewModel.NAME); } } else { if (!string.IsNullOrEmpty(pbox.Password)) { //잠금 설정 folderInfo.Passcode = pbox.Password; folderDAO.Update(folderInfo); //전체 비디오에서 삭제 요청 MessengerInstance.Send <Message>(new Message("FolderDeleted", folderInfo), AllVideoViewModel.NAME); //재생 목록에서 삭제 요청 MessengerInstance.Send <Message>(new Message("FolderDeleted", folderInfo), PlaylistViewModel.NAME); } } } App.ContentDlgOp = null; }); }
/// <summary> /// Get children folders of the specified parent. /// </summary> /// <param name="parent">Parent folder</param> /// <param name="isRoot">True if it's the root folder</param> /// <returns>List of folder</returns> private IEnumerable <FolderDTO> GetChildrenFolder(IFolderInfo parent, bool isRoot) { List <FolderDTO> children = null; if (parent.HasChildren) { children = new List <FolderDTO>(); IEnumerable <IFolderInfo> folders = FolderManager.Instance.GetFolders(parent); foreach (IFolderInfo folder in folders) { FolderInfo current = folder as FolderInfo; if (FolderPermissionController.CanBrowseFolder(current)) { if (current.IsProtected || current.FolderPath == "Cache/") { continue; } if (current.FolderPath == "Users/" && !IsAdmin) { continue; } FolderDTO child = new FolderDTO { Label = current.FolderName, Data = new FolderDataDTO { Path = current.FolderPath, CanManage = FolderPermissionController.CanManageFolder(current) }, Leaf = !current.HasChildren, Children = current.HasChildren ? new List <FolderDTO>() : null }; children.Add(child); } } if (isRoot) { // Add personal folder at the end for not admin users if (!IsAdmin) { DocumentSettings settings = new DocumentSettings(ActiveModule); if (settings.UserFolder) { FolderInfo userFolder = FolderManager.Instance.GetUserFolder(UserInfo) as FolderInfo; FolderDTO userChild = new FolderDTO { Label = LocalizeString("UserFolder"), Data = new FolderDataDTO { Path = userFolder.FolderPath, CanManage = FolderPermissionController.CanManageFolder(userFolder) }, Leaf = !userFolder.HasChildren, Children = userFolder.HasChildren ? new List <FolderDTO>() : null }; children.Add(userChild); } } List <FolderDTO> rootFolders = new List <FolderDTO>(); FolderDTO root = new FolderDTO { Label = LocalizeString("RootFolder"), Data = new FolderDataDTO { Path = "", CanManage = FolderPermissionController.CanManageFolder(parent as FolderInfo) }, Leaf = children.Count == 0, Expanded = true, Children = children }; rootFolders.Add(root); return(rootFolders); } } return(children); }
private async void LoadRootFolders() { try { //폴더 추가 버튼 await DispatcherHelper.RunAsync(async() => { if (ExplorerFolderSource.Count > 0) { ExplorerFolderSource.Clear(); } if (ExplorerFileSource.Count > 0) { ExplorerFileSource.Clear(); } //탐색기 루트를 로드 folderDAO.LoadRootFolderList(ExplorerFolderSource, LockFolderCommand, RemoveFolderCommand, true); ExplorerFolderSource.Add(new FolderInfo() { Name = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView().GetString("AddFolder"), Glyph1 = "\xE109", // Type = FolderType.Picker, IsHighlight = ExplorerFolderSource.Count == 0, Level = 1 }); ///////////////////////////// 윈10 10549 버그 Workaround////////////////////////////////// if (VersionHelper.WindowsVersion == 10 && !ExplorerFolderSource.Any(x => x.Type != FolderType.Picker)) { List <StorageFolder> folders = new List <StorageFolder>(); folders.Add(KnownFolders.VideosLibrary); var external = await KnownFolders.RemovableDevices.GetFoldersAsync(); if (external != null && external.Any()) { folders.AddRange(external); } foreach (var folder in folders) { bool found = false; //중복된 폴더는 추가하지 않음 foreach (var added in ExplorerFolderSource) { var sf = await added.GetStorageFolder(true); if (sf != null && sf.FolderRelativeId == folder.FolderRelativeId) { found = true; break; } } if (!found) { //전체 비디오에 반영 var folderInfo = new FolderInfo(folder) { Level = 1, Type = FolderType.Root, ButtonTappedCommand1 = LockFolderCommand, ButtonTappedCommand2 = RemoveFolderCommand, Passcode = string.Empty }; //선택한 폴더 DB등록 folderDAO.Insert(folderInfo); var addFolder = ExplorerFolderSource.FirstOrDefault(x => x.Type == FolderType.Picker); addFolder.IsHighlight = false; var index = ExplorerFolderSource.IndexOf(addFolder); ExplorerFolderSource.Insert(index, folderInfo); //전체 비디오에 반영 MessengerInstance.Send <Message>(new Message("FolderAdded", folderInfo), AllVideoViewModel.NAME); } } } ////////////////////////////////////////////////////////////////////////////////////////// }); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
protected override void DoOpen() { using (CustomBinaryReader reader = new CustomBinaryReader(new FileStream(ArchivePath, FileMode.Open, FileAccess.Read))) { uint signature = reader.ReadUInt32(); if (signature != 0x415342) { throw new InvalidDataException("File is not BSA"); } uint version = reader.ReadUInt32(); uint folderOffset = reader.ReadUInt32(); flags = (ArchiveFlags)reader.ReadUInt32(); uint folderCount = reader.ReadUInt32(); uint fileCount = reader.ReadUInt32(); uint totalFolderNameLength = reader.ReadUInt32(); uint totalFileNameLength = reader.ReadUInt32(); uint fileExtensions = reader.ReadUInt32(); FolderInfo[] folders = new FolderInfo[(int)folderCount]; // Read folders reader.BaseStream.Position = folderOffset; for (int i = 0; i < folderCount; i++) { ulong hash = reader.ReadUInt64(); uint count = reader.ReadUInt32(); uint unknown = reader.ReadUInt32(); ulong offset = reader.ReadUInt64() - totalFileNameLength; folders[i] = new FolderInfo() { FileCount = count, ContentOffset = offset }; } // Read folder content (name and files) foreach (var folder in folders) { byte folderNameLength = reader.ReadByte(); folder.Path = Encoding.UTF8.GetString(reader.ReadBytes(folderNameLength - 1)); byte zero = reader.ReadByte(); folder.Files = new FileInfo[folder.FileCount]; for (ulong i = 0; i < folder.FileCount; i++) { ulong hash = reader.ReadUInt64(); uint size = reader.ReadUInt32(); bool compressed = flags.HasFlag(ArchiveFlags.DefaultCompressed); if ((size & 0xf0000000) != 0) { size &= 0xfffffff; compressed = !compressed; } uint offset = reader.ReadUInt32(); folder.Files[i] = new FileInfo() { Size = size, DataOffset = offset, IsCompressed = compressed }; } } long total = fileCount; long loaded = 0; string filename = Path.GetFileName(ArchivePath); // Read file names foreach (var folder in folders) { foreach (var file in folder.Files) { file.Filename = reader.ReadStringZeroTerminated(); loaded++; } } // Convert to nested sorted dictionary for fast search for (int i = 0; i < folderCount; i++) { var files = new SortedDictionary <string, FileInfo>(); for (ulong j = 0; j < folders[i].FileCount; j++) { files.Add(folders[i].Files[j].Filename, folders[i].Files[j]); } sorted.Add(folders[i].Path, files); } return; } }
private async void LoadChildFolder(FolderInfo folder) { cancelTokenSource = new CancellationTokenSource(); await Task.Run(async() => { await DispatcherHelper.RunAsync(() => { CheckListButtonEnable = false; }); StorageFolder stFolder = null; //현재 폴더가 저장되지 않았거나, 위로 버튼을 눌러 이동하다 최 상위가 된 경우 if (folder == null || folder.Level == 0) { LoadRootFolders(); return; } else { try { stFolder = await folder.GetStorageFolder(false); } catch (Exception) { //현재 폴더 삭제 DB 물리적 삭제 if (folder.Type == FolderType.Last) { var asyncAction = folderDAO.Delete(folder); //문제가 발생한 경우 루트 폴더를 로드 LoadRootFolders(); } return; } } await DispatcherHelper.RunAsync(() => { if (ExplorerFolderSource.Count > 0) { ExplorerFolderSource.Clear(); } if (ExplorerFileSource.Count > 0) { ExplorerFileSource.Clear(); } ExplorerFolderSource.Add(new FolderInfo() { Level = folder.Level - 1, Name = string.Format(".. ({0})", ResourceLoader.GetForCurrentView().GetString("ToUpper")), Path = folder.ParentFolderPath, Type = FolderType.Upper, }); }); try { var folderList = (await stFolder.GetFoldersAsync()).OrderBy(x => x.Name); if (folderList != null && folderList.Any()) { await LoadFolderList(folderList, folder, cancelTokenSource.Token); } var fileStorageList = (await stFolder.GetFilesAsync()).OrderBy(x => x.Name); var fileList = fileStorageList.Where(x => x.IsVideoFile()); if (fileList != null && fileList.Any()) { await AddExplorerList(fileList, fileStorageList.Where(x => x.IsSubtitleFile()).ToList(), folder, cancelTokenSource.Token); await DispatcherHelper.RunAsync(() => { CheckListButtonEnable = true; }); } } catch (OperationCanceledException ex) { //DispatcherHelper.CheckBeginInvokeOnUI(() => { ExplorerFolderSource.Clear(); }); System.Diagnostics.Debug.WriteLine("폴더 네비게이션 취소됨 : " + ex.CancellationToken.GetHashCode()); } }, cancelTokenSource.Token); }
public void Add(string path) { if (string.IsNullOrEmpty(path)) { return; } bool isDir = false; if (path.EndsWith(DIR_SEP)) { isDir = true; path = path.Substring(0, path.Length - 1); } List <string> folders = new List <string>(); string filename = null; while (!string.IsNullOrEmpty(path)) { string sourcepath = System.IO.Path.GetDirectoryName(path); string elname = System.IO.Path.GetFileName(path); folders.Add(elname); path = sourcepath; if (path.EndsWith(DIR_SEP)) { path = path.Substring(0, path.Length - 1); } } if (!isDir) { filename = folders[0]; folders.RemoveAt(0); } IFolder cur = this; folders.Reverse(); StringBuilder sbp = new StringBuilder(); foreach (var f in folders) { sbp.Append(f); sbp.Append(DIR_SEP); FolderInfo next; if (!cur.Folders.TryGetValue(f, out next)) { //We have a new folder string id; if (!GeneratedKeys.TryGetValue(sbp.ToString(), out id)) { id = Guid.NewGuid().ToString(); GeneratedKeys.Add(sbp.ToString(), id); } Guid g; try { g = new Guid(id); } catch { g = Guid.NewGuid(); GeneratedKeys[sbp.ToString()] = g.ToString(); Console.Error.WriteLine("Unable to parse {0} into a GUID, I told you not to edit the file!!!{1}A new GUID will be used: {2}", id, Environment.NewLine, g); } string userkey; if (!UserKeys.TryGetValue(sbp.ToString(), out userkey)) { userkey = g.ToString(); } next = new FolderInfo(f, userkey, g); cur.Folders.Add(f, next); } cur = next; } if (!string.IsNullOrEmpty(filename)) { sbp.Append(filename); string id; if (!GeneratedKeys.TryGetValue(sbp.ToString(), out id)) { GeneratedKeys.Add(sbp.ToString(), id = Guid.NewGuid().ToString()); } if (UserKeys.ContainsKey(sbp.ToString())) { id = UserKeys[sbp.ToString()]; } string fullpath = System.IO.Path.Combine(m_opt.fileprefix, sbp.ToString()).Replace(DIR_SEP, "\\"); cur.Files.Add(filename, new FileInfo(filename, id, fullpath)); } }
private async Task AddExplorerList(IEnumerable <StorageFile> storageFile, List <StorageFile> subtitleList, FolderInfo parentFolder, CancellationToken token) { var prevFolderName = string.Empty; //재생목록 로드 List <MediaInfo> playlist = null; foreach (var item in storageFile) { var mi = new MediaInfo(item); if (subtitleList != null) { //비동기 모드로 파일의 기본 정보(사이즈, 생성일자) 로드 var asyncAction = ThreadPool.RunAsync((handler) => { if (playlist == null) { playlist = new List <MediaInfo>(); fileDAO.LoadPlayList(playlist, 100, 0, false); } //재생목록 존재여부 체크 mi.IsAddedPlaylist = playlist.Any(x => x.Path == mi.Path); var pathName = mi.Path.Remove(mi.Path.Length - Path.GetExtension(mi.Path).Length); //자막 검색 foreach (var ext in CCPlayerConstant.SUBTITLE_FILE_SUFFIX) { StorageFile subtitleFile = null; try { subtitleFile = new List <StorageFile>(subtitleList).FirstOrDefault(x => Path.GetExtension(x.Path).ToUpper() == ext.ToUpper() && x.Path.Length > ext.Length && x.Path.Remove(x.Path.Length - ext.Length).ToUpper().Contains(pathName.ToUpper())); } catch (Exception) { } if (subtitleFile != null) { subtitleList.Remove(subtitleFile); //자막을 미디어 파일에 연결 mi.AddSubtitle(new SubtitleInfo(subtitleFile)); } } }, WorkItemPriority.Low); } else { if (prevFolderName == item.Name) { mi.Name = string.Format("{0} ({1})", mi.Name, Path.GetPathRoot(mi.Path)); } prevFolderName = item.Name; } token.ThrowIfCancellationRequested(); await DispatcherHelper.RunAsync(() => { //if (token == cancelTokenSource.Token) if (currentFolderInfo.Path == mi.ParentFolderPath) { ExplorerFileSource.Add(mi); } }); } }
/// <summary> /// Returns a flag indicating whether the current user can view a folder or file /// </summary> /// <param name="folder">The page</param> /// <returns>A flag indicating whether the user has permission</returns> public static bool CanViewFolder(FolderInfo folder) { return(provider.CanViewFolder(folder)); }
protected void Page_Load(object sender, System.EventArgs e) { try { string renderUrl = Request.QueryString["rurl"]; if (!(string.IsNullOrEmpty(renderUrl))) { string fileContents = string.Empty; FileController fileCtrl = new FileController(); FileInfo fileInfo = null; int portalID = PortalController.Instance.GetCurrentPortalSettings().PortalId; if (renderUrl.ToLower().Contains("linkclick.aspx") && renderUrl.ToLower().Contains("fileticket")) { //File Ticket int fileID = GetFileIDFromURL(renderUrl); if (fileID > -1) { fileInfo = fileCtrl.GetFileById(fileID, portalID); } } else { if (renderUrl.Contains("?")) { renderUrl = renderUrl.Substring(0, renderUrl.IndexOf("?")); } //File URL string dbPath = (string)(string)FileSystemValidation.ToDBPath(renderUrl); string fileName = System.IO.Path.GetFileName(renderUrl); if (!string.IsNullOrEmpty(fileName)) { FolderInfo dnnFolder = GetDNNFolder(dbPath); if (dnnFolder != null) { fileInfo = fileCtrl.GetFile(fileName, portalID, dnnFolder.FolderID); } } } if (fileInfo != null) { if (CanViewFile(fileInfo.Folder)) { using (var streamReader = new StreamReader(FileManager.Instance.GetFileContent(fileInfo))) { fileContents = streamReader.ReadToEnd(); } } } if (!(string.IsNullOrEmpty(fileContents))) { Content.Text = Server.HtmlEncode(fileContents); } } } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); Content.Text = string.Empty; } }
public void CreateFolders() { if( workingDefinition.MaxNumberOfFoldersToGenerate > 0 ) { int totalProgress = CalculateTotalFoldersForProgressReporting(); updateProgressOverall("Creating Folders", totalProgress); } foreach (SiteCollInfo siteCollInfo in workingSiteCollections) { using (var siteColl = ObjectsFactory.GetSite(siteCollInfo.URL)) { foreach (SiteInfo siteInfo in siteCollInfo.Sites) { using (var web = siteColl.OpenWeb(siteInfo.ID)) { foreach (ListInfo listInfo in siteInfo.Lists) { if(listInfo.isLib) { for (int counter = 1; counter <= workingDefinition.MaxNumberOfFoldersToGenerate; counter++) { try { Log.Write("Creating folders in '" + web.Url + "/" + listInfo.Name); var list = web.GetList(listInfo.Name); string folderName = findAvailableFolderName(list); var folder = list.RootFolder.AddFolder(folderName); folder.Update(); FolderInfo folderInfo = new FolderInfo(); folderInfo.Name = folderName; folderInfo.URL = folder.Url; listInfo.Folders.Add(folderInfo); updateProgressDetail("Folder created '" + folderInfo.Name + "'"); for (int l = 0; l < workingDefinition.MaxNumberOfNestedFolderLevelPerLibrary; l++) { counter++; if (counter >= workingDefinition.MaxNumberOfFoldersToGenerate) { break; } folderName = findAvailableFolderName(list); folder = folder.AddFolder(folderName); //folder.Name = "Folder" + folderNumber; folder.Update(); FolderInfo folderInfo2 = new FolderInfo(); folderInfo2.Name = folderName; folderInfo2.URL = folder.Url; listInfo.Folders.Add(folderInfo2); updateProgressDetail("Folder created '" + folderInfo2.Name + "'"); } } catch(Exception ex) { Errors.Log(ex); } } } } } } } } }
protected override void DoOpen() { using (CustomBinaryReader reader = new CustomBinaryReader(new FileStream(ArchivePath, FileMode.Open, FileAccess.Read))) { uint signature = reader.ReadUInt32(); if (signature != 0x415342) { throw new InvalidDataException("File is not BSA"); } uint version = reader.ReadUInt32(); uint folderOffset = reader.ReadUInt32(); flags = (ArchiveFlags)reader.ReadUInt32(); uint folderCount = reader.ReadUInt32(); uint fileCount = reader.ReadUInt32(); uint totalFolderNameLength = reader.ReadUInt32(); uint totalFileNameLength = reader.ReadUInt32(); uint fileExtensions = reader.ReadUInt32(); FolderInfo[] folders = new FolderInfo[(int)folderCount]; // Read folders reader.BaseStream.Position = folderOffset; for (int i = 0; i < folderCount; i++) { ulong hash = reader.ReadUInt64(); uint count = reader.ReadUInt32(); uint offset = reader.ReadUInt32() - totalFileNameLength; folders[i] = new FolderInfo() { FileCount = count, ContentOffset = offset }; } // Read folder content (name and files) foreach (var folder in folders) { byte folderNameLength = reader.ReadByte(); folder.Path = Encoding.UTF8.GetString(reader.ReadBytes(folderNameLength - 1)); byte zero = reader.ReadByte(); folder.Files = new FileInfo[folder.FileCount]; for (int i = 0; i < folder.FileCount; i++) { ulong hash = reader.ReadUInt64(); uint size = reader.ReadUInt32(); bool compressed = flags.HasFlag(ArchiveFlags.DefaultCompressed); if ((size & 0xf0000000) != 0) { size &= 0xfffffff; compressed = !compressed; } uint offset = reader.ReadUInt32(); folder.Files[i] = new FileInfo() { Size = size, DataOffset = offset, IsCompressed = compressed }; } } long total = fileCount; long loaded = 0; string filename = Path.GetFileName(ArchivePath); // Read file names foreach (var folder in folders) { foreach (var file in folder.Files) { file.Filename = reader.ReadStringZeroTerminated(); loaded++; } } // Convert to nested sorted dictionary for fast search for (int i = 0; i < folderCount; i++) { var files = new SortedDictionary<string, FileInfo>(); for (int j = 0; j < folders[i].FileCount; j++) { files.Add(folders[i].Files[j].Filename, folders[i].Files[j]); } sorted.Add(folders[i].Path, files); } return; } }
public override IEnumerable <FileInfo> GetFiles(FolderInfo objfolderInfo) { return(FolderManager.Instance.GetFiles(objfolderInfo).OfType <FileInfo>().ToList()); }
/// ----------------------------------------------------------------------------- /// <summary> /// SaveFolderPermissions updates a Folder's permissions /// </summary> /// <param name="folder">The Folder to update</param> /// <history> /// [cnurse] 04/15/2009 Created /// </history> /// ----------------------------------------------------------------------------- public static void SaveFolderPermissions(FolderInfo folder) { SaveFolderPermissions((IFolderInfo)folder); }
public void Should_Create_Top_Folder() { var folder = new Mock<IFolder>().SetupProperty(p => p.ID, (uint)100); var userInfo = Make_UserInfo(); var folderInfo = new FolderInfo {ID = 1001}; var subscriptionGuid = new Guid("cb576e41-9e0a-44a0-ab79-753c383b3661"); PermissionManager.Setup(m => m.GetFolders(folder.Object.ID)).Returns(folder.Object); McmRepository.Setup(m => m.FolderCreate(userInfo.Guid, subscriptionGuid, "name", null, 1)).Returns(folderInfo.ID); McmRepository.Setup(m => m.FolderInfoGet(new[] { folderInfo.ID })).Returns(new[] { folderInfo }); PortalRequest.SetupGet(p => p.User).Returns(userInfo); PortalRequest.SetupGet(m => m.Subscriptions).Returns(new[] { new SubscriptionInfo { Guid = subscriptionGuid, Permission = SubscriptionPermission.CreateFolder }, }); var module = Make_FolderExtension(); var result = module.Create(subscriptionGuid, "name", null, 1); Assert.AreEqual(1001, result.ID); }
public void Add(string path) { if (string.IsNullOrEmpty(path)) return; bool isDir = false; if (path.EndsWith(DIR_SEP)) { isDir = true; path = path.Substring(0, path.Length - 1); } List<string> folders = new List<string>(); string filename = null; while(!string.IsNullOrEmpty(path)) { string sourcepath = System.IO.Path.GetDirectoryName(path); string elname = System.IO.Path.GetFileName(path); folders.Add(elname); path = sourcepath; if (path.EndsWith(DIR_SEP)) path = path.Substring(0, path.Length - 1); } if (!isDir) { filename = folders[0]; folders.RemoveAt (0); } IFolder cur = this; folders.Reverse(); StringBuilder sbp = new StringBuilder(); foreach(var f in folders) { sbp.Append(f); sbp.Append(DIR_SEP); FolderInfo next; if (!cur.Folders.TryGetValue(f, out next)) { //We have a new folder string id; if (!GeneratedKeys.TryGetValue(sbp.ToString(), out id)) { id = Guid.NewGuid().ToString(); GeneratedKeys.Add(sbp.ToString(), id); } Guid g; try { g = new Guid(id); } catch { g = Guid.NewGuid(); GeneratedKeys[sbp.ToString()] = g.ToString(); Console.Error.WriteLine ("Unable to parse {0} into a GUID, I told you not to edit the file!!!{1}A new GUID will be used: {2}", id, Environment.NewLine, g); } string userkey; if (!UserKeys.TryGetValue(sbp.ToString(), out userkey)) userkey = g.ToString(); next = new FolderInfo(f, userkey, g); cur.Folders.Add(f, next); } cur = next; } if (!string.IsNullOrEmpty(filename)) { sbp.Append(filename); string id; if (!GeneratedKeys.TryGetValue(sbp.ToString(), out id)) GeneratedKeys.Add(sbp.ToString(), id = Guid.NewGuid().ToString()); if (UserKeys.ContainsKey(sbp.ToString())) id = UserKeys[sbp.ToString()]; string fullpath = System.IO.Path.Combine(m_opt.fileprefix, sbp.ToString()).Replace(DIR_SEP, "\\"); cur.Files.Add(filename, new FileInfo(filename, id, fullpath)); } }
public virtual bool CanViewFolder(FolderInfo dnnFolder) { return(GetUserFolder(dnnFolder.FolderPath) != null); }
void Scan() { try { Msg( "Archive: {0}", ctrl.Path ); //..check the archive path's drive properties ctrl.TestArchiveDriveProperties(); //..create a date/time based folder name for this backup current = Ctrl.DateFolder( start, Ctrl.DateFolderLevel.Second ); { //..find the most recent date/time backup history folder string[] a = ctrl.HistoryFolders(); //..if none exist, invent one for a time 1 second prior to our current folder history = (a.Length > 0) ? a[a.Length -1] : Ctrl.DateFolder( start.AddSeconds( -1.0 ), Ctrl.DateFolderLevel.Second ); //..make sure the new backup folder is more recent than the last one if( string.Compare( current, history ) <= 0 ) { throw new Exception( "Scan: current folder is not newer than history folder" ); } } Msg( "History: {0}", history ); Msg( "Current: {0}", current ); current = ctrl.HistoryFullPath( current ); history = ctrl.HistoryFullPath( history ); if( debug ) { Log( ".s.current folder [{0}]", current ); Log( ".s.history folder [{0}]", history ); } if( DirectoryExists( history ) ) { try { if( debug ) { Log( ".s.move history to current" ); } DirectoryMove( history, current ); } catch( Exception ex ) { throw new Exception( "Scan: can not rename history folder to current", ex ); } } //..check Archive.keep for changes, submit a copy request if changed. try { string n = PathFilename( ctrl.Filename ); FileInfo fi = new FileInfo( ctrl.Filename ); FileInfo ci = new FileInfo( PathCombine( current, n ) ); if( debug ) { Log( ".s.check if control file has been updated [{0}]", fi.FullName ); } if( ! ci.Exists || ! ctrl.FileDateMatches( fi.LastWriteTimeUtc, ci.LastWriteTimeUtc ) || (fi.Length != ci.Length) ) { if( debug ) { Log( ".s.control file changed" ); } FolderInfo fo = new FolderInfo( string.Empty, ctrl.Path ); ScanQueue( ActionType.Copy, fo, string.Empty, n ); } } catch( Exception ex ) { ex.Data[ExCurrentRoot] = current; ex.Data[ExFilename] = ctrl.Filename; throw new Exception( "Scan: failed while checking archive control file", ex ); } CtrlArchive archive = ctrl.Archive; if( archive != null ) { bool b = true; //..backup each folder in archive set if( debug ) { Log( ".s.build list of existing folders in current" ); } List<string> a = DirectoryExists( current ) ? Ctrl.ListDirectories( current ) : new List<string>(); if( archive.Folders != null ) { foreach( CtrlFolder f in archive.Folders ) { try { Scan( f ); ListFilenameRemove( a, f.Name ); } catch( Exception ex ) { string s = string.Format( "Scan: {0}", Except.ToString( ex, debug ) ); Msg( s ); b = false; } } } //..move folders which are no longer part of the backup folder set to history if( b && ! IsCancelRequested && (a.Count > 0) ) { if( debug ) { Log( ".s.remove folders from current which are not part of backup set" ); } foreach( string n in a ) { if( debug ) { Log( " .s.remove [{0}]", n ); } FolderInfo f = new FolderInfo( n, null ); Log( string.Empty ); Msg( "Folder: {0}", f.Name ); //..delete/archive folders which are no longer part of the backup set ScanQueue( ActionType.Delete, f, string.Empty, null ); } } } } catch( Exception ex ) { ex.Data[ExArchiveRoot] = ctrl.Path; ex.Data[ExCurrentRoot] = current; ex.Data[ExHistoryRoot] = history; throw; } finally { status.scan.current = string.Empty; ctrl.HistoryFolders(); // This is here to make sure our last accessed folder doesn't lock one of the history directories } }
public static bool CanAddFolder(FolderInfo folder) { return(provider.CanAddFolder(folder) || CanAdminFolder(folder)); }
public ContextPath(IPrincipalItem currentPrincipal, UserFolderAccess userAccess, FolderInfo folderInfo, CalDavServer server) : base(userAccess, folderInfo, server) { Principal = currentPrincipal; }
public FolderInfo(FolderInfo o) { set(o); }
void RecursiveDelete( FolderInfo folder, string path ) { /* This method does not actually delete files, it merely counts the number of files * moved from Current to History - as in, flagged for deletion */ try { string s = folder.Name + ":" + MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ); status.update.current = s; if( debug ) { Log( ".u.recursive delete [{0}]", s ); } //..check if cancelled if( IsCancelRequested ) { throw new Exception( "Update cancelled." ); } string hp = PathCombine( history, folder.Name, path ); if( debug ) { Log( ".u.history path [{0}]", hp ); } try { #if __MonoCS__ { Mono.Unix.UnixSymbolicLinkInfo i = new Mono.Unix.UnixSymbolicLinkInfo( hp ); if( ! i.Exists || ! i.IsDirectory ) { return; } } #endif if( ! DirectoryExists( hp ) ) { if( debug ) { Log( ".u.history path does not exist" ); } return; } //..flag as deleted the number of files in the folder if( debug ) { Log( ".u.-----> files [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } foreach( string n in Ctrl.ListFiles( hp ) ) { string pn = PathCombine( path, n ); if( debug ) { Log( ".u.file [{0}]", pn ); } LogStatus( StatusType.Deleted, folder.Name, path, n ); Interlocked.Increment( ref status.update.deleted ); } //..recurse into all subdirectories if( debug ) { Log( ".u.-----> directories [{0}]", MatchPath.AbsoluteDirectoryPath( path ?? string.Empty ) ); } foreach( string n in Ctrl.ListDirectories( hp ) ) { string pn = PathCombine( path, n ); if( debug ) { Log( ".u.directory [{0}]", pn ); } RecursiveDelete( folder, pn ); } } catch( Exception ex ) { ex.Data[ExHistoryPath] = hp; throw; } } catch( Exception ex ) { ex.Data[ExPath] = path; throw; } }