Ejemplo n.º 1
0
        private DiscordEmbedBuilder UpdateEmbedListing(FileInfo file, DiscordEmbedBuilder embed)
        {
            embed.Description =
                $"Current File: **{file.Name}\n\nType `{_settings.GoBackCommand[0]}` to go back a directory\nType {_settings.ExitCommand[0]} at anytime to quit.**\n\n";

            var fileContent =
                FileSystemUtilities.GetFileContent(FileSystemUtilities.GetFile(file.Directory, file.Name));

            embed.Description += fileContent.Length > 1200
                ? fileContent.Substring(0, 1200) + "\n__***Too large to view further...***__"
                : fileContent;

            var actions = string.Empty;
            var id      = 1;

            foreach (var name in Enum.GetNames(typeof(FileSystemUtilities.EFileActions)))
            {
                actions += $"**{id}**) {name}\n";
                id++;
            }

            embed.ClearFields();
            embed.AddField("Actions", actions);

            return(embed);
        }
        /// <summary>
        /// Provides a common application logger, which writes to a rolling
        /// log file in the application's working directory. The logger
        /// always logs severe log events using the <see cref="Utilities.Logging.SevereLogFilter"/>,
        /// and by default, uses the default Logger <see cref="Utilities.Logging.Logger.Threshold"/> value.
        /// Initializes a new instance of the <see cref="ApplicationLogger"/> class.
        /// </summary>
        public ApplicationLogger()
        {
            // Figure out where we'll be logging the files
            string fileNameFormatted = FileSystemUtilities.PathCombine(Environment.CurrentDirectory, @"\app{0}.log");

            AddLogger(new RollingFileLogger(fileNameFormatted));
            AddLogFilter(new SevereLogFilter());

            // So that we know where the log is going
            string msg = string.Format("Application logging to {0}", fileNameFormatted);

            Console.WriteLine(msg);

#if DEBUG
            // Sometimes the Console does not go anywhere logical (or nowhere at all),
            // so it becomes difficult to know where the current directory is. Therefore,
            // we write the same message to a global file
            try
            {
                FileSystemUtilities.EnsureDirectoriesInPath(GlobalConstants.UtilitiesDefaultInstallLocation);
                Logger loggers = new FileLogger(GlobalConstants.UtilitiesDefaultInstallLocation + @"loggers.log");
                loggers.Threshold = LoggerSeverity.Info20;
                loggers.LogInfo20(msg);
            }
            catch (Exception)
            {
                // No permissions to write to the directory, and we don't bother trying anywhere else
            }
#endif
        }
Ejemplo n.º 3
0
 public static void CopyDirectoryRecursively(
     [InputPin(PropertyMode = PropertyMode.Default, ResolvePath = true)] string source,
     [InputPin(PropertyMode = PropertyMode.Default, ResolvePath = true)] string target
     )
 {
     FileSystemUtilities.CopyDirectoryRecursively(source, target);
 }
Ejemplo n.º 4
0
        public void NoVoidTypeOfExpressionsInGeneratedCodeEver()
        {
            var dir     = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Schemas"));
            var allXsds = dir.GetFiles("*.xsd", SearchOption.AllDirectories)
                          // Microsoft.Build schemas will have typeof(void) expressions due to the existence of bugs that predate this .net core port
                          .Where(f => !f.FullName.Contains("Microsoft.Build."))
                          .Select(f => f.FullName).ToArray();

            var allProcessableXsds = FileSystemUtilities.ResolvePossibleFileAndFolderPathsToProcessableSchemas(allXsds)
                                     .Select(fp => new FileInfo(fp));

            foreach (var xsd in allProcessableXsds)
            {
                var generatedCodeTree = Utilities.GenerateSyntaxTree(xsd);

                var root = generatedCodeTree.GetRoot();

                var allDescendents    = root.DescendantNodes().SelectMany(d => d.DescendantNodes());
                var allStatements     = allDescendents.OfType <StatementSyntax>();
                var allExpressions    = allStatements.SelectMany(s => s.DescendantNodes()).OfType <ExpressionSyntax>();
                var typeOfExpressions = allExpressions.OfType <TypeOfExpressionSyntax>().Distinct().ToArray();

                Assert.IsNotEmpty(typeOfExpressions);

                var typeOfVoid = SF.ParseExpression("typeof(void)");
                var nonVoidTypeOfExpressions = typeOfExpressions.Where(toe => !toe.IsEquivalentTo(typeOfVoid)).ToArray();
                var voidTypeOfExpressions    = typeOfExpressions.Where(toe => toe.IsEquivalentTo(typeOfVoid)).ToArray();

                Assert.IsNotEmpty(nonVoidTypeOfExpressions);
                Assert.IsEmpty(voidTypeOfExpressions);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Handles the Load event of the SetupForm control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 private void SetupForm_Load(object sender, EventArgs e)
 {
     LogHelper.GetLogger(this.GetType()).Log(string.Format("===== Starting Setup v{0} =====", this.ProductVersion));
     this.Text += " - version " + this.ProductVersion;
     this.RepositionControls();
     WizardManager.Current.SelectTab("Welcome");
     FileSystemUtilities.CopyFile(FileSystemUtilities.ReleaseNotesSetupPath, FileSystemUtilities.ReleaseNotesTempPath);
     FileSystemUtilities.CopyFromResource("SACS.Setup.Resources.DeploymentScript.sql", FileSystemUtilities.DeploymentScriptTempPath);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Saves the current config changes to the underlying config file.
        /// </summary>
        public void SaveChanges()
        {
            FileSystemUtilities.BackupFile(this.UnderlyingConfig.FilePath);

            this.SetAppSettingValue("System.DefaultPagingSize", this.DefaultPagingSize.ToString());
            this.SetAppSettingValue("WebAPI.BaseAddress", this.ServerAddress);
            this.UpdateUnderlyingConfig();

            _logger.Log("Saving config changes to " + this.UnderlyingConfig.FilePath);
            this.UnderlyingConfig.Save(ConfigurationSaveMode.Minimal, false);
        }
        public List <String> GetTargetLocationsValidated()
        {
            List <String> validatedLocations = new List <String>();

            foreach (String loc in validatedLocations)
            {
                if (FileSystemUtilities.IsDirectoryExistInTheSystem(loc))
                {
                    validatedLocations.Add(loc);
                }
            }
            return(validatedLocations);
        }
Ejemplo n.º 8
0
        public FileSystemTreeViewer(ILeftPanel fileSystemTreePanel)
        {
            InitializeComponent();
            var directories = FileSystemUtilities.GetRootDirectories();

            TreeViewer.DataContext = directories;
            _fileSystemTreePanel   = fileSystemTreePanel;
            var fileItemsViewModel = new FileItemsViewModel();

            MainSiteManager.Instance().SetVisibleSite(_fileSystemTreePanel.MainSite);
            (_fileSystemTreePanel.MainSite.RootFrameworkElement as FileItemsView).SetDataContext(fileItemsViewModel);
            FileBrowserHistory.PushBackHistory(String.Empty);
        }
Ejemplo n.º 9
0
        public TcaFileManager(CommandContext ctx, Server server, string rootDir, bool lockDirectory = false)
        {
            Server           = server;
            FileSystem       = Server.FileSystemService;
            CurrentDirectory = rootDir + "\\";
            LockDirectory    = lockDirectory;

            VirtualDirectorySecurity = new VirtualDirectorySecurity(CurrentDirectory);
            FileSystemUtilities      = new FileSystemUtilities(VirtualDirectorySecurity, Server, ctx);
            CurrentListing           = FileSystemUtilities.GenerateListingDirectory(CurrentDirectory, VirtualDirectorySecurity);
            CommandContext           = ctx;

            IsServer = true;
        }
        private void BtnAddFolder_Click(object sender, EventArgs e)
        {
            if (!FileSystemUtilities.IsDirectoryExistInTheSystem(SelectedPath))
            {
                return;
            }

            Button  genericButton    = (Button)sender;
            Panel   panelContainer   = (Panel)genericButton.Parent;
            TextBox addOtherLocation = AddedLocationTextBoxControl(panelContainer);

            if (!IsUniqueTargetLocation(addOtherLocation))
            {
                MessageBox.Show("Duplicate target folder found. Please choose a unique folder...", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Downloads a copy of the file if the file on the file system is older than the threshold.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="hoursThreshold">The number of hours the file should be cached for before a new copy is fetched.</param>
        public async Task Download(string uri, int hoursThreshold)
        {
            if (string.IsNullOrWhiteSpace(this.SaveLocation))
            {
                throw new Exception("The directory in SaveLocation has not been set.");
            }

            // Force it to always be negative
            hoursThreshold = System.Math.Abs(hoursThreshold) * -1;

            string fileName;

            if (string.IsNullOrWhiteSpace(this.OverrideFilename))
            {
                fileName = $"{this.SaveLocation}{FileSystemUtilities.ExtractFileName(uri)}";
            }
            else
            {
                fileName = $"{this.SaveLocation}{this.OverrideFilename}";
            }

            var fileInfo = new FileInfo(fileName);

            if (File.Exists(fileName) ||
                File.Exists(fileName) && fileInfo.LastWriteTime < DateTime.Now.AddHours(hoursThreshold))
            {
                using (var hc = new HttpClient())
                {
                    // Required to get some resources off GitHub.
                    hc.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0)");

                    using (var response = await hc.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
                    {
                        using (var s = await response.Content.ReadAsStreamAsync())
                        {
                            using (var fs = File.Open(fileName, FileMode.Create))
                            {
                                await s.CopyToAsync(fs);
                            }
                        }
                    }
                }
            }

            this.LastProcessedFile = fileName;
        }
        /// <summary>
        /// Gets the name of the file.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="timestamp">The timestamp.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="formatParameters">The format parameters.</param>
        /// <param name="logLine">The log line.</param>
        /// <param name="artifactSet">The artifact set.</param>
        /// <returns></returns>
        public string GetFileName(string fileName, LoggerSeverity severity, DateTime timestamp, object entry, object[] formatParameters, string logLine, LogArtifact[] artifactSet)
        {
            // First, find the largest numbered file
            string[] pieces = FileSystemUtilities.SplitFileIntoDirectoryAndName(fileName, true);
            string   search = pieces[1].Replace("{0}", "*");

            string[] files = Directory.GetFiles(pieces[0], search);

            int maxNumber = 0;

            // Now, build the list of numbers from the file names
            if (files != null)
            {
                foreach (string foundFile in files)
                {
                    int foundNumber = StringUtilities.ExtractFirstNumber(Path.GetFileName(foundFile));
                    if (foundNumber > maxNumber)
                    {
                        maxNumber = foundNumber;
                    }
                }
            }

            if (maxNumber == 0)
            {
                fileName = string.Format(fileName, maxNumber + 1);
            }
            else
            {
                string checkFileName = string.Format(fileName, maxNumber);

                // Check if this file is too big or not
                FileInfo info = new FileInfo(checkFileName);
                if (info.Exists && info.Length >= MaxFileSize)
                {
                    // Increment the file number
                    fileName = string.Format(fileName, maxNumber + 1);
                }
                else
                {
                    fileName = checkFileName;
                }
            }

            return(fileName);
        }
Ejemplo n.º 13
0
        public CustomFileItem(String fileName, CShItem cshItem)
        {
            CommonInitialization();
            String targetPath = cshItem.Path;

            DealWithSpecialFolders(cshItem.Path, cshItem.DisplayName, ref targetPath);
            this.customFileName = fileName.Trim();
            this.keyName        = cshItem.Name.Trim();
            this.Tag            = cshItem.Tag;
            this.lastWriteTime  = cshItem.LastWriteTime;
            this.creationTime   = cshItem.CreationTime;
            this.typeName       = SystemFilesDirInfo.GetFileTypeDescription(targetPath);
            this.fileLength     = cshItem.Length;
            this.filePathFull   = @targetPath;
            this.isFolder       = FileSystemUtilities.IsFullPathIsDirectory(targetPath);
            this.FolderType     = (this.isFolder) ? FolderType.TreeView : FolderType.File;
            SetIconsIndex(targetPath);
        }
        public static String GetLastOpenedDirectory()
        {
            String dir = LastOpenedDirectory;

            if (String.IsNullOrWhiteSpace(dir))
            {
                return(FileSystemUtilities.GetDefaultDirectory());
            }

            if (FileSystemUtilities.IsFullPathIsDirectory(dir.Trim()))
            {
                return(dir.Trim());
            }
            else
            {
                return(FileSystemUtilities.GetDefaultDirectory());
            }
        }
Ejemplo n.º 15
0
 private void SetIconsIndex(String fullPath)
 {
     if (FileSystemUtilities.IsFullPathIsDirectory(fullPath))
     {
         this.IconIndexOpen   = DefaultIcons.SYSTEM_ICONS.GetIconIndexForDirectories();
         this.IconIndexNormal = this.IconIndexOpen;
     }
     else if (this.isSpecialFolder)
     {
         this.IconIndexOpen   = 0;
         this.IconIndexNormal = 0;
     }
     else
     {
         this.IconIndexOpen   = DefaultIcons.SYSTEM_ICONS.GetIconIndex(fullPath);
         this.IconIndexNormal = this.IconIndexOpen;
     }
 }
        private void GenerateListViewCommonProcedureForExplorer(ListViewInterpretorViewingParamModel lvParamModel)
        {
            ArrayList        dirList        = lvParamModel.DirList;
            ArrayList        fileList       = lvParamModel.FileList;
            ListviewExtended targetListView = lvParamModel.TargetListView;

            try
            {
                if ((dirList.Count + fileList.Count) > 0)
                {
                    dirList.Sort();
                    fileList.Sort();

                    ArrayList combinationList = new ArrayList();
                    combinationList.AddRange(dirList);
                    combinationList.AddRange(fileList);

                    foreach (CShItem fileObj in combinationList)
                    {
                        if (!FileSystemUtilities.IsSpecialFolder(fileObj.Path, fileObj.DisplayName))
                        {
                            ListViewItemExtended lvItem = new ListViewItemExtended(fileObj, new string[] {
                                fileObj.DisplayName,                                                               //file name
                                fileObj.LastWriteTime.ToString(),                                                  //date modified
                                (fileObj.IsFolder) ? "" : ConverterUtils.HumanReadableFileSize(fileObj.Length, 2), //file size
                                fileObj.CreationTime.ToString(),                                                   // created date time
                                fileObj.TypeName                                                                   //file type
                            });
                            lvItem.ImageIndex = fileObj.IconIndexNormal;
                            targetListView.Items.Add(lvItem);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dirList.Clear();
                fileList.Clear();
            }
        }
Ejemplo n.º 17
0
        private bool IsFormValuesValidated()
        {
            String message = String.Empty;

            if (String.IsNullOrEmpty(txtBoxTargetDir.Text))
            {
                message = "Please select a target directory.";
            }
            else if (!FileSystemUtilities.IsDirectoryExistInTheSystem(txtBoxTargetDir.Text))
            {
                message = "Target directory value is not a valid or an existing directiory.";
            }
            else if (checkBoxHasMinFileSize.Checked && String.IsNullOrEmpty(((Control)numericUpDownMinFileSize).Text.ToString()))
            {
                message = "Please put a Minimum File Size";
            }
            else if (checkBoxHasMaxFileSize.Checked && String.IsNullOrEmpty(((Control)numericUpDownMaxFileSize).Text.ToString()))
            {
                message = "Please put a Maximum File Size";
            }
            else if (GetSelectedTimeSpanOption() == FolderFilterRule.TimeSpanOption.LAST_XX_DAYS &&
                     String.IsNullOrEmpty(((Control)numericUpDownLastXXDays).Text.ToString()))
            {
                message = "Please put at least on day on the Last XX days field";
            }
            else if (checkBoxHasMaxFileSize.Checked && numericUpDownMaxFileSize.Value == 0)
            {
                message = "Please put a non zero value on Maximum File Size";
            }
            else if (checkBoxHasMinFileSize.Checked && checkBoxHasMaxFileSize.Checked)
            {
                if (numericUpDownMaxFileSize.Value <= numericUpDownMinFileSize.Value)
                {
                    message = "Maximum File Size should be higher";
                }
            }
            if (message == String.Empty)
            {
                return(true);
            }
            MessageBox.Show(message, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return(false);
        }
Ejemplo n.º 18
0
 private bool IsDirectoryValidAndAccessible(String dirPath)
 {
     if (!FileSystemUtilities.isDriveReady(dirPath))
     {
         return(false);
     }
     if (!FileSystemUtilities.IsDirectoryExistInTheSystem(dirPath))
     {
         if (!FileSystemUtilities.MakeDirectory(dirPath))
         {
             return(false);
         }
     }
     if (!FileSystemUtilities.IsDirectoryHasReadAndWritePermission(dirPath))
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 19
0
        protected override void ImportFiles(string destinationDirectory)
        {
            ProcessStartInfo gitCloneStart = new ProcessStartInfo("git.exe");

            gitCloneStart.UseShellExecute        = false;
            gitCloneStart.RedirectStandardInput  = true;
            gitCloneStart.RedirectStandardOutput = true;
            gitCloneStart.RedirectStandardError  = true;
            gitCloneStart.CreateNoWindow         = true;
            gitCloneStart.Arguments = string.Format("clone \"{0}\" \"{1}\" -q", repositoryPath, destinationDirectory);

            var gitClone = Process.Start(gitCloneStart);

            string output;

            while ((output = gitClone.StandardOutput.ReadLine()) != null)
            {
                UpdateProgress("Git: " + output, false);
            }

            gitClone.WaitForExit();

            if (gitClone.ExitCode != 0)
            {
                throw new InvalidOperationException("Git error: " + gitClone.StandardError.ReadToEnd());
            }

            FileSystemUtilities.ResetDirectoryAttributes(destinationDirectory);

            var gitDirectories = Directory.GetDirectories(destinationDirectory, ".git*");

            foreach (var gitDirectory in gitDirectories)
            {
                FileSystemUtilities.DeleteDirectory(gitDirectory);
            }

            var gitFiles = Directory.GetFiles(destinationDirectory, ".git*");

            foreach (var gitFile in gitFiles)
            {
                File.Delete(gitFile);
            }
        }
Ejemplo n.º 20
0
        private void DealWithSpecialFolders(String fullPath, String fileName, ref String targetFilePath)
        {
            targetFilePath = fullPath;

            this.isSpecialFolder = FileSystemUtilities.IsSpecialFolder(fullPath, fileName);
            if (this.isSpecialFolder)
            {
                this.specialFolderFullPath = FileSystemUtilities.GetSpecialFolderFullPath(fileName);

                if (!String.IsNullOrWhiteSpace(this.specialFolderFullPath))
                {
                    targetFilePath = this.specialFolderFullPath;
                }
                else
                {
                    throw new Exception("Invalid Path");
                }
            }
        }
Ejemplo n.º 21
0
        public TcaFileManager(CommandContext ctx, CommandAttributes.RequireAuthentication authenticationService,
                              string rootDir, bool lockDirectory = false)
        {
            AuthenticationService = authenticationService;

            var service = authenticationService.Service;
            var user    = authenticationService.User;

            Server           = new Server(service.ServerId);
            FileSystem       = Server.FileSystemService;
            CurrentDirectory = rootDir + "\\";
            LockDirectory    = lockDirectory;

            VirtualDirectorySecurity =
                new VirtualDirectorySecurity(FileSystem, CurrentDirectory, user.UserType, service.GameId);
            FileSystemUtilities = new FileSystemUtilities(VirtualDirectorySecurity, Server, service, ctx);
            CurrentListing      = FileSystemUtilities.GenerateListingDirectory(CurrentDirectory, VirtualDirectorySecurity);
            CommandContext      = ctx;

            IsServer = false;
        }
Ejemplo n.º 22
0
        public ArrayList GetShellInfoDirectories()
        {
            ArrayList result = new ArrayList();

            DirectoryInfo[] dInfo = FileSystemUtilities.GetDirectories(FilePathFull);
            if (dInfo == null)
            {
                return(result);
            }

            foreach (DirectoryInfo obj in dInfo)
            {
                if (!FileSystemUtilities.IsSpecialFolder(obj.FullName, obj.Name))
                {
                    result.Add(new CustomFileItem(obj.Name, obj)
                    {
                        isFolder = true
                    });
                }
            }
            return(result);
        }
Ejemplo n.º 23
0
        public ArrayList GetShellInfoFiles()
        {
            ArrayList     result = new ArrayList();
            DirectoryInfo dInfo  = new DirectoryInfo(FilePathFull);

            try
            {
                foreach (FileInfo obj in dInfo.GetFiles())
                {
                    if (!FileSystemUtilities.IsSpecialFolder(obj.FullName, obj.Name))
                    {
                        result.Add(new CustomFileItem(obj.Name, obj)
                        {
                            isFolder = false
                        });
                    }
                }
            }
            catch (UnauthorizedAccessException) {}

            return(result);
        }
Ejemplo n.º 24
0
        public void ToClassStringWritersTest()
        {
            var xmlSpecXsd           = @"XMLSpec\xmlspec.xsd";
            var xmlSpecXsdConfigFile = @"XMLSpec\xmlspec.xsd.config";
            var xmlSpecXsdConfig     = Configuration.Load(xmlSpecXsdConfigFile);
            var xmlSpecSchemaSet     = FileSystemUtilities.PreLoadXmlSchemas(xmlSpecXsd);

            Assert.IsNotNull(xmlSpecSchemaSet);
            Assert.IsTrue(xmlSpecSchemaSet.IsCompiled);

            var ccu = XObjectsCoreGenerator.GenerateCodeCompileUnit(xmlSpecSchemaSet,
                                                                    xmlSpecXsdConfig.ToLinqToXsdSettings());

            var classStringWriters = ccu.ToClassStringWriters().ToList();

            Assert.IsNotEmpty(classStringWriters);

            foreach (var one in classStringWriters)
            {
                var classString = one.ToString();

                Assert.IsNotEmpty(classString);
            }
        }
Ejemplo n.º 25
0
 private void btnSaveLog_Click(object sender, EventArgs e)
 {
     FileSystemUtilities.SaveListViewItemsToLogFile(listViewLogs);
 }
 private void AddOtherFolder()
 {
     AddNewTargetLocationControls(
         (FileSystemUtilities.IsDirectoryExistInTheSystem(SelectedPath)
                 ? SelectedPath : ""));
 }
Ejemplo n.º 27
0
 private void linkSaveLogs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     FileSystemUtilities.SaveListViewItemsToLogFile(listViewLogs);
 }
Ejemplo n.º 28
0
        public async System.Threading.Tasks.Task InitializeFileManagerAsync()
        {
            var interactivity = CommandContext.Client.GetInteractivity();
            var waitMsg       = await CommandContext.RespondAsync("Please wait");

            if (!FileSystem.DirectoryExists(CurrentDirectory))
            {
                throw new CustomMessageException(EmbedTemplates.CreateErrorEmbed("Could not find directory"));
            }

            var embed = new DiscordEmbedBuilder
            {
                Title       = "File Manager", Color = new Optional <DiscordColor>(new DiscordColor(_settings.HexColor)),
                Description = $"**Navigating {CurrentDirectory}**\n\n",
                Thumbnail   = new DiscordEmbedBuilder.EmbedThumbnail
                {
                    Url = _settings.ThumbnailUrl
                }
            };

            embed = UpdateEmbedListing(embed);

            await waitMsg.DeleteAsync();

            ListingMessage = await CommandContext.RespondAsync(embed : embed);

            var      currentlyInFile = false;
            FileInfo currentFileInfo = null;

            while (true)
            {
                var choice = await interactivity.WaitForMessageAsync(x =>
                                                                     x.Author.Id == CommandContext.User.Id && x.Channel.Id == CommandContext.Channel.Id);

                if (choice.TimedOut)
                {
                    await ListingMessage.ModifyAsync(
                        embed : new Optional <DiscordEmbed>(
                            EmbedTemplates.CreateInfoEmbed("File Manager", "Ended Session")));

                    return;
                }

                var message = choice.Result.Content.ToLower();
                await choice.Result.DeleteAsync();

                if (_settings.ExitCommand.Contains(message))
                {
                    await ListingMessage.DeleteAsync();

                    return;
                }

                if (_settings.GoBackCommand.Contains(message))
                {
                    if (currentlyInFile)
                    {
                        CurrentListing  = FileSystemUtilities.NavigateCurrentFolder(currentFileInfo.Directory);
                        currentFileInfo = null;
                        currentlyInFile = false;
                        var updatedEmbed = UpdateEmbedListing(embed);
                        await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                    }
                    else
                    {
                        if (IsServer)
                        {
                            CurrentListing   = FileSystemUtilities.NavigateBackFolder(CurrentDirectory + "\\");
                            CurrentDirectory = new DirectoryInfo(CurrentDirectory).Parent?.FullName + "\\";
                            var updatedEmbed = UpdateEmbedListing(embed);
                            await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());

                            continue;
                        }

                        if (FileSystemUtilities.CanGoBack(CurrentDirectory + "\\",
                                                          AuthenticationService.Service.ServiceId) && !LockDirectory)
                        {
                            CurrentListing   = FileSystemUtilities.NavigateBackFolder(CurrentDirectory + "\\");
                            CurrentDirectory = new DirectoryInfo(CurrentDirectory).Parent?.FullName + "\\";
                            var updatedEmbed = UpdateEmbedListing(embed);
                            await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                        }
                    }
                }

                else if (int.TryParse(message, out var index))
                {
                    if (currentlyInFile)
                    {
                        var fileAction = (FileSystemUtilities.EFileActions)index;
                        if (await FileSystemUtilities.FileAction(currentFileInfo, fileAction))
                        {
                            if (fileAction == FileSystemUtilities.EFileActions.Extract ||
                                fileAction == FileSystemUtilities.EFileActions.Delete)
                            {
                                CurrentListing = FileSystemUtilities.NavigateCurrentFolder(CurrentDirectory);
                                var updatedEmbed = UpdateEmbedListing(embed);
                                await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());

                                currentlyInFile = false;
                                currentFileInfo = null;
                            }
                            else
                            {
                                var updatedEmbed = UpdateEmbedListing(currentFileInfo, embed);
                                await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                            }
                        }

                        continue;
                    }

                    var type = FileSystemUtilities.GetListingType(int.Parse(message), CurrentListing);

                    if (type == FileSystemUtilities.EListingType.Directory)
                    {
                        CurrentDirectory = CurrentListing.Directories[index - 1].FullName + "\\";
                        CurrentListing   = FileSystemUtilities.NavigateNextFolder(index, CurrentListing);
                        var updatedEmbed = UpdateEmbedListing(embed);
                        await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                    }
                    else
                    {
                        var fileInfo = FileSystemUtilities.GetFileInfo(index - CurrentListing.Directories.Length,
                                                                       CurrentListing);
                        currentFileInfo = fileInfo;
                        currentlyInFile = true;
                        var updatedEmbed = UpdateEmbedListing(fileInfo, embed);
                        await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                    }
                }

                else if (char.TryParse(message, out var result))
                {
                    var action = ToEnum <FileSystemUtilities.EDirectoryActions>(result.ToString().ToUpper());

                    if (!Enum.IsDefined(typeof(FileSystemUtilities.EDirectoryActions), action))
                    {
                        await CommandContext.RespondAsync("Cannot execute option if does not exist.");

                        continue;
                    }

                    if (await FileSystemUtilities.DirectoryAction(action, CurrentListing, CurrentDirectory))
                    {
                        if (action == FileSystemUtilities.EDirectoryActions.DeleteFolder)
                        {
                            CurrentListing = FileSystemUtilities.NavigateBackFolder(CurrentDirectory);
                            var updatedEmbed = UpdateEmbedListing(embed);
                            await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                        }
                        else
                        {
                            CurrentListing = FileSystemUtilities.NavigateCurrentFolder(CurrentDirectory);
                            var updatedEmbed = UpdateEmbedListing(embed);
                            await ListingMessage.ModifyAsync(embed : updatedEmbed.Build());
                        }
                    }
                    else
                    {
                        await CommandContext.RespondAsync("Error in refreshing directory");
                    }
                }
                else
                {
                    await CommandContext.RespondAsync("I don't know what you mean by " + message);
                }
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Ensure that all the folders needed by this application are present
 /// </summary>
 public static void EnsureDirectories()
 {
     FileSystemUtilities.EnsureDirectory("App_Data");
     FileSystemUtilities.EnsureDirectory("App_Data", "Logs");
     FileSystemUtilities.EnsureDirectory("App_Data", "Configurations");
 }
Ejemplo n.º 30
0
 protected override void ImportFiles(string destinationDirectory)
 {
     FileSystemUtilities.CopyDirectory(dependencyPath, destinationDirectory);
 }