20 August, 2025

[C#] Chia sẻ source code phần mềm Image Downloader tải hình ảnh hàng loạt

August 20, 2025 Posted by Tôi Hùng ✅ , , No comments

Chào mọi người.

Đã lâu rồi mình không ghé trang laptrinhvb.net, nay ghé lại thấy anh thảo có chia sẽ bộ mã nguồn download image hoàng loạt cũng khá thú vị nên mình mang về chia sẽ lại cho mọi người.
Như hình, các bạn chỉ cần dán danh sách link vào và bấm nút tải về.

Có thể xem trước (preview) từng hình ảnh.

Dưới đây là video demo ứng dụng:


Full Source Code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq;

namespace ImageDownloader
{
    public partial class MainForm : Form
    {
        private ListBox listBoxUrls;
        private TextBox textBoxUrls;
        private TextBox textBoxOutputPath;
        private Button buttonBrowseOutput;
        private Button buttonAddUrls;
        private Button buttonRemoveUrl;
        private Button buttonDownloadAll;
        private Button buttonClearAll;
        private ProgressBar progressBar;
        private Label labelStatus;
        private PictureBox pictureBoxPreview;
        private Label labelPreview;
        private Panel panelPreview;
        private static readonly HttpClient httpClient = new HttpClient();

        public MainForm()
        {
            InitializeComponent();
            InitializeHttpClient();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // Form properties
            this.Text = "Image Downloader - https://laptrinhvb.net";
            this.Size = new Size(1000, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            this.MinimumSize = new Size(800, 500);

            // URL input textbox (multiline for pasting multiple URLs)
            this.textBoxUrls = new TextBox
            {
                Location = new Point(12, 12),
                Size = new Size(450, 100),
                Multiline = true,
                ScrollBars = ScrollBars.Vertical,
               
            };

            // Add URLs button
            this.buttonAddUrls = new Button
            {
                Location = new Point(470, 12),
                Size = new Size(80, 30),
                Text = "Add URLs",
                UseVisualStyleBackColor = true
            };
            this.buttonAddUrls.Click += ButtonAddUrls_Click;

            // URLs ListBox
            this.listBoxUrls = new ListBox
            {
                Location = new Point(12, 120),
                Size = new Size(550, 200),
                SelectionMode = SelectionMode.MultiExtended
            };
            this.listBoxUrls.SelectedIndexChanged += ListBoxUrls_SelectedIndexChanged;
            this.listBoxUrls.KeyDown += ListBoxUrls_KeyDown;

            // Remove URL button
            this.buttonRemoveUrl = new Button
            {
                Location = new Point(12, 330),
                Size = new Size(100, 30),
                Text = "Remove Selected",
                UseVisualStyleBackColor = true
            };
            this.buttonRemoveUrl.Click += ButtonRemoveUrl_Click;

            // Clear all button
            this.buttonClearAll = new Button
            {
                Location = new Point(120, 330),
                Size = new Size(80, 30),
                Text = "Clear All",
                UseVisualStyleBackColor = true
            };
            this.buttonClearAll.Click += ButtonClearAll_Click;

            // Output path label
            Label labelOutput = new Label
            {
                Location = new Point(12, 375),
                Size = new Size(100, 20),
                Text = "Output Folder:"
            };

            // Output path textbox
            this.textBoxOutputPath = new TextBox
            {
                Location = new Point(12, 400),
                Size = new Size(450, 23),
                Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Downloaded_Images")
            };

            // Browse output button
            this.buttonBrowseOutput = new Button
            {
                Location = new Point(470, 400),
                Size = new Size(75, 23),
                Text = "Browse",
                UseVisualStyleBackColor = true
            };
            this.buttonBrowseOutput.Click += ButtonBrowseOutput_Click;

            // Download all button
            this.buttonDownloadAll = new Button
            {
                Location = new Point(12, 435),
                Size = new Size(120, 35),
                Text = "Download All",
                UseVisualStyleBackColor = true,
                BackColor = Color.LightGreen
            };
            this.buttonDownloadAll.Click += ButtonDownloadAll_Click;

            // Progress bar
            this.progressBar = new ProgressBar
            {
                Location = new Point(12, 485),
                Size = new Size(550, 23),
                Style = ProgressBarStyle.Continuous
            };

            // Status label
            this.labelStatus = new Label
            {
                Location = new Point(12, 520),
                Size = new Size(550, 40),
                Text = "Ready to download images...",
                AutoSize = false
            };

            // Preview Panel
            this.panelPreview = new Panel
            {
                Location = new Point(580, 12),
                Size = new Size(400, 548),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.WhiteSmoke
            };

            // Preview label
            this.labelPreview = new Label
            {
                Location = new Point(10, 10),
                Size = new Size(380, 20),
                Text = "Click on a URL to preview image",
                TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("Microsoft Sans Serif", 9, FontStyle.Bold)
            };

            // Picture box for preview
            this.pictureBoxPreview = new PictureBox
            {
                Location = new Point(10, 40),
                Size = new Size(380, 500),
                SizeMode = PictureBoxSizeMode.Zoom,
                BorderStyle = BorderStyle.FixedSingle,
                BackColor = Color.White
            };

            // Add controls to preview panel
            this.panelPreview.Controls.AddRange(new Control[] {
                this.labelPreview,
                this.pictureBoxPreview
            });

            // Add controls to form
            this.Controls.AddRange(new Control[] {
                this.textBoxUrls,
                this.buttonAddUrls,
                this.listBoxUrls,
                this.buttonRemoveUrl,
                this.buttonClearAll,
                labelOutput,
                this.textBoxOutputPath,
                this.buttonBrowseOutput,
                this.buttonDownloadAll,
                this.progressBar,
                this.labelStatus,
                this.panelPreview
            });

            // Handle form resize
            this.Resize += MainForm_Resize;

            this.ResumeLayout();
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            // Adjust preview panel position and size when form is resized
            int formWidth = this.ClientSize.Width;
            int formHeight = this.ClientSize.Height;

            // Adjust main controls width
            int mainControlsWidth = Math.Max(300, formWidth - 420);

            textBoxUrls.Width = mainControlsWidth - 120;
            listBoxUrls.Width = mainControlsWidth;
            textBoxOutputPath.Width = mainControlsWidth - 80;
            progressBar.Width = mainControlsWidth;
            labelStatus.Width = mainControlsWidth;

            // Adjust button positions
            buttonAddUrls.Left = textBoxUrls.Right + 10;
            buttonBrowseOutput.Left = textBoxOutputPath.Right + 10;

            // Adjust preview panel
            panelPreview.Left = mainControlsWidth + 20;
            panelPreview.Width = Math.Max(300, formWidth - mainControlsWidth - 40);
            panelPreview.Height = formHeight - 30;

            // Adjust preview controls
            labelPreview.Width = panelPreview.Width - 20;
            pictureBoxPreview.Width = panelPreview.Width - 20;
            pictureBoxPreview.Height = panelPreview.Height - 60;
        }

        private void InitializeHttpClient()
        {
            httpClient.DefaultRequestHeaders.Add("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            httpClient.Timeout = TimeSpan.FromMinutes(5);
        }

        private void ButtonAddUrls_Click(object sender, EventArgs e)
        {
            string urlsText = textBoxUrls.Text.Trim();
            if (!string.IsNullOrEmpty(urlsText))
            {
                string[] urls = urlsText.Split(new char[] { '\n', '\r' },
                    StringSplitOptions.RemoveEmptyEntries);

                int addedCount = 0;
                int duplicateCount = 0;
                int invalidCount = 0;

                foreach (string url in urls)
                {
                    string trimmedUrl = url.Trim();
                    if (!string.IsNullOrEmpty(trimmedUrl))
                    {
                        if (IsValidImageUrl(trimmedUrl))
                        {
                            if (!listBoxUrls.Items.Contains(trimmedUrl))
                            {
                                listBoxUrls.Items.Add(trimmedUrl);
                                addedCount++;
                            }
                            else
                            {
                                duplicateCount++;
                            }
                        }
                        else
                        {
                            invalidCount++;
                        }
                    }
                }

                textBoxUrls.Clear();

                string statusMessage = $"Added {addedCount} URLs. Total: {listBoxUrls.Items.Count}";
                if (duplicateCount > 0)
                    statusMessage += $" (Skipped {duplicateCount} duplicates)";
                if (invalidCount > 0)
                    statusMessage += $" (Skipped {invalidCount} invalid URLs)";

                labelStatus.Text = statusMessage;

                if (invalidCount > 0)
                {
                    MessageBox.Show($"Skipped {invalidCount} invalid URLs. Only image URLs with extensions (jpg, jpeg, png, gif, bmp, webp) are accepted.",
                        "Invalid URLs", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private async void ListBoxUrls_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxUrls.SelectedItem != null)
            {
                string selectedUrl = listBoxUrls.SelectedItem.ToString();
                await LoadPreviewImage(selectedUrl);
            }
            else
            {
                // Clear preview when no selection
                pictureBoxPreview.Image?.Dispose();
                pictureBoxPreview.Image = null;
                labelPreview.Text = "Click on a URL to preview image";
            }
        }

        private async Task LoadPreviewImage(string url)
        {
            try
            {
                labelPreview.Text = "Loading preview...";
                pictureBoxPreview.Image?.Dispose();
                pictureBoxPreview.Image = null;

                // Load image from URL
                byte[] imageBytes = await httpClient.GetByteArrayAsync(url);
                using (var ms = new MemoryStream(imageBytes))
                {
                    Image image = Image.FromStream(ms);
                    pictureBoxPreview.Image = new Bitmap(image); // Create a copy
                }

                // Update label with image info
                if (pictureBoxPreview.Image != null)
                {
                    string fileName = GetFileNameFromUrl(url);
                    labelPreview.Text = $"{fileName} ({pictureBoxPreview.Image.Width}x{pictureBoxPreview.Image.Height})";
                }
            }
            catch (Exception ex)
            {
                pictureBoxPreview.Image?.Dispose();
                pictureBoxPreview.Image = null;
                labelPreview.Text = $"Failed to load preview: {ex.Message}";
            }
        }

        private void ListBoxUrls_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                ButtonRemoveUrl_Click(sender, e);
            }
        }

        private void ButtonRemoveUrl_Click(object sender, EventArgs e)
        {
            if (listBoxUrls.SelectedItems.Count > 0)
            {
                var itemsToRemove = new List<object>();
                foreach (object item in listBoxUrls.SelectedItems)
                {
                    itemsToRemove.Add(item);
                }

                foreach (object item in itemsToRemove)
                {
                    listBoxUrls.Items.Remove(item);
                }

                labelStatus.Text = $"Removed {itemsToRemove.Count} URLs. Total: {listBoxUrls.Items.Count}";

                // Clear preview if no items selected
                if (listBoxUrls.SelectedItems.Count == 0)
                {
                    pictureBoxPreview.Image?.Dispose();
                    pictureBoxPreview.Image = null;
                    labelPreview.Text = "Click on a URL to preview image";
                }
            }
        }

        private void ButtonClearAll_Click(object sender, EventArgs e)
        {
            if (listBoxUrls.Items.Count > 0)
            {
                var result = MessageBox.Show("Are you sure you want to clear all URLs?",
                    "Clear All", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    listBoxUrls.Items.Clear();
                    labelStatus.Text = "All URLs cleared.";

                    // Clear preview
                    pictureBoxPreview.Image?.Dispose();
                    pictureBoxPreview.Image = null;
                    labelPreview.Text = "Click on a URL to preview image";
                }
            }
        }

        private void ButtonBrowseOutput_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
            {
                folderDialog.Description = "Select output folder for downloaded images";
                folderDialog.SelectedPath = textBoxOutputPath.Text;

                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    textBoxOutputPath.Text = folderDialog.SelectedPath;
                }
            }
        }

        private async void ButtonDownloadAll_Click(object sender, EventArgs e)
        {
            if (listBoxUrls.Items.Count == 0)
            {
                MessageBox.Show("No URLs to download!", "No URLs",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string outputPath = textBoxOutputPath.Text.Trim();
            if (string.IsNullOrEmpty(outputPath))
            {
                MessageBox.Show("Please select an output folder!", "No Output Folder",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // Create output directory if it doesn't exist
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // Disable controls during download
                SetControlsEnabled(false);

                progressBar.Maximum = listBoxUrls.Items.Count;
                progressBar.Value = 0;

                int successCount = 0;
                int failCount = 0;

                for (int i = 0; i < listBoxUrls.Items.Count; i++)
                {
                    string url = listBoxUrls.Items[i].ToString();
                    labelStatus.Text = $"Downloading {i + 1} of {listBoxUrls.Items.Count}: {Path.GetFileName(url)}";

                    try
                    {
                        await DownloadImage(url, outputPath);
                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        // Log error but continue with other downloads
                        Console.WriteLine($"Failed to download {url}: {ex.Message}");
                    }

                    progressBar.Value = i + 1;
                    Application.DoEvents(); // Update UI
                }

                labelStatus.Text = $"Download completed! Success: {successCount}, Failed: {failCount}";

                if (successCount > 0)
                {
                    var result = MessageBox.Show($"Download completed!\n\nSuccess: {successCount}\nFailed: {failCount}\n\nOpen output folder?",
                        "Download Complete", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                    if (result == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", outputPath);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error during download: {ex.Message}", "Download Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                labelStatus.Text = "Download failed!";
            }
            finally
            {
                SetControlsEnabled(true);
                progressBar.Value = 0;
            }
        }

        private async Task DownloadImage(string url, string outputPath)
        {
            try
            {
                byte[] imageBytes = await httpClient.GetByteArrayAsync(url);

                // Generate filename from URL
                string fileName = GetFileNameFromUrl(url);
                string fullPath = Path.Combine(outputPath, fileName);

                // Handle duplicate filenames
                int counter = 1;
                string originalFileName = Path.GetFileNameWithoutExtension(fileName);
                string extension = Path.GetExtension(fileName);

                while (File.Exists(fullPath))
                {
                    fileName = $"{originalFileName}_{counter}{extension}";
                    fullPath = Path.Combine(outputPath, fileName);
                    counter++;
                }

                await Task.Run(() => File.WriteAllBytes(fullPath, imageBytes));
            }
            catch (HttpRequestException ex)
            {
                throw new Exception($"Network error: {ex.Message}");
            }
            catch (TaskCanceledException)
            {
                throw new Exception("Download timeout");
            }
            catch (Exception ex)
            {
                throw new Exception($"Download failed: {ex.Message}");
            }
        }

        private string GetFileNameFromUrl(string url)
        {
            try
            {
                Uri uri = new Uri(url);
                string fileName = Path.GetFileName(uri.LocalPath);

                // If no filename in URL, generate one
                if (string.IsNullOrEmpty(fileName) || !fileName.Contains("."))
                {
                    string extension = GetImageExtensionFromUrl(url);
                    fileName = $"image_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid().ToString("N").Substring(0, 8)}{extension}";
                }

                // Remove invalid characters
                string invalidChars = new string(Path.GetInvalidFileNameChars());
                foreach (char c in invalidChars)
                {
                    fileName = fileName.Replace(c, '_');
                }

                return fileName;
            }
            catch
            {
                return $"image_{DateTime.Now:yyyyMMdd_HHmmss}.jpg";
            }
        }

        private string GetImageExtensionFromUrl(string url)
        {
            string[] extensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };

            foreach (string ext in extensions)
            {
                if (url.ToLower().Contains(ext))
                    return ext;
            }

            return ".jpg"; // Default extension
        }

        private bool IsValidImageUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
                return false;

            try
            {
                Uri uri = new Uri(url);
                if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
                    return false;

                string[] validExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                string lowerUrl = url.ToLower();

                return validExtensions.Any(ext => lowerUrl.Contains(ext)) ||
                       lowerUrl.Contains("image") ||
                       lowerUrl.Contains("photo") ||
                       lowerUrl.Contains("pic");
            }
            catch
            {
                return false;
            }
        }

        private void SetControlsEnabled(bool enabled)
        {
            buttonAddUrls.Enabled = enabled;
            buttonRemoveUrl.Enabled = enabled;
            buttonClearAll.Enabled = enabled;
            buttonDownloadAll.Enabled = enabled;
            buttonBrowseOutput.Enabled = enabled;
            textBoxUrls.Enabled = enabled;
            listBoxUrls.Enabled = enabled;
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            // Dispose preview image
            pictureBoxPreview.Image?.Dispose();
            httpClient?.Dispose();
            base.OnFormClosed(e);
        }
    }

    // Program entry point
    
}

Chúc mọi người thành công. Mọi người có thể Download Full Source Code bên dưới để về tìm hiểu và vọc vạch nhé.

Download Source Code


03 February, 2025

[CSHARP] Count down Number with Simple Observer Pattern

February 03, 2025 Posted by Tôi Hùng ✅ , 4 comments
Xin chào các bạn, bài viết hôm nay mình sẽ tiếp tục hướng dẫn các bạn sử dụng Observer Pattern bằng một ví dụ đơn giản tăng giảm số lượng trên C#, Winform.

[C#] Ứng dụng ví dụ Simple Observer Pattern tăng giảm số lượng trên winform

Vậy Observer Pattern là gì?

Observer Pattern là một trong những Pattern thuộc nhóm hành vi (Behavior Pattern).

Nó định nghĩa mối phụ thuộc một – nhiều giữa các đối tượng để khi mà một đối tượng có sự thay đổi trạng thái, tất các thành phần phụ thuộc của nó sẽ được thông báo và cập nhật một cách tự động.

Các bạn có thể xem ví dụ ở bên dưới này là dễ hiểu nhất.

Khi mình thay đổi giá trị trên Form1, thì Form2, form3 hay form này có đăng ký Observer thì đều cập nhật lại trạng thái của chúng.

Hình ảnh demo.


Ở ví dụ trên các bạn thấy, mình thay đổi giá trị ở form này thì ngay lập tức, các giá trị ở form khác đều thay đổi.

Nếu bạn nào đã từng làm việc về State giống trong React hay Flutter thì các bạn sẽ thấy nó thay đổi giống vậy.

Đầu tiên các bạn tạo cho mình một class IObserver.cs

public interface IObserver
{
    void Update(int count);
}

Tiếp theo một class ISubject.cs

public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void UnregisterObserver(IObserver observer);
    void notifyObserver(int count);
}

Tiếp tục tạo một class Counter.cs để tăng giảm số lượng.

public class Counter : ISubject
{
	private List<IObserver> observers;
	private int count;

	public Counter()
	{
	    observers = new List<IObserver>();
	    count = 0;
	}

	public void Increment()
	{
	    count++;
	    notifyObserver(count);
	}

	public void Decrement()
	{
	    if (count > 0)
	    {
	        count--;
	        notifyObserver(count);
	    }
	        
	}
	    

	public void notifyObserver(int count)
	{
	    foreach (IObserver ob in observers)
	    {
	        ob.Update(count);
	    }
	}

	public void RegisterObserver(IObserver observer)
	{
	    observers.Add(observer);
	}

	public void UnregisterObserver(IObserver observer)
	{
	    observers.Remove(observer);
	}
}

Mình bắt đầu code cho ba form: Form1, Form2 và Form3

Source code Form1.cs

public partial class Form1 : Form
{
    private Counter counter;
    public Form1()
    {
        counter = new Counter();
        InitializeComponent();
        var frm = new Form2(counter);
        frm.Show();
        counter.RegisterObserver(frm);

        var frmRect = new FrmRect(counter);
        frmRect.Show();
        counter.RegisterObserver(frmRect);
    }

    private void btnDecrement_Click(object sender, EventArgs e)
    {
        counter.Decrement();
    }

    private void btnIncrement_Click(object sender, EventArgs e)
    {
        counter.Increment();
    }
}

Source code Form2.cs

public partial class Form2 : Form, IObserver
{
    Counter counter1;
    public Form2(Counter counter)
    {
        InitializeComponent();
        this.counter1 = counter;
        this.FormClosing += Form2_FormClosing;
    }

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        counter1.UnregisterObserver(this);
    }

    public void Update(int count)
    {
        label1.Text = $"{count}";
    }
}

Và cuối cùng là source code cho Form3.cs

public partial class FrmRect : Form, IObserver
{
    Counter counter1;
    public FrmRect(Counter counter)
    {
        InitializeComponent();
        this.counter1 = counter;
        this.FormClosing += FrmRect_FormClosing;
    }

    private void FrmRect_FormClosing(object sender, FormClosingEventArgs e)
    {
        counter1.UnregisterObserver(this);
    }

    public void Update(int count)
    {
        updateRectange(count);
    }

    private void updateRectange(int count)
    {
        this.CreateGraphics().Clear(this.BackColor);
        SolidBrush solidBrush = new SolidBrush(Color.Red);
        Graphics graphics;
        graphics = this.CreateGraphics();
        graphics.FillRectangle(solidBrush, new Rectangle(0,0, count * 10, count *10));
        solidBrush.Dispose();
        graphics.Dispose();

    }
}

Như vậy đã hoàn thành ba mẫu giao diện như hình ảnh demo phía trên, mọi người muốn áp dụng thủ thuật nào vào chương trình để thuận lợi nhất thì có thể áp dụng đoạn code mình mong muốn nhé.

Các bạn thấy, khi mình mở Form2FormRect (form3) thì chúng ta gọi hàm RegisterObserver, và trong 2 form đó khi đóng lại, các bạn nhớ gọi hàm UnRegisterObserver.

Mô hình observer pattern này, hoạt động giống như khi các bạn đăng ký một topic nào đó để nhận thông báo tin nhắn. Và khi không muốn nhận nữa chúng ta chỉ cần Unsubcribe là xong.

Các bạn có thể ứng dụng pattern này trong form CRUD, khi các bạn mở một hộp thoại dialog lên để nhập liệu, khi bấm lưu lưu hay cập nhật chỉnh sửa dữ liệu

=> Form danh sách ở dưới cũng được cập nhật theo.

Chúc mọi người thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE

Chúc mọi người thành công.

[CSHARP] Tạo mã thanh toán VietQR không sử dụng API

February 03, 2025 Posted by Tôi Hùng ✅ , , , No comments
Chào mọi người, hôm nay mình sẽ hướng dẫn mọi người tạo mã VietQR Pay không cần lấy thông tin API nhanh nhất trong lập trình ứng dụng Winform.

Mã thanh toán VietQR giờ quá phổ biến ở nước ta, hầu như tất cả các ngân hàng hiện tại đều có thể thanh toán qua mã VietQR.

Bài viết này, hướng dẫn các bạn tạo mã thanh toán VietQR một cách dễ dàng trên C#, mà không cần phụ thuộc vào đơn vị thứ 3 qua API.

Video hướng dẫn step by step các bước thực hiện:


Chúng ta bắt đầu từng bước để thiết lập chương trình nhé.

Bước 1. Các bạn cần cài đặt thư viện VietQRHelper từ Nuget.

NuGet\Install-Package VietQRHelper -Version 1.0.0

Bước 2. Source code tạo mã VietQR đơn giản:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VietQRHelper;

namespace TaoMaVietQR
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void picQRPay_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            var qrPay = QRPay.InitVietQR(
                bankBin: BankApp.BanksObject[BankKey.VIETCOMBANK].bin,
                bankNumber: "0721000584901", // Số tài khoản
                amount: "20000", // Số tiền
                purpose: "Donate Hung.Pro.VN"  // Nội dung chuyển tiền,
               
              );
            var content = qrPay.Build();

            var imageQR = QRCodeHelper.TaoVietQRCodeImage(content);
            picQRPay.Image = imageQR;
        }
    }
}

Như vậy đã hoàn thành việc setup chương trình Winform tạo mã VietQR Pay đơn giản cho người dùng.


PassWord Unzip: HUNG.PRO.VN

12 January, 2025

[PROGRAM] DUAL MESSENGER TOOLKIT

January 12, 2025 Posted by Tôi Hùng ✅ , No comments
Xin chào mọi người, hôm nay ngồi đọc bài bên laptrinhvb.net có bán chương trình đăng nhập nhiều tài khoản ZALO, TELEGRAM cùng lúc trên máy tính WINDOWS mà không bị dính lỗi đăng nhập nhiều tài khoản.

Nên mình chia sẽ lại cho mọi người được biết và nếu có nhu cầu sữ dụng thì liên hệ với quản trị bên trang đó để mua nhé.

Chúng ta bắt đầu nhé.


Phía trên là hình ảnh demo chương trình, chương trình được viết từ ngôn ngữ CSHARP

VIDEO DEMO.


Lợi ích nổi bật:

✔️ Đăng nhập đa tài khoản: Sử dụng nhiều tài khoản Zalo và Telegram trên cùng một máy tính mà không gặp rắc rối.

✔️ Tăng hiệu suất làm việc: Quản lý công việc, chăm sóc khách hàng, và giao tiếp cá nhân dễ dàng hơn bao giờ hết.

✔️ Tiết kiệm thời gian: Không cần phải mở nhiều trình duyệt hoặc phần mềm, chỉ cần một công cụ duy nhất.

✔️ An toàn và bảo mật: Không lưu trữ thông tin đăng nhập, đảm bảo an toàn tuyệt đối cho dữ liệu cá nhân.

???? Giá chỉ 20K – Quá rẻ cho một giải pháp tiện ích! ????

Với Dual Messenger Toolkit, bạn không cần phải chi hàng trăm ngàn để mua phần mềm phức tạp. Chỉ với 20K, bạn đã sở hữu một công cụ mạnh mẽ, đáp ứng mọi nhu cầu đa nhiệm của bạn.

???? Ai nên sử dụng?

Chủ shop online: Dễ dàng quản lý các tài khoản bán hàng, tư vấn khách hàng nhanh chóng.

Người làm việc văn phòng: Phân tách tài khoản công việc và cá nhân rõ ràng.

Người dùng cá nhân: Giữ liên lạc với gia đình và bạn bè mà không bỏ lỡ tin nhắn quan trọng.

???? Cách mua và sử dụng:

1️⃣ Liên hệ ngay để mua tool với giá chỉ 20K.

2️⃣ Nhận file cài đặt và hướng dẫn chi tiết từ chúng tôi.

3️⃣ Kích hoạt và trải nghiệm ngay!

???? Inbox ngay để được hỗ trợ và nhận tool trong 5 phút!
Dual Messenger Toolkit – Công cụ đơn giản nhưng hiệu quả để tối ưu hóa cách bạn sử dụng Zalo và Telegram.

Chúc mọi người thành công và sữ dụng chương trình này một cách hợp lý nhé.
 
Người sữ dụng nên cân nhắc khi sữ dụng chương trình này nhé, và tránh dùng để spam hay đi lừa người dùng

25 December, 2024

[CSHARP] Fake IP HTTP Request

December 25, 2024 Posted by Tôi Hùng ✅ , No comments
Bài viết này mình sẽ hướng dẫn mọi người viết chương trình FAKE IP HTTP Request mới nhất cho mọi người, vừa lấy dữ liệu IP và tự thay đổi địa chỉ IP nếu bạn muốn.

Vậy Fake Ip là gì?

Fake IP là việc kết nối đến một trang web bất kỳ thông qua một Server Proxy, giúp che giấu địa chỉ IP thật của máy tính và thay vào đó là một dải địa chỉ IP ảo, hoặc IP của một quốc gia nào đó. Trong mạng LAN Server Proxy là máy chủ nối chung gian giữa các máy thành viên trong mạng LAN và internet.

Mình ví dụ:

Nếu bạn nào đang truy cập những website, mình website đó chặn IP đến từ Việt Nam, thì mình có nó để truy cập website.

Hoặc nếu các bạn nào dùng HttpRequest để truy cập website lấy dữ liệu hàng loạt, khi truy cập website liên tục, website đó sẽ chặn IP của bạn lại.

Và cách để các bạn có thể tiếp tục truy cập để là mình phải Fake IP để qua mặt những website này.

Thư viện xNet có hỗ trợ bạn truy cập website qua Proxy với nhiều giao thức: https, Sock4, Sock5...

Trong bài viết này, mình sử dụng thư viện Xnet, HttpRequest qua giao thức Sock5.

Đầu tiên, các bạn cần truy cập website sau:

http://spys.one/en/socks-proxy-list/
Website này, cung cấp cho bạn danh sách những Proxy Sock5 miễn phí và được cập nhật liên tục để các bạn có thể Fake IP.
[CSHARP] Fake IP HTTP Request

Các bạn có thể truy cập website:
https://whoer.net
Để xem Ip của mình đang request đến:

Dưới đây là IP Address hiện tại của mình khi chưa sử dụng Proxy để Fake IP.
[CSHARP] Fake IP HTTP Request

Dưới đây là giao diện ứng dụng Fake IP C#:
[CSHARP] Fake IP HTTP Request

Giao diện trên chúng ta thấy, mình đã fake IP thành công, và nó hiện thỉ cho chúng ta thấy chúng ta đang sử dụng IP đến từ Germany.

Source code Fake IP Proxy C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using xNet;

namespace FakeIP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_get_Click(object sender, EventArgs e)
        {
            try
            {
                HttpRequest httpRequest = new HttpRequest();
                httpRequest.Cookies = new CookieDictionary();
                httpRequest.UserAgent = Http.ChromeUserAgent();
                httpRequest.Proxy = Socks5ProxyClient.Parse(txt_sock5.Text.Trim());
                string html = httpRequest.Get(txt_website.Text.Trim()).ToString();
                webBrowser1.DocumentText = html;
               

            }
            catch (Exception ex)
            {
                webBrowser1.DocumentText = ex.Message;
            }
        }
    }
}

Như vậy đã hoàn thành việc trên, chúc mọi người thành công.

24 December, 2024

[CSHARP] Find Position Keywords in Google Search

December 24, 2024 Posted by Tôi Hùng ✅ , No comments
xin chào mọi người, bài viết này mình sẽ hướng dẫn các bạn viết chương trình tìm kiếm thứ hạng từ khóa trên GOOGLE SEARCH một cách đơn giản nhất.

HOW TO FIND POSITON KEYWORDS IN GOOGLE PROGRAMMING WITH CSHARP

Keyword là gì?
Keywords có nghĩa là từ khóa hay cụm từ khóa, là những ký tự mà dựa trên những truy vấn của người dùng mà các webmaster làm căn cứ để lên kế hoạch cho chiến dịch tối ưu hóa website với mục đích tiếp cận khách hàng càng nhiều càng tốt.

Thuật Ngữ KEYWORD
Với mỗi chiến dịch lập hệ thống Keywords khác nhau thì mức độ thành công của các webmaster khác nhau. Một chiến dịch tạo dựng hệ thống Keywords thành công được đánh giá bởi thứ hạng của website đó trên bảng xếp hạng các kết quả tìm kiếm và điều mấu chốt ở đây là tỷ lệ chuyển đổi từ khách thăm website thành khách hàng.


+ Bây giờ, mình xin hướng dẫn các bạn cách làm thế nào để lấy được từ khóa của google.
Đầu tiên, các bạn có thể tham khảo dường dẫn Url sau:
https://google.com.vn/search?num=100&q={0}&btnG=Search

Trong đó, num =100 là số trang mà bạn muốn tìm kiếm để hiển thị. Ví dụ: mình muốn biết từ khóa mình SEO có đang nằm trong top thứ 100 tìm kiếm của bộ máy google hay không?

Thường thì, một trang tìm kiếm của google search sẽ hiển thị 10 kết quả tìm kiếm.

+ Khi các bạn truy vấn kết quả tìm kiếm trả về, bạn sẽ cắt element có chứa class "

" sau đó, mình sẽ đưa vào Mảng hoặc List để xử lý.

Sau đó, mình foreach kết từ từ vị trí số 1 cho đến 100, khi kết quả nào trả về có chứa đường dẫn Url của mình, ví dụ trang http://laptrinhvb.net thì mình trả về vị trí, cùng đường dẫn chứa từ khóa tại position đó.


+ Giao diện demo ứng dụng trên có thể giúp cho các bạn tìm vị trí của từ khóa google theo các google ở mỗi quốc gia khác nhau.

- Bài viết, này mình chỉ hướng dẫn các bạn các tìm 1 từ khóa, các bạn có thể tùy biến để tìm nhiều từ khóa khác nhau cùng một domain.

Đầu tiên các bạn cần tạo 1 class Keywords: để khi quét element trả về position và link url của domain trong lap trinh csharp.

Source code tạo Class Keywords C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class keyword
    {
        private string link;

        private int postion;

        public keyword()
        {

        }
        public keyword(string link, int postion)
        {
            this.Link = link;
            this.Postion = postion;
        }

        public string Link
        {
            get
            {
                return link;
            }

            set
            {
                link = value;
            }
        }

        public int Postion
        {
            get
            {
                return postion;
            }

            set
            {
                postion = value;
            }
        }
    }
}

Và tiếp đến mình sẽ code cho ứng dụng:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
//using System.Web;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
        }
        private  keyword GetPosition(string Url, string searchTerm)
        {
            keyword result = new keyword();
            string raw = comboBox1.Text + "/search?num=100&q={0}&btnG=Search";
            string search = string.Format(raw, System.Uri.EscapeDataString(searchTerm));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);
            using (HttpWebResponse  response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader  reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    
                    string html = reader.ReadToEnd();
                    result =  FindPosition(html, Url);                  
                    return result;
                }
            }
           
        } 
      private  keyword FindPosition(string html, string url)
        {
            keyword result = new keyword();
            var Webget = new HtmlWeb();
            var page = Webget.Load("https://google.com");
            page.LoadHtml(html);

            var list = page.DocumentNode.SelectNodes("//h3[@class='r']//a");
            int count = list.Count();
            int i = 0;
            foreach (var obj in list)
            {
                i++;
                if (i > count)
                {
                    break;
                }
                else
                {
                    var urls = obj.SelectSingleNode(".").Attributes["href"].Value;
                    if (urls.Contains(url) )
                    {
                        // lấy link bài viết
                        result.Link = urls;
                        // lấy được vị trí
                        result.Postion = i;
                        return result;
                    }

                }
            }
            return null;    
            
      }

        private void button1_Click(object sender, EventArgs e)
        {
            keyword ketqua = new keyword();         
            ketqua = GetPosition(txtUrl.Text,txtkeyword.Text);
         
            if(ketqua != null)
            {
                lblResult.Text = string.Format("{0}", ketqua.Postion);
                string link = ketqua.Link;
                var linkParser = new Regex(@"(?:https?://|www.)S+?&sa", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                foreach (Match m in linkParser.Matches(link))
                    link = m.Value;
                string pattern = "&sa";
                string replacement = "";
                Regex rgx = new Regex(pattern);
                string result = rgx.Replace(link, replacement);
                lblLinkResponse.Text = result;
            }else
            {
                lblResult.Text = "Từ khóa của bạn không nằm trong Top 100";
                lblLinkResponse.Text = "NaN";
            }
           
        }

        private void lblLinkResponse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(lblLinkResponse.Text);
        }
    }
}

Video DEMO Ứng Dụng.



Chúc các bạn thành công! Hãy nhớ like and share để lấy cảm hứng cho tác giả các bạn nhé.

[CSHARP] PDF counter tool, convert page size A4 to A3 files

December 24, 2024 Posted by Tôi Hùng ✅ , , No comments
Xin chào các bạn, bài viết hôm nay mình tiếp tục chia sẻ các source code phần mềm đếm số trang hàng loạt của tập tin PDF, trong một tập tin bao gồm bao nhiêu trang khổ A3, bao nhiêu trang khổ giấy A4.
[CSHARP] PDF counter tool, convert page size A4 to A3 files

Khi các bạn muốn đếm file PDF trong tất cả các folder thư mục bao gồm bao nhiêu trang A4, bao nhiêu trang A3.

Và các bạn có thể dễ dàng đồng bộ chuyển đổi kích thước khổ giấy từ A4 sang khổ giấy A3.

Tính năng nổi bật

1 Đếm số trang chính xác:
  • Phần mềm hỗ trợ đếm chính xác số trang trong các tệp PDF, bất kể kích thước file lớn hay nhỏ.

2 Nhận diện kích thước trang A4:
  • Không chỉ đếm trang, phần mềm còn kiểm tra và phân loại các trang có kích thước A4, giúp bạn dễ dàng thống kê hoặc in ấn.

3 Hỗ trợ nhiều tệp PDF:
  • Bạn có thể tải lên nhiều tệp PDF cùng lúc để phần mềm xử lý, tiết kiệm tối đa thời gian.

4 Giao diện thân thiện, dễ sử dụng:
  • Với thiết kế giao diện đơn giản, trực quan, bạn không cần phải là chuyên gia công nghệ cũng có thể sử dụng một cách dễ dàng.

5 Tốc độ xử lý nhanh:
  • Phần mềm được tối ưu hóa để xử lý tệp PDF nhanh chóng, ngay cả với những tài liệu có hàng nghìn trang.

Lợi ích khi sử dụng

  • Tiết kiệm thời gian và công sức khi đếm thủ công.
  • Phù hợp cho doanh nghiệp in ấn, văn phòng, và cá nhân cần xử lý tài liệu PDF thường xuyên.
  • Đảm bảo tính chính xác và chuyên nghiệp khi làm việc với tài liệu PDF.
  • Ứng dụng thực tế
  • Nhà in: Kiểm tra và báo giá dịch vụ in ấn theo số lượng trang A4.
  • Văn phòng: Quản lý tài liệu PDF dễ dàng hơn.
  • Cá nhân: Xác định số trang để gửi in, nộp hồ sơ trực tuyến hoặc kiểm tra tài liệu.

Chúc mọi người thành công với tiện ích này.

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

02 November, 2024

[CSHARP] How to create qrcode style in winform

November 02, 2024 Posted by Trick Blogger , 1 comment
Chào mọi người, bài viết hôm nay mình hướng dẫn các bạn tạo sử dụng API request đến QRcode monkey để tạo mã qr code với nhiều mẫu mã khác nhau.

[C#] Hướng dẫn tạo mã QRcode Style trên winform

QRCode Monkey là một trong những công cụ trực tuyến hàng đầu và miễn phí để tạo mã QR với chất lượng cao và tính năng tùy chỉnh đa dạng.
 
Website này cho phép người dùng tạo mã QR cho nhiều mục đích khác nhau như URL, văn bản, email, thông tin liên lạc, vị trí và thậm chí cả thanh toán.

Điểm nổi bật của QRCode Monkey là khả năng tùy biến mạnh mẽ – người dùng có thể điều chỉnh màu sắc, kiểu dáng, logo, và chọn các mẫu độc đáo để làm cho mã QR phù hợp với thương hiệu hoặc phong cách riêng.

Ngoài ra, QRCode Monkey còn hỗ trợ xuất mã QR với độ phân giải cao và các định dạng như PNG, SVG, PDF, và EPS, giúp mã QR của bạn rõ nét trên mọi thiết bị hoặc tài liệu in ấn.
Website cũng bảo mật và không yêu cầu tài khoản, mang lại sự tiện lợi và an tâm cho người dùng khi sử dụng.

Đây là công cụ lý tưởng cho các cá nhân, doanh nghiệp và nhà tiếp thị muốn tối ưu hóa và cá nhân hóa mã QR cho các chiến dịch của mình.

Dưới đây, là hình ảnh demo ứng dụng: (https://www.qrcode-monkey.com/)

Source code C#:

Tạo class QRStyle.cs

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Drawing;
using System.Threading.Tasks;


namespace QRCodeStyle
{
    #region Enums
    public static class QRCodePatterns
    {
        public enum Body
        {
            Square,
            Mosaic,
            Dot,
            Circle,
            CircleZebra,
            CircleZebraVertical,
            CircleZebraHorizontal,
            Circular,
            EdgeCut,
            EdgeCutSmooth,
            Japanese,
            Leaf,
            Pointed,
            PointedEdgeCut,
            PointedIn,
            PointedInSmooth,
            PointedSmooth,
            Round,
            RoundedIn,
            RoundedInSmooth,
            RoundedPointed,
            Star,
            Diamond
        }


        public enum Eye
        {
            Frame0,
            Frame1,
            Frame2,
            Frame3,
            Frame4,
            Frame5,
            Frame6,
            Frame7,
            Frame8,
            Frame9,
            Frame10,
            Frame11,
            Frame12,
            Frame13,
            Frame14,
            Frame15,
            Frame16
        }

        public enum Ball
        {
            Ball0,
            Ball1,
            Ball2,
            Ball3,
            Ball4,
            Ball5,
            Ball6,
            Ball7,
            Ball8,
            Ball9,
            Ball10,
            Ball11,
            Ball12,
            Ball13,
            Ball14,
            Ball15,
            Ball16,
            Ball17,
            Ball18
        }

        public enum Gradient
        {
            Linear,
            Radial
        }

        public enum Logo
        {
            Default,
            Clean
        }
    }
    #endregion

    #region Pattern Converters
    public static class PatternConverter
    {
        public static string GetBodyString(QRCodePatterns.Body pattern)
        {
            switch (pattern)
            {
                case QRCodePatterns.Body.Square: return "square";
                case QRCodePatterns.Body.Mosaic: return "mosaic";
                case QRCodePatterns.Body.Dot: return "dot";
                case QRCodePatterns.Body.Circle: return "circle";
                case QRCodePatterns.Body.CircleZebraVertical: return "circle-zebra-vertical";
                case QRCodePatterns.Body.CircleZebraHorizontal: return "circle-zebra-horizontal";
                case QRCodePatterns.Body.Circular: return "circular";
                case QRCodePatterns.Body.EdgeCut: return "edge-cut";
                case QRCodePatterns.Body.EdgeCutSmooth: return "edge-cut-smooth";
                case QRCodePatterns.Body.Japanese: return "japnese";
                case QRCodePatterns.Body.Leaf: return "leaf";
                case QRCodePatterns.Body.Pointed: return "pointed";
                case QRCodePatterns.Body.PointedEdgeCut: return "pointed-edge-cut";
                case QRCodePatterns.Body.PointedIn: return "pointed-in";
                case QRCodePatterns.Body.PointedInSmooth: return "pointed-in-smooth";
                case QRCodePatterns.Body.PointedSmooth: return "pointed-smooth";
                case QRCodePatterns.Body.Round: return "round";
                case QRCodePatterns.Body.RoundedIn: return "rounded-in";
                case QRCodePatterns.Body.RoundedInSmooth: return "rounded-in-smooth";
                case QRCodePatterns.Body.RoundedPointed: return "rounded-pointed";
                case QRCodePatterns.Body.Star: return "star";
                case QRCodePatterns.Body.Diamond: return "diamond";
                default: return "square";
            }

        }

        public static string GetEyeString(QRCodePatterns.Eye eye)
        {
            return "frame" + ((int)eye).ToString();
        }

        public static string GetBallString(QRCodePatterns.Ball ball)
        {
            return "ball" + ((int)ball).ToString();
        }

        public static string GetGradientString(QRCodePatterns.Gradient gradient)
        {
            return gradient.ToString().ToLower();
        }

        public static string GetLogoString(QRCodePatterns.Logo logo)
        {
            return logo.ToString().ToLower();
        }
    }
    #endregion

    #region Configuration Classes
    public class QRConfig
    {
        private QRCodePatterns.Body _bodyPattern;
        private QRCodePatterns.Eye _eyePattern;
        private QRCodePatterns.Ball _ballPattern;
        private QRCodePatterns.Gradient _gradientPattern;
        private QRCodePatterns.Logo _logoPattern;

        private string _body;
        private string _eye;
        private string _eyeBall;
        private string _gradientType;
        private string _logoMode;

        public QRCodePatterns.Body BodyPattern
        {
            get { return _bodyPattern; }
            set
            {
                _bodyPattern = value;
                _body = PatternConverter.GetBodyString(value);
            }
        }

        public QRCodePatterns.Eye EyePattern
        {
            get { return _eyePattern; }
            set
            {
                _eyePattern = value;
                _eye = PatternConverter.GetEyeString(value);
            }
        }

        public QRCodePatterns.Ball BallPattern
        {
            get { return _ballPattern; }
            set
            {
                _ballPattern = value;
                _eyeBall = PatternConverter.GetBallString(value);
            }
        }

        public QRCodePatterns.Gradient GradientPattern
        {
            get { return _gradientPattern; }
            set
            {
                _gradientPattern = value;
                _gradientType = PatternConverter.GetGradientString(value);
            }
        }

        public QRCodePatterns.Logo LogoPattern
        {
            get { return _logoPattern; }
            set
            {
                _logoPattern = value;
                _logoMode = PatternConverter.GetLogoString(value);
            }
        }

        public string body { get { return _body; } }
        public string eye { get { return _eye; } }
        public string eyeBall { get { return _eyeBall; } }
        public string[] erf1 { get; set; }
        public string[] erf2 { get; set; }
        public string[] erf3 { get; set; }
        public string[] brf1 { get; set; }
        public string[] brf2 { get; set; }
        public string[] brf3 { get; set; }
        public string bodyColor { get; set; }
        public string bgColor { get; set; }
        public string eye1Color { get; set; }
        public string eye2Color { get; set; }
        public string eye3Color { get; set; }
        public string eyeBall1Color { get; set; }
        public string eyeBall2Color { get; set; }
        public string eyeBall3Color { get; set; }
        public string gradientColor1 { get; set; }
        public string gradientColor2 { get; set; }
        public string gradientType { get { return _gradientType; } }
        public bool gradientOnEyes { get; set; }
        public string logo { get; set; }
        public string logoMode { get { return _logoMode; } }

        public QRConfig()
        {
            BodyPattern = QRCodePatterns.Body.Square;
            EyePattern = QRCodePatterns.Eye.Frame0;
            BallPattern = QRCodePatterns.Ball.Ball0;
            GradientPattern = QRCodePatterns.Gradient.Linear;
            LogoPattern = QRCodePatterns.Logo.Default;

            erf1 = new string[] { };
            erf2 = new string[] { };
            erf3 = new string[] { };
            brf1 = new string[] { };
            brf2 = new string[] { };
            brf3 = new string[] { };

            bodyColor = "#000000";
            bgColor = "#FFFFFF";
            eye1Color = "#000000";
            eye2Color = "#000000";
            eye3Color = "#000000";
            eyeBall1Color = "#000000";
            eyeBall2Color = "#000000";
            eyeBall3Color = "#000000";
            gradientOnEyes = false;
            logo = "";
        }
    }

    public class QRRequest
    {
        public string data { get; set; }
        public QRConfig config { get; set; }
        public int size { get; set; }
        public string download { get; set; }
        public string file { get; set; }

        public QRRequest()
        {
            size = 1000;
            download = "imageUrl";
            file = "png";
        }
    }
    #endregion

    #region QR Code Generator
    public class QRGenerator
    {
        private const string API_URL = "https://api.qrcode-monkey.com/qr/custom";
        private Dictionary<int, QRConfig> customStyles;

        public QRGenerator()
        {
            customStyles = new Dictionary<int, QRConfig>();
            InitializeDefaultStyles();
        }

        private void InitializeDefaultStyles()
        {
            customStyles[1] = new QRConfig
            {
                BodyPattern = QRCodePatterns.Body.Square,
                EyePattern = QRCodePatterns.Eye.Frame13,
                BallPattern = QRCodePatterns.Ball.Ball14,
                bodyColor = "#000000",
                bgColor = "#FFFFFF",
                eye1Color = "#021326",
                eye2Color = "#021326",
                eye3Color = "#021326",
                eyeBall1Color = "#074f03",
                eyeBall2Color = "#074f03",
                eyeBall3Color = "#074f03",
                gradientColor1 = "#12a637",
                gradientColor2 = "#0b509e",
                GradientPattern = QRCodePatterns.Gradient.Linear,
                gradientOnEyes = true
            };

        }

        public void AddStyle(int styleNumber, QRConfig config)
        {
            if (customStyles.ContainsKey(styleNumber))
            {
                customStyles[styleNumber] = config;
            }
            else
            {
                customStyles.Add(styleNumber, config);
            }
        }

        public class GenerationResult
        {
            public bool Success { get; set; }
            public string Message { get; set; }
            public string ImageUrl { get; set; }
        }

        public GenerationResult Generate(string data, int styleNumber, string savePath)
        {
            try
            {
                QRConfig config = customStyles.ContainsKey(styleNumber)
                    ? customStyles[styleNumber]
                    : customStyles[1];

                var request = new QRRequest
                {
                    data = data,
                    config = config
                };

                var serializer = new JavaScriptSerializer();
                string jsonRequest = serializer.Serialize(request);

                var webRequest = (HttpWebRequest)WebRequest.Create(API_URL);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonRequest);
                }

                using (var response = (HttpWebResponse)webRequest.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string jsonResponse = reader.ReadToEnd();
                    var responseData = serializer.Deserialize<Dictionary<string, object>>(jsonResponse);

                    if (responseData.ContainsKey("imageUrl"))
                    {
                        string imageUrl = "http:" + responseData["imageUrl"].ToString();

                        if (!string.IsNullOrEmpty(savePath))
                        {
                            using (WebClient webClient = new WebClient())
                            {
                                webClient.DownloadFile(imageUrl, savePath);
                            }
                        }

                        return new GenerationResult
                        {
                            Success = true,
                            Message = "Success",
                            ImageUrl = imageUrl
                        };
                    }
                }

                return new GenerationResult
                {
                    Success = false,
                    Message = "Failed to get image URL",
                    ImageUrl = null
                };
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    return new GenerationResult
                    {
                        Success = false,
                        Message = "Error: " + reader.ReadToEnd(),
                        ImageUrl = null
                    };
                }
            }
            catch (Exception ex)
            {
                return new GenerationResult
                {
                    Success = false,
                    Message = "Error: " + ex.Message,
                    ImageUrl = null
                };
            }
        }
        public Image Generate(string data, int styleNumber)
        {
            try
            {
                QRConfig config = customStyles.ContainsKey(styleNumber)
                    ? customStyles[styleNumber]
                    : customStyles[1];

                var request = new QRRequest
                {
                    data = data,
                    config = config
                };

                var serializer = new JavaScriptSerializer();
                string jsonRequest = serializer.Serialize(request);

                var webRequest = (HttpWebRequest)WebRequest.Create(API_URL);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonRequest);
                }

                using (var response = (HttpWebResponse)webRequest.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string jsonResponse = reader.ReadToEnd();
                    var responseData = serializer.Deserialize<Dictionary<string, object>>(jsonResponse);

                    if (responseData.ContainsKey("imageUrl"))
                    {
                        string imageUrl = "http:" + responseData["imageUrl"].ToString();

                        using (WebClient webClient = new WebClient())
                        {
                            byte[] imageData = webClient.DownloadData(imageUrl);

                            using (MemoryStream memoryStream = new MemoryStream(imageData))
                            {
                                return Image.FromStream(memoryStream);
                            }
                        }
                    }
                }

                return null;
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine("Error: " + reader.ReadToEnd());
                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                return null;
            }
        }

        public async Task<Image> GenerateAsync(string data, int styleNumber)
        {
            try
            {
                QRConfig config = customStyles.ContainsKey(styleNumber)
                    ? customStyles[styleNumber]
                    : customStyles[1];

                var request = new QRRequest
                {
                    data = data,
                    config = config
                };

                var serializer = new JavaScriptSerializer();
                string jsonRequest = serializer.Serialize(request);

                var webRequest = (HttpWebRequest)WebRequest.Create(API_URL);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";

                using (var requestStream = await Task.Factory.FromAsync(
                    webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null))
                using (var streamWriter = new StreamWriter(requestStream))
                {
                    await streamWriter.WriteAsync(jsonRequest);
                }

                using (var response = (HttpWebResponse)await Task.Factory.FromAsync(
                    webRequest.BeginGetResponse, webRequest.EndGetResponse, null))
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string jsonResponse = await reader.ReadToEndAsync();
                    var responseData = serializer.Deserialize<Dictionary<string, object>>(jsonResponse);

                    if (responseData.ContainsKey("imageUrl"))
                    {
                        string imageUrl = "http:" + responseData["imageUrl"].ToString();

                        using (WebClient webClient = new WebClient())
                        {
                            byte[] imageData = await webClient.DownloadDataTaskAsync(imageUrl);

                            using (MemoryStream memoryStream = new MemoryStream(imageData))
                            {
                                return Image.FromStream(memoryStream);
                            }
                        }
                    }
                }

                return null;
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine("Error: " + await reader.ReadToEndAsync());
                    return null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                return null;
            }
        }

        public string UploadImage(string imagePath)
        {
            string url = "https://api.qrcode-monkey.com//qr/uploadimage";
            string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            using (Stream requestStream = request.GetRequestStream())
            {
                byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "
");
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(
                    "Content-Disposition: form-data; name="file"; filename="" + Path.GetFileName(imagePath) + ""
" +
                    "Content-Type: application/octet-stream

");
                requestStream.Write(headerBytes, 0, headerBytes.Length);

                using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                {
                    fileStream.CopyTo(requestStream);
                }

                byte[] trailerBytes = System.Text.Encoding.ASCII.GetBytes("
--" + boundary + "--
");
                requestStream.Write(trailerBytes, 0, trailerBytes.Length);
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
                {
                    return "Error: " + reader.ReadToEnd();
                }
            }
        }
    }
}
#endregion

2. Source code sử dụng trên Form1.cs

using QRCodeStyle;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestMultiQR
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadInit();
        }
        private void PopulateComboBox<T>(ComboBox comboBox)
        {
            comboBox.Items.Clear();
            foreach (var pattern in Enum.GetValues(typeof(T)))
            {
                comboBox.Items.Add(pattern.ToString());
            }

            comboBox.SelectedIndex = 0;
        }

        private T GetSelectedEnum<T>(ComboBox comboBox) where T : Enum
        {
            if (comboBox.SelectedItem != null)
            {
                return (T)Enum.Parse(typeof(T), comboBox.SelectedItem.ToString());
            }
            throw new InvalidOperationException("No item selected in the ComboBox.");
        }

        private void LoadInit()
        {
            PopulateComboBox<QRCodePatterns.Body>(cb_bodyShape);
            PopulateComboBox<QRCodePatterns.Eye>(cb_eyeFrame);
            PopulateComboBox<QRCodePatterns.Ball>(cb_eyeBall);
        }

        private void btnColor1_Click(object sender, EventArgs e)
        {
            var color1 = btnColor1.BackColor;
            colorDialog1.Color = color1;
            var dlg = colorDialog1.ShowDialog();

            if (dlg == DialogResult.OK)
            {
                btnColor1.BackColor = colorDialog1.Color;
                var htmlText = ColorTranslator.ToHtml(btnColor1.BackColor);
                btnColor1.Text = htmlText;
            }

        }

        private void btnColor2_Click(object sender, EventArgs e)
        {
            var color2 = btnColor2.BackColor;
            colorDialog1.Color = color2;
            var dlg = colorDialog1.ShowDialog();

            if (dlg == DialogResult.OK)
            {
                btnColor2.BackColor = colorDialog1.Color;
                var htmlText = ColorTranslator.ToHtml(btnColor2.BackColor);
                btnColor2.Text = htmlText;
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var body = GetSelectedEnum<QRCodePatterns.Body>(cb_bodyShape);
            var frame = GetSelectedEnum<QRCodePatterns.Eye>(cb_eyeFrame);
            var ball = GetSelectedEnum<QRCodePatterns.Ball>(cb_eyeBall);

            var color1 = ColorTranslator.ToHtml(btnColor1.BackColor);
            var color2 = ColorTranslator.ToHtml(btnColor2.BackColor);

            var generator = new QRGenerator();


            var customConfig = new QRConfig
            {
                BodyPattern = body,
                EyePattern = frame,
                BallPattern = ball,
                GradientPattern = QRCodePatterns.Gradient.Linear,
                bodyColor = "#FF0000",
                bgColor = "#FFFFFF",
                gradientColor1 = color1,
                gradientColor2 = color2,
                gradientOnEyes = true,
                LogoPattern = QRCodePatterns.Logo.Clean,
                logo = logoFile
            };

            // Add custom style
            generator.AddStyle(2, customConfig);
            var text = txtText.Text;
            var image = await generator.GenerateAsync(text, 2);
            picResult.Image = image;
        }
        public string logoFile;
        private void button2_Click(object sender, EventArgs e)
        {
            var dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var path = dlg.FileName;
                var generator = new QRGenerator();
                var jsonData = generator.UploadImage(path);
                logoFile = JsonConvert.DeserializeObject<LogoURL>(jsonData).file;
                piclogo.LoadAsync(path);
                MessageBox.Show(logoFile);
            }
        }

        public class LogoURL
        {
            public string file { get; set; }
        }
    }
}
erator();
                var jsonData = generator.UploadImage(path);
                logoFile = JsonConvert.DeserializeObject<LogoURL>(jsonData).file;
                piclogo.LoadAsync(path);
                MessageBox.Show(logoFile);
            }
        }

        public class LogoURL
        {
            public string file { get; set; }
        }
    }
}

Chúc mọi người thành công với tiện ích trên.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

23 October, 2024

[CSHARP] How to use Temp Mail Service in Winform

October 23, 2024 Posted by Trick Blogger , 2 comments
Chào mọi người lại là bài viết chia sẽ về thủ thuật lập trình. Hôm nay mình cần một số lượng mail để nhận OTP khá nhiều nên mình đã tìm hiểu trên mạng ở đâu chia sẽ nhiều mail để mình sữ dụng, và mình thấy bài viết này bên laptrinhvb.net chia sẽ cách nhận mail khá hay :D

Bài viết mày mình hướng dẫn các bạn cách sử dụng Temp Mail Service Api trên C#, Winform.
Trong ứng dụng này, mình sử dụng API 1sec Mail.
Chi tiết, các bạn có thể tham khảo tài liệu API của nó
https://www.1secmail.com/api/

Vậy Temp Mail là gì? và tại sao lại sử dụng temp mail.

Temp Mail (email tạm thời) là một loại dịch vụ email cung cấp cho người dùng một địa chỉ email tạm thời, ngắn hạn để nhận thư.

Sau một khoảng thời gian nhất định hoặc sau khi người dùng không cần sử dụng nữa, địa chỉ email này sẽ tự động hết hiệu lực và bị xoá.

Temp mail thường được dùng trong các tình huống khi bạn không muốn tiết lộ địa chỉ email thật của mình hoặc tránh bị spam.

Hình ảnh ứng dụng:


Tại sao nên sử dụng Temp Mail?

Bảo vệ quyền riêng tư

Khi đăng ký các dịch vụ trực tuyến, nhiều trang web yêu cầu địa chỉ email để gửi thông tin xác thực hoặc thông báo. Nếu bạn không muốn chia sẻ email chính của mình để tránh bị theo dõi hoặc bị làm phiền, temp mail sẽ giúp bạn giữ quyền riêng tư.

Tránh thư rác (spam)

Temp mail giúp bạn tránh việc bị spam bởi các trang web hoặc dịch vụ không đáng tin cậy, vốn có thể bán địa chỉ email của bạn cho bên thứ ba. Sau khi sử dụng xong, email này sẽ biến mất, ngăn chặn mọi thư spam có thể được gửi đến.

Đăng ký nhanh chóng

Việc tạo một địa chỉ email tạm thời chỉ mất vài giây mà không cần phải trải qua quá trình đăng ký phức tạp như với các dịch vụ email thông thường (Gmail, Outlook, Yahoo, v.v.).

Bảo mật thông tin cá nhân

Khi bạn sử dụng một địa chỉ email tạm thời, các thông tin cá nhân của bạn (như tên, tuổi, số điện thoại) sẽ không bị gắn liền với tài khoản đó, giúp giảm thiểu nguy cơ lộ thông tin nhạy cảm.
Tiện lợi khi sử dụng dịch vụ ngắn hạn

Temp mail rất hữu ích khi bạn chỉ cần nhận một lần thư xác thực hoặc một thông báo ngắn hạn, chẳng hạn như để kích hoạt tài khoản, tải về tài liệu, hoặc nhận mã xác nhận.

Video Demo ứng dụng:


Full source code C#:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace DemoTempEmail
{
    public partial class MainForm : Form
    {
        private string currentEmail;
        private string currentDomain;
        private System.Windows.Forms.Timer mailboxTimer;
        private List<EmailMessage> currentMessages;

        public MainForm()
        {
            InitializeComponent();
            mailboxTimer = new System.Windows.Forms.Timer();
            mailboxTimer.Interval = 10000; // Check every 10 seconds
            mailboxTimer.Tick += MailboxTimer_Tick;
            currentMessages = new List<EmailMessage>();
        }

        private void InitializeComponent()
        {
            this.btnCreateEmail = new System.Windows.Forms.Button();
            this.lblCurrentEmail = new System.Windows.Forms.TextBox();
            this.lstMessages = new System.Windows.Forms.ListBox();
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // btnCreateEmail
            // 
            this.btnCreateEmail.Location = new System.Drawing.Point(241, 89);
            this.btnCreateEmail.Name = "btnCreateEmail";
            this.btnCreateEmail.Size = new System.Drawing.Size(220, 23);
            this.btnCreateEmail.TabIndex = 0;
            this.btnCreateEmail.Text = "Create New Email";
            this.btnCreateEmail.Click += new System.EventHandler(this.btnCreateEmail_Click);
            // 
            // lblCurrentEmail
            // 
            this.lblCurrentEmail.Location = new System.Drawing.Point(122, 137);
            this.lblCurrentEmail.Name = "lblCurrentEmail";
            this.lblCurrentEmail.Size = new System.Drawing.Size(538, 20);
            this.lblCurrentEmail.TabIndex = 1;
            // 
            // lstMessages
            // 
            this.lstMessages.FormattingEnabled = true;
            this.lstMessages.Location = new System.Drawing.Point(12, 189);
            this.lstMessages.Name = "lstMessages";
            this.lstMessages.Size = new System.Drawing.Size(668, 160);
            this.lstMessages.TabIndex = 2;
            this.lstMessages.SelectedIndexChanged += new System.EventHandler(this.lstMessages_SelectedIndexChanged);
            // 
            // webBrowser1
            // 
            this.webBrowser1.Location = new System.Drawing.Point(12, 355);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1";
            this.webBrowser1.ScriptErrorsSuppressed = true;
            this.webBrowser1.Size = new System.Drawing.Size(668, 339);
            this.webBrowser1.TabIndex = 3;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(14, 140);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(102, 13);
            this.label1.TabIndex = 4;
            this.label1.Text = "Email temp Address:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
            this.label2.Location = new System.Drawing.Point(164, 25);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(359, 24);
            this.label2.TabIndex = 5;
            this.label2.Text = "TEMP EMAIL C# - LAPTRINHVB.NET";
            // 
            // pictureBox1
            // 
            this.pictureBox1.Image = global::DemoTempEmail.Properties.Resources.logo;
            this.pictureBox1.Location = new System.Drawing.Point(560, 25);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 87);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 6;
            this.pictureBox1.TabStop = false;
            // 
            // linkLabel1
            // 
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(13, 72);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(107, 13);
            this.linkLabel1.TabIndex = 7;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "https://laptrinhvb.net";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            // 
            // MainForm
            // 
            this.ClientSize = new System.Drawing.Size(692, 706);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.webBrowser1);
            this.Controls.Add(this.btnCreateEmail);
            this.Controls.Add(this.lblCurrentEmail);
            this.Controls.Add(this.lstMessages);
            this.Name = "MainForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "[C#] Temp Email Inbox - https://laptrinhvb.net";
            this.Load += new System.EventHandler(this.MainForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private System.Windows.Forms.Button btnCreateEmail;
        private System.Windows.Forms.TextBox lblCurrentEmail;
        private System.Windows.Forms.ListBox lstMessages;

        private async void btnCreateEmail_Click(object sender, EventArgs e)
        {
            try
            {
                var email = await GenerateRandomEmail();
                currentEmail = email.Split('@')[0];
                currentDomain = email.Split('@')[1];
                lblCurrentEmail.Text = $"{email}";
                lstMessages.Items.Clear();
             
                currentMessages.Clear();
                mailboxTimer.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error generating email: {ex.Message}");
            }
        }

        private async Task<string> GenerateRandomEmail()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync("https://www.1secmail.com/api/v1/?action=genRandomMailbox&count=1");
                var emails = JsonConvert.DeserializeObject<List<string>>(response);
                return emails[0];
            }
        }

        private async void MailboxTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                var messages = await GetMessages();
                UpdateMessageList(messages);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error checking mailbox: {ex.Message}");
            }
        }

        private async Task<List<EmailMessage>> GetMessages()
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync($"https://www.1secmail.com/api/v1/?action=getMessages&login={currentEmail}&domain={currentDomain}");
                return JsonConvert.DeserializeObject<List<EmailMessage>>(response);
            }
        }

        private void UpdateMessageList(List<EmailMessage> messages)
        {
            foreach (var message in messages)
            {
                if (!currentMessages.Exists(m => m.Id == message.Id))
                {
                    currentMessages.Add(message);
                    lstMessages.Items.Add(message.Subject);
                }
            }
        }

        private async void lstMessages_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstMessages.SelectedIndex != -1)
            {
                var selectedMessage = currentMessages[lstMessages.SelectedIndex];
                try
                {
                    var fullMessage = await GetFullMessage(selectedMessage.Id);
                    webBrowser1.DocumentText = fullMessage.Body;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Error fetching message details: {ex.Message}");
                }
            }
        }

        private async Task<FullEmailMessage> GetFullMessage(int id)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetStringAsync($"https://www.1secmail.com/api/v1/?action=readMessage&login={currentEmail}&domain={currentDomain}&id={id}");
                return JsonConvert.DeserializeObject<FullEmailMessage>(response);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://laptrinhvb.net");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Process.Start("https://chromewebstore.google.com/detail/zalo-marketing-pro-ch%E1%BB%91ng/kgbfpnnjchndjegeckjggbgcmklefman?authuser=0&hl=vi");
        }
    }

    public class EmailMessage
    {
        public int Id { get; set; }
        public string From { get; set; }
        public string Subject { get; set; }
        public string Date { get; set; }
    }

    public class FullEmailMessage : EmailMessage
    {
        public string Body { get; set; }
        public string TextBody { get; set; }
        public string HtmlBody { get; set; }
    }
}

Qua đoạn code bên trên mọi người cũng biết thêm bớt gì rồi chứ.
Chúc mọi người thành công với thủ thuật trên.

DOWNLOAD SOURCE CODE
PASSWORD: HUNG.PRO.VN
Top