Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Advanced WinForms Utilities: Batch File Processing, Secure Encryption, URL Decoding, Recursive Archive Extraction, and Dynamic Asset Management

Tech 1

Batch Extension Management and Database Integration

File extension modification requires reliable sorting mechanisms and database-backed configuraton storage. The following implementation retrieves sorted suffix entries from a local SQLite repository, populates a dropdown control, and executes batch renaming operations while gracefully handling duplicate extensions.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public partial class ExtensionManager : Form
{
    private List<string> predefinedSuffixes = new();

    private void Form_Load(object sender, EventArgs e)
    {
        LoadSortedSuffixes();
        if (suffixComboBox.Items.Count > 0) suffixComboBox.SelectedIndex = 0;
    }

    private void LoadSortedSuffixes()
    {
        suffixComboBox.Items.Clear();
        // Retrieve suffixes ordered by custom sort field
        var queryResult = DatabaseHelper.Query<string>("SELECT suffixName FROM SuffixConfig ORDER BY sortOrder");
        foreach (var item in queryResult)
            suffixComboBox.Items.Add(item);
    }

    private List<string> selectedFiles = new();

    private void BrowseFilesButton_Click(object sender, EventArgs e)
    {
        filePreviewList.Items.Clear();
        using var openFileDialog = new OpenFileDialog { Multiselect = true, Title = "Select Files" };
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            selectedFiles = openFileDialog.FileNames.ToList();
            foreach (var filePath in selectedFiles)
                filePreviewList.Items.Add(Path.GetFileName(filePath));
            statusLabel.Text = $"Selected: {selectedFiles.Count} files";
        }
    }

    private void RenameButton_Click(object sender, EventArgs e)
    {
        if (selectedFiles == null || !selectedFiles.Any())
        {
            MessageBox.Show("No files selected. Use the browse button first.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        string newSuffix = suffixComboBox.Text.Trim();
        if (string.IsNullOrEmpty(newSuffix)) newSuffix = ".txt"; // Default fallback

        filePreviewList.Items.Clear();
        int successCount = 0;

        foreach (var originalPath in selectedFiles)
        {
            try
            {
                string directory = Path.GetDirectoryName(originalPath);
                string fileNameWithoutExt = Path.GetFileNameWithoutExtension(originalPath);
                string newPath = Path.Combine(directory, $"{fileNameWithoutExt}{newSuffix}");

                if (!File.Exists(newPath))
                {
                    File.Move(originalPath, newPath);
                    filePreviewList.Items.Add(Path.GetFileName(newPath));
                    successCount++;
                }
            }
            catch (Exception ex)
            {
                filePreviewList.Items.Add($"[Skipped] {Path.GetFileName(originalPath)}");
            }
        }

        MessageBox.Show($"Batch operation complete. {successCount} files processed.", "Info");
    }
}

Asynchronous Binary Transformation Pipeline

Implementing multi-file cryptographic transformations requires background execution to maintain UI responsiveness. The pipeline reads binary data in chunks, applies a bitwise complement transformation, writes to output streams, and optionally purges source files upon completion.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class CryptoTransformer : Form
{
    private List<string> targetPaths = new();

    public CryptoTransformer()
    {
        InitializeComponent();
        progressBar.Value = 0;
        progressBar.Maximum = 100;
    }

    private async Task ProcessFilesAsync()
    {
        if (targetPaths == null || !targetPaths.Any())
        {
            MessageBox.Show("Add files before processing.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        progressBar.Value = 0;
        progressBar.Maximum = targetPaths.Count;
        totalProcessedLabel.Text = "0/0";

        for (int i = 0; i < targetPaths.Count; i++)
        {
            string currentPath = targetPaths[i];
            try
            {
                string originalName = Path.GetFileNameWithoutExtension(currentPath);
                string extension = Path.GetExtension(currentPath);
                string outputName;

                if (originalName.EndsWith("_encrypted", StringComparison.OrdinalIgnoreCase))
                    outputName = originalName.Replace("_encrypted", "_decrypted") + extension;
                else if (originalName.EndsWith("_decrypted", StringComparison.OrdinalIgnoreCase))
                    outputName = originalName.Replace("_decrypted", "_encrypted") + extension;
                else
                    outputName = $"{originalName}_encrypted{extension}";

                string outputPath = Path.Combine(Path.GetDirectoryName(currentPath), outputName);

                byte[] buffer = new byte[5242880]; // 5MB blocks for performance
                using var inputStream = new FileStream(currentPath, FileMode.Open, FileAccess.Read);
                using var outputStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write);

                int bytesRead;
                while ((bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    for (int j = 0; j < bytesRead; j++)
                        buffer[j] = (byte)(~buffer[j]); // Bitwise flip

                    await outputStream.WriteAsync(buffer, 0, bytesRead);
                }

                if (deleteOriginalCheckbox.Checked)
                {
                    try { File.Delete(currentPath); } catch { /* Access denied */ }
                }

                targetPaths[i] = outputPath;
                fileDisplayBox.Items.Add(outputName);
            }
            catch (IOException ex)
            {
                MessageBox.Show($"Source file locked or missing: {currentPath}\n{ex.Message}", "Error");
                return;
            }

            totalProcessedLabel.Text = $"{i + 1}/{targetPaths.Count}";
            progressBar.Value++; // Increment based on count, not percentage, for accuracy
        }

        progressBar.Value = 100;
        MessageBox.Show("Transformation completed successfully.", "Success");
    }

    private void ExecuteEncryptionButton_Click(object sender, EventArgs e)
    {
        targetPaths = GetSelectedPathsFromFilePicker();
        _ = ProcessFilesAsync();
    }

    private List<string> GetSelectedPathsFromFilePicker() { /* Implementation omitted for brevity */ return targetPaths; }
}

URL Obfuscation and Regular Expression Restoration

Download links are frequently obfuscated by platforms by interleaving arbitrary characters. Restoration involves stripping non-alphenumeric segments via Unicode range matching and reconstructing provider-speicfic base URLs based on identifier length patterns.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;

public partial class UrlDecoder : Form
{
    private void InitializeLoad() { LoadCustomInsertsFromDB(); }

    private void InsertRandomCharactersButton_Click(object sender, EventArgs e)
    {
        string url = rawUrlTextBox.Text.Trim();
        if (string.IsNullOrWhiteSpace(url)) { MessageBox.Show("Input a valid URL first."); return; }

        string insertionText = insertCombo.Text.Trim();
        if (string.IsNullOrWhiteSpace(insertionText) || !Regex.IsMatch(insertionText, @"^\p{IsCJKUnifiedIdeographs}+$"))
        {
            MessageBox.Show("Only Chinese characters are allowed for insertion."); return;
        }

        char[] urlChars = url.ToCharArray();
        Random random = new Random();
        int[] insertionIndices = new int[insertionText.Length];

        for (int i = 0; i < insertionText.Length; i++)
            insertionIndices[i] = random.Next(1, urlChars.Length - 1);

        Array.Sort(insertionIndices);

        List<char> finalChars = new();
        int urlIdx = 0;
        for (int i = 0; i < insertionIndices.Length; i++)
        {
            while (urlIdx < insertionIndices[i])
            {
                finalChars.Add(urlChars[urlIdx]);
                urlIdx++;
            }
            finalChars.Add(insertionText[i]);
        }
        while (urlIdx < urlChars.Length) { finalChars.Add(urlChars[urlIdx]); urlIdx++; }

        scrambledOutputTextBox.Text = new string(finalChars.ToArray());
    }

    private void RestoreUrlButton_Click(object sender, EventArgs e)
    {
        string obscured = scrambledOutputTextBox.Text.Trim();
        string clean = Regex.Replace(obscured, @"[^a-zA-Z0-9\/\.\:\?&=\-]", "");

        string baseUrl = "";
        int len = clean.Length;

        if (len is 23 or 32) baseUrl = "https://pan.baidu.com/s/";
        else if (len is 26 or 35) baseUrl = "https://pan.baidu.com/s/";
        else if (len is 12 or 15) baseUrl = "https://pan.quark.cn/s/";
        else baseUrl = "https://www.example-host.com/dl/";

        restoredUrlTextBox.Text = baseUrl + clean;
    }
}

Recursive Archive Decompression Engine

Automated unpacking of nested archives and split volumes demands careful directory state management. The extractor validates that the destination remains empty, attempts decryption against a credential store, identifies compressed payloads by size thresholds, and triggers recursive extraction until no archive remnants remain.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class AutoExtractor : Form
{
    private string sourceArchivePath = "";
    private string extractionRoot = "";
    private readonly HashSet<string> knownPasswords = new();

    private async Task ExtractRecursivelyAsync(string targetPath)
    {
        var dirInfo = new DirectoryInfo(targetPath);
        var allFiles = dirInfo.GetFiles();
        
        if (allFiles.Length == 0) return;

        List<FileInfo> archiveCandidates = allFiles.Where(f => f.Length > 5 * 1024 * 1024).ToList();
        if (archiveCandidates.Count == 0) return;

        // Handle split volumes
        if (archiveCandidates.Count > 1)
        {
            archiveCandidates = SplitVolumeResolver.Resolve(archiveCandidates);
        }

        foreach (var candidate in archiveCandidates)
        {
            string tempDir = Path.Combine(targetPath, Guid.NewGuid().ToString());
            Directory.CreateDirectory(tempDir);

            bool extracted = false;
            foreach (var pwd in knownPasswords)
            {
                if (await ExternalTool.UnpackAsync(candidate.FullName, tempDir, pwd))
                {
                    extracted = true;
                    break;
                }
            }

            if (!extracted && knownPasswords.Count == 0)
            {
                MessageBox.Show("No credentials available for extraction.");
                return;
            }

            await ExtractRecursivelyAsync(tempDir);
            
            // Cleanup failed attempts or merge successful ones
            foreach (var subFile in new DirectoryInfo(tempDir).GetFiles())
            {
                string dest = Path.Combine(targetPath, subFile.Name);
                if (!File.Exists(dest)) File.Move(subFile.FullName, dest);
            }
            Directory.Delete(tempDir, true);
        }
    }

    private void ValidateEmptyDirectory(string path)
    {
        if (Directory.Exists(path) && (Directory.GetFiles(path).Any() || Directory.GetDirectories(path).Any()))
            throw new InvalidOperationException("Extraction target must be an empty directory.");
    }
}

Virtual Directory Explorer Interface

A custom navigation pane replaces standard dialog controls to provide richer metadata visibility. Folders and files are enumerated into a ListView with categorized columns, supporting context-driven actions like direct extraction or parent directory traversal.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public partial class CustomExplorer : Form
{
    private string currentBrowsePath = string.Empty;

    private void PopulateFileSystemTree(string rootPath)
    {
        fileViewerList.Items.Clear();
        var di = new DirectoryInfo(rootPath);

        foreach (var folder in di.GetDirectories())
            fileViewerList.Items.Add(new ListViewItem(new[] { folder.Name, "Folder", "-" }, ImageIndex.Folder));

        foreach (var file in di.GetFiles())
        {
            string type = file.Extension switch
            {
                ".exe" or ".dll" => "Executable",
                ".txt" or ".log" => "Document",
                ".zip" or ".rar" or ".7z" => "Compressed",
                _ => "Unknown"
            };
            long displaySize = Math.Round(file.Length / 1024.0, 2);
            fileViewerList.Items.Add(new ListViewItem(new[] { file.Name, type, $"{displaySize} KB" }, ImageIndex.File));
        }
    }

    private void NavigateUpButton_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(currentBrowsePath) || currentBrowsePath.Length <= 3)
        {
            MessageBox.Show("Cannot navigate above root drive.");
            return;
        }

        var parent = Path.GetDirectoryName(currentBrowsePath);
        if (!string.IsNullOrEmpty(parent))
        {
            currentBrowsePath = parent;
            addressBar.Text = currentBrowsePath;
            PopulateFileSystemTree(currentBrowsePath);
        }
    }

    private void ContextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
    {
        var selected = fileViewerList.SelectedItems;
        if (selected.Count != 1) return;

        string fileType = selected[0].SubItems[1].Text;
        actionMenuItem.Text = fileType == "Folder" ? "Navigate Into" : "Extract Archive";
    }
}

Dynamic Asset Browser and Control Generation

Displaying game repositories with embedded media requires dynamic layout management. Thumbnails are fetched from binary blobs, scaled proportionally to fit a container, and aligned vertically. Metadata such as download links and passwords trigger programmatic generation of interactive UI elements.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public partial class GameCatalog : UserControl
{
    private List<GameRecord> catalogData = new();

    private void RenderImageGallery(List<ImageBlob> images, Panel displayArea)
    {
        displayArea.Controls.Clear();
        int accumulatedHeight = 0;
        int maxWidth = 740;

        for (int i = 0; i < images.Count; i++)
        {
            MemoryStream stream = new(images[i].RawBytes);
            PictureBox thumb = new()
            {
                SizeMode = PictureBoxSizeMode.Zoom,
                Visible = true
            };

            Image origImg = Image.FromStream(stream);
            float ratio = (float)origImg.Width / origImg.Height;
            int drawWidth = origImg.Width > maxWidth ? maxWidth : origImg.Width;
            int drawHeight = (int)(drawWidth / ratio);

            thumb.Size = new Size(drawWidth, drawHeight);
            thumb.Image = origImg;
            thumb.Location = new Point(0, accumulatedHeight);

            accumulatedHeight += drawHeight + 5;
            displayArea.Controls.Add(thumb);
        }
    }

    private void GenerateMetadataControls(GameRecord record)
    {
        flowLayoutPanel.Controls.Clear();
        
        for (int i = 0; i < record.Links.Count; i++)
        {
            var link = record.Links[i];
            
            Button dlBtn = new()
            {
                Text = link.DisplayName,
                Size = new Size(90, 28),
                Tag = link.Url
            };
            dlBtn.Click += (s, e) => OpenExternalBrowser(dlBtn.Tag.ToString());
            
            TextBox passBox = new()
            {
                Text = link.Password,
                ReadOnly = true,
                Size = new Size(90, 28),
                Location = new Point((flowLayoutPanel.Controls.Count * 95) + 5, 35)
            };

            flowLayoutPanel.Controls.AddRange(new Control[] { dlBtn, passBox });
        }
    }

    private void OpenExternalBrowser(string url)
    {
        string browserPath = browserSelection.SelectedValue?.ToString();
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
        {
            FileName = string.IsNullOrEmpty(browserPath) ? "explorer" : browserPath,
            Arguments = url,
            UseShellExecute = true
        });
    }
}

Network Endpoint Verification Helper

Validating remote resource availability prior to user initiation prevents runtime failures. A HEAD request assesses server reachability and HTTP status codes without downloading payload data.

using System;
using System.Net;
using System.Threading.Tasks;

public static class ConnectivityVerifier
{
    public static async Task<bool> IsEndpointReachableAsync(string uriString)
    {
        if (!Uri.TryCreate(uriString, UriKind.Absolute, out Uri uri)) return false;

        try
        {
            using HttpClient client = new()
            {
                Timeout = TimeSpan.FromSeconds(5)
            };

            HttpRequestMessage request = new(HttpMethod.Head, uri)
            {
                Headers = { UserAgent.Parse("WinFormsUtility/1.0") }
            };

            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            return response.IsSuccessStatusCode;
        }
        catch (TaskCanceledException)
        {
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.