/// <summary>
        /// Creates a new <see cref="FileSystemControl" />.
        /// </summary>
        public FileSystemControl()
            : base()
        {
            m_controller = new FileSystemController();
            m_controller.SelectDirectory(CurrentDirectory);

            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.OpenSpecialDirectoriesDrawerCommand, OpenSpecialDirectoriesDrawerCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.SwitchPathPartsAsButtonsCommand, SwitchPathPartsAsButtonsHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.SelectDirectoryItemCommand, SelectDirectoryItemCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.SelectFileSystemEntryCommand, SelectFileSystemEntryCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.ShowInfoCommand, ShowInfoCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.CancelCommand, CancelCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.ShowCreateNewDirectoryCommand, ShowCreateNewDirectoryCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.CancelNewDirectoryCommand, CancelNewDirectoryCommandHandler));
            CommandBindings.Add(new CommandBinding(FileSystemControlCommands.CreateNewDirectoryCommand, CreateNewDirectoryCommandHandler));

            InputBindings.Add(new KeyBinding(FileSystemControlCommands.CancelCommand, new KeyGesture(Key.Escape)));

            m_pathPartsScrollViewer            = null;
            m_pathPartsItemsControl            = null;
            m_currentDirectoryTextBox          = null;
            m_fileSystemEntryItemsScrollViewer = null;
            m_fileSystemEntryItemsControl      = null;

            Loaded   += LoadedHandler;
            Unloaded += UnloadedHandler;
        }
Example #2
0
        private void DisplayPackagePath()
        {
            if (this.cboProductName.SelectedItem == null || this.cboProductVersion.SelectedItem == null)
            {
                return;
            }

            Package package;
            var     fileName = string.Empty;

            package  = this.Packages.FirstOrDefault(p => p.did == ((ComboItem)this.cboProductName.SelectedItem).Value && p.version == ((ComboItem)this.cboProductVersion.SelectedItem).Value);
            fileName = package.url.Split('/').Last();

            var downloadDirectory = FileSystemController.GetDownloadDirectory();
            var packageFullpath   = downloadDirectory + fileName;

            if (File.Exists(packageFullpath))
            {
                this.txtLocalInstallPackage.Text = packageFullpath;
            }
            else
            {
                this.txtLocalInstallPackage.Text = null;
            }
        }
Example #3
0
        private void GetOnlineVersion()
        {
            if (this.cboProductName.SelectedItem == null || this.cboProductVersion.SelectedItem == null)
            {
                return;
            }

            Package package;

            package = this.Packages.FirstOrDefault(p => p.did == ((ComboItem)this.cboProductName.SelectedItem).Value && p.version == ((ComboItem)this.cboProductVersion.SelectedItem).Value);
            var url      = package.url;
            var fileName = package.url.Split('/').Last();

            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.client_DownloadProgressChanged);
                client.DownloadFileCompleted   += new AsyncCompletedEventHandler(this.client_DownloadFileCompleted);
                var downloadDirectory = FileSystemController.GetDownloadDirectory();
                if (!Directory.Exists(downloadDirectory))
                {
                    Directory.CreateDirectory(downloadDirectory);
                }

                var dlContinue = true;
                if (File.Exists(downloadDirectory + fileName))
                {
                    var result = DialogController.ShowMessage(
                        "Get Online Version",
                        "Install Package is already downloaded. Would you like to download\nit again? This will replace the existing download.",
                        SystemIcons.Warning,
                        DialogController.DialogButtons.YesNo);

                    if (result == DialogResult.No)
                    {
                        dlContinue = false;
                    }
                }

                if (dlContinue)
                {
                    Log.Logger.Information("Downloading package from {url}", url);
                    this.downloadProgressLogTimer.Start();
                    client.DownloadFileAsync(new Uri(url), downloadDirectory + fileName);
                    this.progressBarDownload.BackColor = Color.WhiteSmoke;
                    this.progressBarDownload.Visible   = true;
                }
                else
                {
                    this.txtLocalInstallPackage.Text = Directory.GetCurrentDirectory() + "\\Downloads\\" + Path.GetFileName(url);
                    Properties.Settings.Default.LocalInstallPackageRecent = downloadDirectory;
                    Properties.Settings.Default.Save();
                    Log.Logger.Information("Using local install package {filePath}", this.txtLocalInstallPackage.Text);
                    this.ValidateInstallPackage();
                }
            }
        }
Example #4
0
        private void InitProgressBars()
        {
            var max = FileSystemController.CountFilesAndDirectories(this.sitePath);

            if (max > 0)
            {
                this.progressDeleteFiles.Maximum = max;
            }

            this.UpdateTotalProgress();
        }
Example #5
0
        public MainWindow()
        {
            InitializeComponent();
            InitStateForm();
            InitJournal();

            FileSystem = new FileSystemController();
            this.RequestRestore();

            this.FilesListBox.ItemsSource = FileSystem.filesList;

            FileSystem.UpdateFileSystemAsync();
        }
        public void TestBuildFullFileNameForInCurrentDirectoryWithoutForcedFileExtension()
        {
            FileSystemController fileSystemController = new FileSystemController()
            {
                ForceFileExtensionOfFileFilter = false,
                FileFilterToApply = FileFilterHelper.ParseFileFilter("Test", "*.cs;*.xaml")
            };

            fileSystemController.SelectDirectory(m_directory);

            string filename = fileSystemController.BuildFullFileNameForInCurrentDirectory("test.txt");

            Assert.AreEqual($@"{m_directory}\test.txt", filename);
        }
Example #7
0
        public void CheckForSpecifiedPathTest_Return_False()
        {
            // Arrange
            var dataStructure = new DataStructure
            {
                Input_address = Guid.NewGuid().ToString()
            };
            var fileSystemController = new FileSystemController(dataStructure);

            // Act
            var result = fileSystemController.CheckForSpecifiedPath();

            // Assert
            Assert.IsFalse(result);
        }
Example #8
0
        public void GetListOfFilesTest_Return_False()
        {
            // Arrange
            var dataStructure = new DataStructure
            {
                Input_address = Guid.NewGuid().ToString()
            };
            var fileSystemController = new FileSystemController(dataStructure);

            // Act
            var result = fileSystemController.GetListOfFiles();

            // Assert
            Assert.IsFalse(result);
        }
        public void TestSelectOrRemoveFileForMultipleSelection()
        {
            string gitconfigFile = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\.gitconfig";

            FileSystemController fileSystemController = new FileSystemController();

            Assert.False(fileSystemController.SelectedFiles.Any());

            fileSystemController.SelectOrRemoveFileForMultipleSelection(gitconfigFile);

            Assert.Contains(fileSystemController.SelectedFiles, file => file.FullName == gitconfigFile);

            fileSystemController.SelectOrRemoveFileForMultipleSelection(gitconfigFile);

            Assert.DoesNotContain(fileSystemController.SelectedFiles, file => file.FullName == gitconfigFile);
        }
Example #10
0
        public MainWindow(string path)
        {
            InitializeComponent();
            try
            {
                fsctrl = new FileSystemController();
                fsctrl.openSpace(path);
                openPath(fsctrl.CurrDir);
            }
            catch
            {
            }
            Title = "MeowOS - " + Session.userInfo.Login;

            showHiddenItem.IsEnabled = Session.userInfo.Role == UserInfo.Roles.ADMIN;
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            MainScreen            mainScreen              = new MainScreen();
            TargetCommunication   targetConnection        = new TargetCommunication();
            RealTimeModel         realTimeModelProperties = new RealTimeModel();
            RealTimeMonitor       realTimeMonitor         = new RealTimeMonitor();
            SimulationEnvironment simulationState         = new SimulationEnvironment();
            TargetFileSystem      targetFileSystem        = new TargetFileSystem();
            RealTimeLogging       realTimeLogger          = new RealTimeLogging();

            CommunicationController communicationController = new CommunicationController(mainScreen, targetConnection);
            RealTimeModelController realTimeModelController = new RealTimeModelController(mainScreen, targetConnection, realTimeModelProperties, simulationState);
            ApplicationController   applicationController   = new ApplicationController(mainScreen, targetConnection, realTimeModelProperties, realTimeMonitor, simulationState);
            FileSystemController    fileSystemController    = new FileSystemController(mainScreen, targetConnection, targetFileSystem, realTimeLogger, simulationState);

            Application.Run(mainScreen);
        }
        public FileSystemControl()
            : base()
        {
            m_controller = new FileSystemController();
            m_controller.SelectDirectory(CurrentDirectory);

            CommandBindings.Add(new CommandBinding(OpenSpecialDirectoriesDrawerCommand, OpenSpecialDirectoriesDrawerCommandHandler));
            CommandBindings.Add(new CommandBinding(SelectDirectoryItemCommand, SelectDirectoryItemCommandHandler));
            CommandBindings.Add(new CommandBinding(SelectFileSystemEntryCommand, SelectFileSystemEntryCommandHandler));
            CommandBindings.Add(new CommandBinding(ShowInfoCommand, ShowInfoCommandHandler));
            CommandBindings.Add(new CommandBinding(CancelCommand, CancelCommandHandler));

            m_pathPartsScrollViewer            = null;
            m_pathPartsItemsControl            = null;
            m_fileSystemEntryItemsScrollViewer = null;
            m_fileSystemEntryItemsControl      = null;

            Loaded   += LoadedHandler;
            Unloaded += UnloadedHandler;
        }
Example #13
0
        public void WriteDataToFileTest_Return_True()
        {
            // Arrange
            var listOfProcessedData = new Dictionary <string, int>();

            for (int i = 0; i < 10; i++)
            {
                listOfProcessedData.Add(Guid.NewGuid().ToString(), i);
            }

            var dataStructure = new DataStructure
            {
                ListOfProcessedData = listOfProcessedData
            };
            var fileSystemController = new FileSystemController(dataStructure);

            // Act
            var result = fileSystemController.WriteDataToFile();

            // Assert
            Assert.IsTrue(result);
        }
Example #14
0
        public void ProcessInputDataTest_Return_True()
        {
            // Arrange
            var listOfInputData = new List <string>();

            for (int i = 0; i < 10; i++)
            {
                listOfInputData.Add($"{Guid.NewGuid().ToString()},{i}");
            }

            var dataStructure = new DataStructure
            {
                ListOfInputData = listOfInputData
            };
            var fileSystemController = new FileSystemController(dataStructure);

            // Act
            var result = fileSystemController.ProcessInputData();

            // Assert
            Assert.IsTrue(result);
        }
        public void TestSelectOrRemoveDirectoryForMultipleSelection()
        {
            string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string myPictures  = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string myMusic     = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);

            FileSystemController fileSystemController = new FileSystemController();

            Assert.False(fileSystemController.SelectedDirectories.Any());

            fileSystemController.SelectOrRemoveDirectoryForMultipleSelection(myDocuments);
            fileSystemController.SelectOrRemoveDirectoryForMultipleSelection(myPictures);
            fileSystemController.SelectOrRemoveDirectoryForMultipleSelection(myMusic);

            Assert.Contains(fileSystemController.SelectedDirectories, directory => directory.FullName == myDocuments);
            Assert.Contains(fileSystemController.SelectedDirectories, directory => directory.FullName == myPictures);
            Assert.Contains(fileSystemController.SelectedDirectories, directory => directory.FullName == myMusic);

            fileSystemController.SelectOrRemoveDirectoryForMultipleSelection(myMusic);

            Assert.Contains(fileSystemController.SelectedDirectories, directory => directory.FullName == myDocuments);
            Assert.Contains(fileSystemController.SelectedDirectories, directory => directory.FullName == myPictures);
            Assert.DoesNotContain(fileSystemController.SelectedDirectories, directory => directory.FullName == myMusic);
        }
Example #16
0
 public void SetupContext()
 {
     controller = new FileSystemController();
 }
Example #17
0
        private async void DeleteSite()
        {
            using (var iisManager = new ServerManager())
            {
                // Stop Site
                var stopSiteProgress = new Progress <int>(percent =>
                {
                    this.progressStopSite.Value = percent;
                    this.UpdateTotalProgress();
                });
                try
                {
                    await Task.Run(() => IISController.StopSite(this.site.Id, stopSiteProgress)).ConfigureAwait(true);
                }
                catch (ArgumentException ex)
                {
                    this.Abort(ex.Source, ex.Message);
                }

                // Stop AppPool
                var stopAppPoolProgress = new Progress <int>(percent =>
                {
                    this.progressStopAppPool.Value = percent;
                    this.UpdateTotalProgress();
                });
                try
                {
                    await Task.Run(() => IISController.StopAppPool(this.site.Id, stopAppPoolProgress)).ConfigureAwait(true);
                }
                catch (ArgumentException ex)
                {
                    this.Abort(ex.Source, ex.Message);
                }

                // Delete Database
                var deleteDatabaseProgress = new Progress <int>(percent =>
                {
                    this.progressDeleteDatabae.Value = percent;
                    this.UpdateTotalProgress();
                });
                try
                {
                    var installFolder      = Directory.GetParent(this.sitePath);
                    var databaseController = new DatabaseController(
                        this.site.Name.Split('.')[0],
                        Properties.Settings.Default.DatabaseServerNameRecent,
                        true,
                        string.Empty,
                        string.Empty,
                        installFolder.FullName,
                        true,
                        this.site.Name);
                    await Task.Run(() => databaseController.DeleteDatabase(deleteDatabaseProgress)).ConfigureAwait(true);
                }
                catch (ArgumentException ex)
                {
                    this.Abort(ex.Source, ex.Message);
                    throw;
                }

                // Delete files
                var deleteFilesProgress = new Progress <string>(name =>
                {
                    if (this.progressDeleteFiles.Value < this.progressDeleteFiles.Maximum)
                    {
                        this.progressDeleteFiles.Value++;
                        this.UpdateTotalProgress();
                    }
                });
                try
                {
                    await Task.Run(() => FileSystemController.DeleteDirectory(this.sitePath, deleteFilesProgress, true)).ConfigureAwait(true);
                }
                catch (IOException)
                {
                    // Files mights still be streaming (logs for instance) after the site is stopped and deleted. Let's wait a bit and retry once after waiting 10 seconds.
                    Thread.Sleep(10000);
                    await Task.Run(() => FileSystemController.DeleteDirectory(this.sitePath, deleteFilesProgress, true)).ConfigureAwait(true);
                }

                this.progressDeleteFiles.Value = this.progressDeleteFiles.Maximum;
                this.UpdateTotalProgress();

                // Delete entry from HOSTS file
                var deleteHostEntryProgress = new Progress <int>(percent =>
                {
                    this.progressRemoveHostEntry.Value = percent;
                    this.UpdateTotalProgress();
                });
                await Task.Run(() => FileSystemController.RemoveHostEntry(this.site.Name, deleteHostEntryProgress)).ConfigureAwait(true);

                // Delete Site
                var deleteSiteProgress = new Progress <int>(percent =>
                {
                    this.progressDeletingSite.Value = percent;
                    this.UpdateTotalProgress();
                });
                try
                {
                    await Task.Run(() => IISController.DeleteSite(this.site.Id, deleteSiteProgress)).ConfigureAwait(true);
                }
                catch (ArgumentException ex)
                {
                    this.Abort(ex.Source, ex.Message);
                }

                // Try to delete AppPool if possible
                var deleteAppPoolProgress = new Progress <int>(percent =>
                {
                    this.progressDeleteAppPool.Value = percent;
                    this.UpdateTotalProgress();
                });
                try
                {
                    await Task.Run(() => IISController.DeleteAppPool(this.site.ApplicationDefaults.ApplicationPoolName, deleteAppPoolProgress)).ConfigureAwait(true);
                }
                catch (ArgumentException ex)
                {
                    DialogController.ShowMessage(
                        ex.Source,
                        ex.Message,
                        SystemIcons.Error,
                        DialogController.DialogButtons.OK);
                }
            }

            this.progressTotal.Value = this.progressTotal.Maximum;

            DialogController.ShowMessage(
                "Site Deleted",
                $"{this.site.Name} has been deleted successfully.",
                SystemIcons.Information,
                DialogController.DialogButtons.OK);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #18
0
        private void btnDatabaseInfoNext_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtDBServerName.Text) || string.IsNullOrWhiteSpace(this.txtDBName.Text))
            {
                DialogController.ShowMessage(
                    "Database Info",
                    "Please make sure you have entered a Database Server Name and\na Database Name.",
                    SystemIcons.Warning,
                    DialogController.DialogButtons.OK);

                return;
            }

            try
            {
                IISController.CreateSite(
                    this.SiteName,
                    this.InstallFolder,
                    this.chkSiteSpecificAppPool.Checked,
                    this.chkDeleteSiteIfExists.Checked);

                FileSystemController.UpdateHostsFile(this.SiteName);

                FileSystemController.CreateDirectories(
                    this.InstallFolder,
                    this.SiteName,
                    this.chkSiteSpecificAppPool.Checked,
                    this.txtDBServerName.Text.Trim(),
                    this.txtDBServerName.Text,
                    this.rdoWindowsAuthentication.Checked,
                    this.txtDBUserName.Text,
                    this.txtDBPassword.Text);

                var databaseController = new DatabaseController(
                    this.txtDBName.Text,
                    this.txtDBServerName.Text,
                    this.rdoWindowsAuthentication.Checked,
                    this.txtDBUserName.Text,
                    this.txtDBPassword.Text,
                    this.InstallFolder,
                    this.chkSiteSpecificAppPool.Checked,
                    this.SiteName);
                databaseController.CreateDatabase();
                databaseController.SetDatabasePermissions();

                this.tabInstallPackage.Enabled = false;
                this.tabSiteInfo.Enabled       = false;
                this.tabDatabaseInfo.Enabled   = false;
                this.tabControl.TabPages.Insert(3, this.tabProgress);
                this.tabProgress.Enabled      = true;
                this.lblProgress.Visible      = true;
                this.progressBar.Visible      = true;
                this.tabControl.SelectedIndex = 3;

                this.SaveUserSettings();

                this.ReadAndExtract(this.txtLocalInstallPackage.Text, Path.Combine(this.txtInstallBaseFolder.Text, this.txtInstallSubFolder.Text, "Website"));
                FileSystemController.ModifyConfig(
                    this.txtDBServerName.Text,
                    this.rdoWindowsAuthentication.Checked,
                    this.txtDBUserName.Text,
                    this.txtDBPassword.Text,
                    this.txtDBName.Text,
                    this.InstallFolder);

                this.btnVisitSite.Visible = true;
                Log.Logger.Information("Site {siteName} ready to visit", this.SiteName);
            }
            catch (SiteExistsException ex)
            {
                DialogController.ShowMessage(ex.Source, ex.Message, SystemIcons.Warning, DialogController.DialogButtons.OK);
            }
            catch (IISControllerException ex)
            {
                DialogController.ShowMessage(ex.Source, ex.Message, SystemIcons.Error, DialogController.DialogButtons.OK);
            }
            catch (FileSystemControllerException ex)
            {
                DialogController.ShowMessage(ex.Source, ex.Message, SystemIcons.Error, DialogController.DialogButtons.OK);
            }
            catch (DatabaseControllerException ex)
            {
                DialogController.ShowMessage(ex.Source, ex.Message, SystemIcons.Error, DialogController.DialogButtons.OK);
            }
            catch (Exception ex)
            {
                DialogController.ShowMessage("Database Info Next", ex.Message, SystemIcons.Error, DialogController.DialogButtons.OK);
                throw;
            }
        }
Example #19
0
        private void btnSiteInfoNext_Click(object sender, EventArgs e)
        {
            bool proceed;

            if (string.IsNullOrWhiteSpace(this.txtInstallBaseFolder.Text) || string.IsNullOrWhiteSpace(this.txtInstallSubFolder.Text) || string.IsNullOrWhiteSpace(this.txtSiteNamePrefix.Text))
            {
                DialogController.ShowMessage(
                    "Site Info",
                    "Please make sure you have entered a Site Name and Install Folder",
                    SystemIcons.Warning,
                    DialogController.DialogButtons.OK);

                return;
            }

            if (!Directory.Exists(this.InstallFolder))
            {
                var doNotWarnAgain = Properties.Settings.Default.LocationDoNotWarnAgain;

                if (!doNotWarnAgain)
                {
                    var result = DialogController.ShowMessage(
                        "Site Info",
                        "The entered location does not exist. Do you wish to create it?",
                        SystemIcons.Warning,
                        DialogController.DialogButtons.YesNoIgnore,
                        Properties.Settings.Default.LocationDoNotWarnAgain);

                    if (result == DialogResult.Yes)
                    {
                        Directory.CreateDirectory(this.InstallFolder);
                        proceed = true;
                    }
                    else
                    {
                        proceed = false;
                    }

                    Properties.Settings.Default.LocationDoNotWarnAgain = DialogController.DoNotWarnAgain;
                    Properties.Settings.Default.Save();
                }
                else
                {
                    Directory.CreateDirectory(this.InstallFolder);
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            if (proceed)
            {
                if (!FileSystemController.DirectoryEmpty(this.InstallFolder))
                {
                    var result = DialogController.ShowMessage(
                        "Confirm Installation",
                        "All files and folders at this location will be deleted prior to installation of\nthe new DNN instance. Do you wish to proceed?",
                        SystemIcons.Information,
                        DialogController.DialogButtons.YesNo);

                    if (result == DialogResult.No)
                    {
                        proceed = false;
                    }
                    else
                    {
                        proceed = true;
                    }
                }
                else
                {
                    proceed = true;
                }
            }

            if (proceed)
            {
                this.tabInstallPackage.Enabled = false;
                this.tabSiteInfo.Enabled       = false;
                this.tabControl.TabPages.Insert(2, this.tabDatabaseInfo);
                this.tabDatabaseInfo.Enabled  = true;
                this.tabProgress.Enabled      = false;
                this.tabControl.SelectedIndex = 2;
                this.SaveUserSettings();
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            Console.Title = "File processing Application v1.0";

            IDataProcessing dataProcessing;

            try
            {
                if (args == null)
                {
                    throw new IndexOutOfRangeException(Constants.EXCEPTION_INDEX_OUT_OF_RANGE);
                }

                if (args.Length < Constants.maxArgs)
                {
                    throw new IndexOutOfRangeException(Constants.EXCEPTION_INDEX_OUT_OF_RANGE);
                }

                if (args.Length == Constants.maxArgs)
                {
                    var result = OperationStatus.OPERATION_FAILED;

                    if (Constants.count_parallel <= 0)
                    {
                        throw new ArgumentException(Constants.EXCEPTION_ARGUMENT_PARALLEL);
                    }

                    var dataStructure = new DataStructure
                    {
                        Input_mode    = args[0],
                        Input_address = args[1]
                    };

                    switch (args[0])
                    {
                    case Constants.filesystemValue:
                    {
                        dataProcessing = new FileSystemController(dataStructure);
                        result         = dataProcessing.StartProcessing();
                    }
                    break;

                    case Constants.httpValue:
                    {
                        dataProcessing = new HttpController(dataStructure);
                        result         = dataProcessing.StartProcessing();
                    }
                    break;

                    case Constants.helpValue:
                    {
                        HelpInformation();
                    }
                    break;

                    default:
                    {
                        throw new ArgumentException(Constants.EXCEPTION_ARGUMENT_COMMON);
                    }
                    }

                    switch (result)
                    {
                    case OperationStatus.OPERATION_FAILED: { } break;

                    case OperationStatus.OPERATION_SUCCEEDED: { } break;

                    case OperationStatus.PATH: { Console.WriteLine(Constants.ERROR_PATH); } break;

                    case OperationStatus.LIST_OF_FILES: { Console.WriteLine(Constants.ERROR_LIST_OF_FILES); } break;

                    case OperationStatus.LIST_OF_INPUT_DATA: { Console.WriteLine(Constants.ERROR_LIST_OF_INPUT_DATA); } break;

                    case OperationStatus.PROCESSING_INPUT_DATA: { Console.WriteLine(Constants.ERROR_PROCESSING_INPUT_DATA); } break;

                    case OperationStatus.WRITE_DATA: { Console.WriteLine(Constants.ERROR_WRITE_DATA); } break;

                    case OperationStatus.DOWNLOAD_FILES: { Console.WriteLine(Constants.ERROR_DOWNLOAD_FILES); } break;
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (FormatException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Example #21
0
        private void authorize(string login, string password, bool createNew, ContentControl statusControl)
        {
            statusControl.Visibility = Visibility.Hidden;
            FileSystemSettingsWindow fssw = null;

            if (createNew)
            {
                fssw = new FileSystemSettingsWindow();
                if (!fssw.ShowDialog().Value)
                {
                    return;
                }
            }

            FileDialog dialog = createNew ? (FileDialog) new SaveFileDialog() : (FileDialog) new OpenFileDialog();

            dialog.DefaultExt = "mfs";
            dialog.Filter     = "Meow disk (*.mfs)|*.mfs";
            UserInfo userInfo = null;

            if (dialog.ShowDialog() == true)
            {
                FileSystemController fsctrl = new FileSystemController();
                SHA1   sha    = SHA1.Create();
                string digest = UsefulThings.ENCODING.GetString(sha.ComputeHash(UsefulThings.ENCODING.GetBytes(password)));
                digest = UsefulThings.replaceControlChars(digest);
                bool success;

                try
                {
                    if (createNew)
                    {
                        //Создать
                        //TODO 15.11: запрашивать параметры создаваемого диска?

                        /*ushort clusterSize = FileSystemController.FACTOR * 4; //Блок = 4 КБ
                         * ushort rootSize = (ushort)(clusterSize * 10); //Корневой каталог = 10 блоков
                         * uint diskSize = 50 * FileSystemController.FACTOR * FileSystemController.FACTOR; //Раздел = 50 МБ (или 1 МБ для тестов)*/
                        fsctrl.SuperBlock = new SuperBlock(fsctrl, "MeowFS", fssw.ClusterSizeBytes, fssw.RootSizeBytes, fssw.DiskSizeBytes);
                        fsctrl.Fat        = new FAT(fsctrl, (int)(fssw.DiskSizeBytes / fssw.ClusterSizeBytes));
                        fsctrl.RootDir    = UsefulThings.ENCODING.GetBytes(new String('\0', fssw.RootSizeBytes));
                        fsctrl.createSpace(dialog.FileName, login, digest);
                        userInfo = new UserInfo(1, login, 1, UserInfo.DEFAULT_GROUP, UserInfo.Roles.ADMIN);
                        success  = true;
                    }
                    else
                    {
                        //Открыть
                        fsctrl.openSpace(dialog.FileName);
                        byte[]   users    = fsctrl.readFile("/users.sys", false);
                        string[] usersStr = UsefulThings.fileFromByteArrToStringArr(users);
                        string[] tokens   = { "", "", "", "" }; //0 = login, 1 = digest, 2 = gid, 3 = role
                        ushort   uid;
                        success = false;
                        for (uid = 1; uid <= usersStr.Length && !success; ++uid)
                        {
                            tokens  = usersStr[uid - 1].Split(UsefulThings.USERDATA_SEPARATOR.ToString().ToArray(), StringSplitOptions.None);
                            success = tokens[0].ToLower().Equals(login.ToLower()) && tokens[1].Equals(digest);
                        }
                        if (success)
                        {
                            --uid;
                            byte[]   groups    = fsctrl.readFile("/groups.sys", false);
                            string[] groupsStr = UsefulThings.fileFromByteArrToStringArr(groups);
                            ushort   gid       = ushort.Parse(tokens[2]); if (gid > groups.Length)
                            {
                                gid = 1;
                            }
                            userInfo = new UserInfo(uid, tokens[0], gid, groupsStr[gid - 1], (UserInfo.Roles)Enum.Parse(typeof(UserInfo.Roles), tokens[3]));
                        }
                    }
                }
                catch
                {
                    success = false;
                }
                finally
                {
                    fsctrl.closeSpace();
                }

                if (success)
                {
                    Session.userInfo = userInfo;
                    MainWindow mw = new MainWindow(dialog.FileName);
                    Close();
                    mw.Show();
                }
                else
                {
                    statusControl.Content    = "Доступ не разрешён";
                    statusControl.Visibility = Visibility.Visible;
                }
            }
        }