Пример #1
0
 private void EncryptFileButton_Click(object sender, EventArgs e)
 {
     if (string.IsNullOrWhiteSpace(KeyBoxFile.Text) || string.IsNullOrWhiteSpace(FilePathBox.Text))
     {
         MessageBox.Show("You must enter a key!");
     }
     else
     {
         ResultsTextBox.AppendText("Encrypting...\n");
         var    crypto = new Crypto(KeyBoxFile.Text);
         string fileContents;
         using (StreamReader sr = new StreamReader(FilePathBox.Text))
         {
             fileContents = sr.ReadToEnd();
         }
         using (
             StreamWriter sw =
                 new StreamWriter(Path.Combine(Path.GetDirectoryName(FilePathBox.Text),
                                               Path.GetFileNameWithoutExtension(FilePathBox.Text) + "Encrypted" + ".txt")))
         {
             sw.Write(crypto.Encrypt(fileContents));
             sw.Write(Hasher.GenerateBase64Hash(MD5.Create(), fileContents));
         }
         ResultsTextBox.AppendText("Encryption complete.\n");
     }
 }
 private void RefreshResultsForm()
 {
     //MaintextBox.AppendText(grade.ToString());
     // MaintextBox.AppendText("\r\n");
     ResultsTextBox.Clear();
     ResultsTextBox.AppendText($"TotalScore: {quiz.CorrectAnswers} / {quiz.NumberOfQuestions}");
 }
Пример #3
0
        /// <summary>
        /// Загрузка
        /// </summary>
        ///
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            StartButton.IsEnabled = false;
            try
            {
                cts = new CancellationTokenSource();
                //ResultsTextBox.Clear();
                StopButton.Visibility = Visibility.Visible;
                await AccessTheWebAsync(UrlTextBox.Text.ToString(), cts.Token);

                ResultsTextBox.AppendText("Загрузка завершена.\n");
                if (new DirectoryInfo(BadDirectory).Exists)
                {
                    PurgeButton.Visibility = Visibility.Visible;
                }
            }
            catch (OperationCanceledException)
            {
                ResultsTextBox.AppendText("Загрузка отменена.\n");
            }
            catch (Exception)
            {
                ResultsTextBox.AppendText("Загрузка не удалась.\n");
            }
            finally
            {
                StartButton.IsEnabled = true;
                StopButton.Visibility = Visibility.Hidden;
            }
        }
Пример #4
0
 private void Purge(DirectoryInfo di)
 {
     try
     {
         Directory.Delete(di.FullName, true);
         //foreach (FileInfo file in di.EnumerateFiles())
         //{
         //    //if (WaitForFile(file.FullName))
         //        file.Delete();
         //}
         //foreach (DirectoryInfo dir in di.EnumerateDirectories())
         //{
         //    dir.Delete(true);
         //}
         ResultsTextBox.AppendText("Папка \"" + di.Name + "\" из каталога " + di.Parent.FullName + " успешно удалена!\n");
         PurgeButton.Visibility = Visibility.Hidden;
     }
     catch (Exception ex)
     {
         if (di.Exists)
         {
             ResultsTextBox.AppendText("Папка \"" + di.Name + "\" используется. Пожалуйста подождите ещё.\n");
         }
         else
         {
             ResultsTextBox.AppendText("Папка \"" + di.Name + "\" не найдена в каталоге " + di.Parent.FullName + "\n");
         }
     }
     finally
     {
     }
 }
Пример #5
0
        /// <summary>
        /// SELECT MAX(Salary) FROM Emps;
        /// </summary>
        public void Example3Button_Click(object sender, EventArgs e)
        {
            var res = Emps.Max(emp => emp.Salary);

            ResultsTextBox.Clear();
            ResultsTextBox.AppendText(res.ToString());
            ResultsList.DataSource = null;
        }
Пример #6
0
        /// <summary>
        /// Zwróć wartość "true" jeśli choć jeden
        /// z elementów kolekcji pracuje jako "Backend programmer".
        /// </summary>
        public void Example8Button_Click(object sender, EventArgs e)
        {
            var res = Emps.Any(emp => "Backend programmer".Equals(emp.Job));

            ResultsTextBox.Clear();
            ResultsTextBox.AppendText(res.ToString());
            ResultsList.DataSource = null;
        }
Пример #7
0
        //Znajdź pracownika z najwyższą pensją wykorzystując metodę Aggregate()
        public void Example11Button_Click(object sender, EventArgs e)
        {
            var res = Emps.Aggregate((empA, empB) => empA.Salary > empB.Salary ? empA : empB);

            ResultsTextBox.Clear();
            ResultsTextBox.AppendText(res.ToString());
            ResultsList.DataSource = null;
        }
Пример #8
0
        private void FeaturesSelectionComputeButton_Click(object sender, RoutedEventArgs e)
        {
            if (FeatureClasses == null || !FeatureClasses.Any())
            {
                ResultsTextBox.AppendText($"{Environment.NewLine}There is no class loaded, use Open file button to load some data.");
                return;
            }

            var validFeatureCountInputted = int.TryParse(FeaturesSelectionFeaturesCountTextBox.Text, out int featureCount);

            if (validFeatureCountInputted)
            {
                var computationResultBuilder = new StringBuilder($"{Environment.NewLine}Best {featureCount} features: ");
                try
                {
                    var watch = Stopwatch.StartNew();
                    IEnumerable <int> discriminationResults;
                    switch (SelectedAlgorithm)
                    {
                    case FeatureSelectionAlgorithm.SFS:
                        discriminationResults = new FisherLinearDiscriminator().DiscriminateWithSequentialForwardSelection(FeatureClasses, int.Parse(FeaturesSelectionFeaturesCountTextBox.Text));
                        break;

                    case FeatureSelectionAlgorithm.Default:
                    default:
                        discriminationResults = new FisherLinearDiscriminator().Discriminate(FeatureClasses, int.Parse(FeaturesSelectionFeaturesCountTextBox.Text));
                        break;
                    }
                    watch.Stop();

                    foreach (var featurePosition in discriminationResults)
                    {
                        computationResultBuilder.Append($"{featurePosition}, ");
                    }
                    computationResultBuilder.Remove(computationResultBuilder.Length - 2, 2);
                    computationResultBuilder.AppendLine($"\t{SelectedAlgorithm.ToString()}\tElapsed time: {watch.Elapsed.Minutes} min {watch.Elapsed.Seconds} s");
                    ResultsTextBox.AppendText(computationResultBuilder.ToString());
                }
                catch (Exception ex)
                {
                    ResultsTextBox.AppendText($"{Environment.NewLine}Error occured while computing: {ex.Message}.");
                }
            }
            else
            {
                ResultsTextBox.AppendText($"{Environment.NewLine}Invalid feature count \"{FeaturesSelectionFeaturesCountTextBox.Text}\" inputted.");
            }
        }
Пример #9
0
 private void DecryptFileButton_Click(object sender, EventArgs e)
 {
     if (string.IsNullOrWhiteSpace(KeyBoxFile.Text) || string.IsNullOrWhiteSpace(FilePathBox.Text))
     {
         MessageBox.Show("You must enter a key!");
     }
     else
     {
         ResultsTextBox.AppendText("Decrypting...\n");
         var    crypto = new Crypto(KeyBoxFile.Text);
         string fileContents;
         string extractedHash;
         string decryptedHash;
         using (StreamReader sr = new StreamReader(FilePathBox.Text))
         {
             fileContents = sr.ReadToEnd();
         }
         extractedHash         = Hasher.ExtractHash(fileContents);
         ExtractedHashBox.Text = extractedHash;
         fileContents          = fileContents.Substring(0, fileContents.Length - 24);
         var utf8WithBom = new UTF8Encoding(true);
         using (
             StreamWriter sw =
                 new StreamWriter(Path.Combine(Path.GetDirectoryName(FilePathBox.Text),
                                               Path.GetFileNameWithoutExtension(FilePathBox.Text) + "Decrypted" + ".txt"), false, utf8WithBom))
         {
             sw.Write(crypto.Decrypt(fileContents));
         }
         using (StreamReader sr = new StreamReader(Path.Combine(Path.GetDirectoryName(FilePathBox.Text), Path.GetFileNameWithoutExtension(FilePathBox.Text) + "Decrypted" + ".txt")))
         {
             fileContents = sr.ReadToEnd();
         }
         decryptedHash = Hasher.GenerateBase64Hash(MD5.Create(), fileContents);
         ResultsTextBox.AppendText("Decryption complete.\n");
         ResultsTextBox.AppendText(string.Format("Decrypted Hash: {0}\n", decryptedHash));
         ResultsTextBox.AppendText(string.Format("Extracted Hash: {0}\n", extractedHash));
         if (Hasher.VerifyHash(decryptedHash, extractedHash))
         {
             ResultsTextBox.AppendText("Hashes match!  Successful decryption.\n");
         }
         else
         {
             ResultsTextBox.AppendText("Hashes do not match!  Unsuccessful decryption.\n");
         }
     }
 }
Пример #10
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ResultsTextBox.AppendText(
                "\"URL\" - страница манги на comic-gardo. \n" +
                "\"Bad\" - папка для перепутанных изображений с сайта. \n" +
                "\"Good\" - папка для обработаных изображений. \n" +
                "\"Загрузить\" - загрузить изображения с сайта в папку Bad. \n" +
                "\"Обработать\" - восстановить порядок в изображениях и положить в папку Good.\n" +
                "\"Purge\" - удалить папку \"Bad\". Может потребовать подождать некоторое время.\n" +
                "===============================================================\n"

                );
            SrcTextBox.Text = System.AppDomain.CurrentDomain.BaseDirectory + "Bad\\";
            BadDirectory    = SrcTextBox.Text;

            OutTextBox.Text = System.AppDomain.CurrentDomain.BaseDirectory + "Good\\";
            //GoodDirectory = OutTextBox.Text;

            if (new DirectoryInfo(BadDirectory).Exists)
            {
                PurgeButton.Visibility = Visibility.Visible;
            }
        }
Пример #11
0
        private void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter      = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
                FilterIndex = 0
            };

            if (openFileDialog.ShowDialog() == true)
            {
                string[] fileContent = null;
                try
                {
                    fileContent = File.ReadAllLines(openFileDialog.FileName);
                    if (fileContent != null && fileContent.Any())
                    {
                        FeatureClasses = GetFeatureClasses(fileContent);
                        foreach (var featureClass in FeatureClasses)
                        {
                            if (featureClass.Features.Count < 10 && featureClass.Samples.Count < 10)
                            {
                                ResultsTextBox.AppendText($"{Environment.NewLine}{featureClass.ToString()}");
                            }
                            else
                            {
                                ResultsTextBox.AppendText($"{Environment.NewLine}{featureClass.Name} class loaded");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    ResultsTextBox.AppendText($"{Environment.NewLine} File {openFileDialog.FileName} is broken or of not supported format.");
                }
            }
        }
Пример #12
0
        private void ClassificationClassifyButton_Click(object sender, RoutedEventArgs e)
        {
            if (FeatureClasses == null || !FeatureClasses.Any())
            {
                ResultsTextBox.AppendText($"{Environment.NewLine}There is no class loaded, use Open file button to load some data.");
                return;
            }

            Vector <double> sample = null;
            int             k      = 1;

            try
            {
                sample = Vector <double> .Build.DenseOfEnumerable(ClassificationSampleTextBox.Text.Split(',').Select(x => double.Parse(x.Replace('.', ','))));

                k = int.Parse(ClassificationKTextBox.Text);
            }
            catch (Exception)
            {
                ResultsTextBox.AppendText($"{Environment.NewLine}Incorrect format of sample or k use:{Environment.NewLine}- \"double,double,double...\" e.g. \"1.023,34.232,43.123\" for sample{Environment.NewLine}- integer for k");
                return;
            }

            IClassifier classifier = null;

            switch ((ClassificationAlgorithm)ClassificationClassifierComboBox.SelectedIndex)
            {
            case ClassificationAlgorithm.NearestNeighbours:
            {
                classifier = new NearestNeighboursClassifier();
                break;
            }

            case ClassificationAlgorithm.NearestMeans:
            {
                if (!int.TryParse(ClassificationTrainingPartTextBox.Text, out int trainingPart) || trainingPart < 0 || trainingPart > 100)
                {
                    throw new ArgumentOutOfRangeException("Training part should be in range 0-100.");
                }
                classifier = new NearestMeansClassifier();
                break;
            }

            case ClassificationAlgorithm.NearestMeansWithDispertion:
            {
                if (!int.TryParse(ClassificationTrainingPartTextBox.Text, out int trainingPart) || trainingPart < 0 || trainingPart > 100)
                {
                    throw new ArgumentOutOfRangeException("Training part should be in range 0-100.");
                }
                classifier = new NearestMeansWithDispertionClassifier();
                break;
            }
            }
            string classificationResultClassName = string.Empty;

            try
            {
                classificationResultClassName = classifier.Classify(sample, FeatureClasses, k);
            }
            catch (Exception ex)
            {
                ResultsTextBox.AppendText($"{Environment.NewLine}Error occured while classifying: {ex.Message}");
                return;
            }

            ResultsTextBox.AppendText($"{Environment.NewLine}Sample has been classified to class: {classificationResultClassName}");
        }
Пример #13
0
 void ProgressEventHandler(object sender, PercentCompleteEventArgs e)
 {
     ResultsTextBox.AppendText(Properties.Resources.ProgressCharacter);
     ScrollToBottom();
     UpdateStatus(e.Percent);
 }
Пример #14
0
        private void RestoreButton_Click(object sender, EventArgs e)
        {
            // Restore the complete database to disk
            Cursor           csr = null;
            Restore          restore;
            Database         db;
            BackupDeviceItem backupDeviceItem;

            // Are you sure?  Default to No.
            if (System.Windows.Forms.MessageBox.Show(this,
                                                     string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                   Properties.Resources.ReallyRestore,
                                                                   DatabasesComboBox.Text), this.Text, MessageBoxButtons.YesNo,
                                                     MessageBoxIcon.Question, MessageBoxDefaultButton.Button2,
                                                     0) == DialogResult.No)
            {
                return;
            }

            try
            {
                csr         = this.Cursor;        // Save the old cursor
                this.Cursor = Cursors.WaitCursor; // Display the waiting cursor

                // Get database object from combobox
                db = (Database)DatabasesComboBox.SelectedItem;

                // Create a new Restore object instance
                restore = new Restore();

                // Restore database action
                restore.Action = RestoreActionType.Database;

                // Set database name
                restore.Database = db.Name;

                // Create a file backup device
                backupDeviceItem = new BackupDeviceItem(
                    BackupFileTextBox.Text, DeviceType.File);

                // Add database backup device
                restore.Devices.Add(backupDeviceItem);

                // Notify this program every 5%
                restore.PercentCompleteNotification = 5;

                // Replace the existing database
                restore.ReplaceDatabase = true;

                // Unload the backup device (tape)
                restore.UnloadTapeAfter = true;

                // add event handler to show progress
                restore.PercentComplete += new PercentCompleteEventHandler(
                    this.ProgressEventHandler);

                // generate and print script
                ResultsTextBox.AppendText(Properties.Resources.GeneratedScript);

                System.Collections.Specialized.StringCollection strColl =
                    restore.Script(SqlServerSelection);

                foreach (string script in strColl)
                {
                    ResultsTextBox.AppendText(script + Environment.NewLine);
                }

                ResultsTextBox.AppendText(Properties.Resources.Restoring);
                UpdateStatus(0);

                // Actual restore begins here
                restore.SqlRestore(SqlServerSelection);
                ResultsTextBox.AppendText(Properties.Resources.RestoreComplete);
            }
            catch (SmoException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
            finally
            {
                // Restore the original cursor
                this.Cursor = csr;
            }
        }
Пример #15
0
        /// <summary>
        /// Кнопка "Обработать"
        /// </summary>
        ///
        private async void Combine_Click(object sender, RoutedEventArgs e)
        {
            BadDirectory = SrcTextBox.Text;

            if (new DirectoryInfo(BadDirectory).Exists)
            {
                CombineButton.IsEnabled = false;
                try
                {
                    cts2 = new CancellationTokenSource();
                    StopButton.Visibility = Visibility.Visible;
                    cts3 = new CancellationTokenSource();
                    int      row   = 4;
                    int      col   = 4;
                    string[] files = { "" };
                    if (SrcTextBox.Text != "")
                    {
                        files = Directory.GetFiles(SrcTextBox.Text);
                    }

                    foreach (string image in files)
                    {
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(image);
                        string fileName = Path.GetFileName(image);
                        ResultsTextBox.AppendText("Обрабатывается: " + fileName + '\n');
                        DirectoryInfo di          = Directory.CreateDirectory(SrcTextBox.Text + "Temp\\" + fileNameWithoutExtension);
                        string        nameFromURL = "";
                        Regex         regex       = new Regex(@"[\d]");
                        Match         match       = regex.Match(UrlTextBox.Text);
                        while (match.Success)
                        {
                            nameFromURL += match.Value;
                            match        = match.NextMatch();
                        }
                        await SplitToImagesAsync(image, row, col, di.FullName, cts2.Token);

                        string[]      stitchedImages = Directory.GetFiles(di.FullName);
                        DirectoryInfo di2            = Directory.CreateDirectory(OutTextBox.Text + "\\" + nameFromURL);
                        Image         combinedImage  = await CombineAsync(stitchedImages, row, col, cts3.Token);

                        combinedImage.Save(di2.FullName + "\\" + fileName, System.Drawing.Imaging.ImageFormat.Png);
                        combinedImage.Dispose();
                    }
                    ResultsTextBox.AppendText("Изображения обработаны.\n");
                }
                catch (OperationCanceledException)
                {
                    ResultsTextBox.AppendText("Обработка отменена.\n");
                }
                catch (Exception)
                {
                    ResultsTextBox.AppendText("Обработка не удалась.\n");
                }
                finally
                {
                    CombineButton.IsEnabled = true;
                    StopButton.Visibility   = Visibility.Hidden;
                }
            }
            else
            {
                ResultsTextBox.AppendText("Директория: \"" + BadDirectory + "\" не найдена.\n");
            }
        }
Пример #16
0
        private void BackupButton_Click(object sender, EventArgs e)
        {
            Cursor           csr = null;
            Backup           backup;
            Database         db;
            BackupDeviceItem backupDeviceItem;

            try
            {
                csr         = this.Cursor;        // Save the old cursor
                this.Cursor = Cursors.WaitCursor; // Display the waiting cursor

                // Get database object from combobox
                db = (Database)DatabasesComboBox.SelectedItem;

                // Backup a complete database to disk
                // Create a new Backup object instance
                backup = new Backup();

                // Backup database action
                backup.Action = BackupActionType.Database;

                // Set backup description
                backup.BackupSetDescription
                    = string.Format(
                          System.Globalization.CultureInfo.InvariantCulture,
                          Properties.Resources.SampleBackup, db.Name);

                // Set backup name
                backup.BackupSetName
                    = string.Format(
                          System.Globalization.CultureInfo.InvariantCulture,
                          Properties.Resources.BackupSetName, db.Name);

                // Set database name
                backup.Database = db.Name;

                // Create a file backup device
                backupDeviceItem = new BackupDeviceItem(
                    BackupFileTextBox.Text, DeviceType.File);

                // Add a new backup device
                backup.Devices.Add(backupDeviceItem);

                // Only store this backup in the set
                backup.Initialize = true;

                // Set the media name
                backup.MediaName = Properties.Resources.MediaName;

                // Set the media description
                backup.MediaDescription = Properties.Resources.MediaDescription;

                // Notify this program every 5%
                backup.PercentCompleteNotification = 5;

                // Set the backup file retention to the current server run value
                backup.RetainDays = db.Parent.Configuration.MediaRetention.RunValue;

                // Skip the tape header, because we are writing to a file
                backup.SkipTapeHeader = true;

                // Unload the tape after the backup completes
                backup.UnloadTapeAfter = true;

                // Add event handler to show progress
                backup.PercentComplete += new PercentCompleteEventHandler(
                    this.ProgressEventHandler);

                // Generate and print script.
                ResultsTextBox.AppendText(Properties.Resources.GeneratedScript);
                ScrollToBottom();

                // Scripting here is strictly for text display purposes.
                String script = backup.Script(SqlServerSelection);

                ResultsTextBox.AppendText(script + Environment.NewLine);
                ScrollToBottom();
                ResultsTextBox.AppendText(Properties.Resources.BackingUp);
                ScrollToBottom();
                UpdateStatus(0);

                // Actual backup starts here.
                backup.SqlBackup(SqlServerSelection);

                ResultsTextBox.AppendText(Properties.Resources.BackupComplete);
                ScrollToBottom();
            }
            catch (SmoException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
            finally
            {
                // Restore the original cursor
                this.Cursor = csr;
            }
        }
Пример #17
0
        async Task AccessTheWebAsync(string url, CancellationToken ct)
        {
            //ResultsTextBox.AppendText(GetDomain(url));

            //Like https://comic-gardo.com/episode/10834108156661711906
            if (GetDomain(url) == "comic-gardo.com")
            {
                HttpClient          client   = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(url, 0, ct);

                string output = await response.Content.ReadAsStringAsync();

                string output2 = "", output3 = "", output4 = "", output5 = "";

                if (new DirectoryInfo(BadDirectory).Exists)
                {
                    Purge(new DirectoryInfo(BadDirectory));
                }


                //В теге <img> с классами "page-image js-page-image hidden"
                Regex regex1 = new Regex(@"<img\n\s\s\s\sclass=""page-image\sjs-page-image\shidden""[^>]+>");
                Match match  = regex1.Match(output);
                while (match.Success)
                {
                    output2 += match.Value;
                    match    = match.NextMatch();
                }
                //Строка data-src=""
                Regex regex2 = new Regex(@"data-src=""[^""]+""");
                match = regex2.Match(output2);
                while (match.Success)
                {
                    output3 += match.Value;
                    match    = match.NextMatch();
                }
                //В кавычках
                Regex regex3 = new Regex(@"""(.*?)""");
                match = regex3.Match(output3);
                while (match.Success)
                {
                    output4 += match.Value;
                    output4 += "\n";
                    match    = match.NextMatch();
                }
                //Без кавычек
                Regex regex4 = new Regex(@"[^""]");
                match = regex4.Match(output4);
                while (match.Success)
                {
                    output5 += match.Value;
                    match    = match.NextMatch();
                }

                string[] words = output5.Split('\n');
                foreach (string word in words)
                {
                    if (word != "")
                    {
                        outputs.Add(word);
                    }
                }
                //ResultsTextBox.AppendText(output5);
                ResultsTextBox.AppendText("\n");
                int i = 0;
                foreach (string imageSrc in outputs)
                {
                    WebClient     webClient = new WebClient();
                    DirectoryInfo bad       = Directory.CreateDirectory(SrcTextBox.Text);
                    webClient.DownloadFileAsync(new Uri(imageSrc), SrcTextBox.Text + "IMG-" + i++.ToString() + ".png");
                    ResultsTextBox.AppendText("URL: " + imageSrc + "\n");
                    ResultsTextBox.AppendText("Сохранён в файл: " + SrcTextBox.Text + "IMG-" + i.ToString() + ".png \n\n");
                }
                i = 0;
                outputs.Clear();
            }


            else
            {
                ResultsTextBox.AppendText("\nВ настоящий момент поддерживется только \"comic-gardo.com\".\n");
            }
        }