Hiển thị các bài đăng có nhãn NUGET. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn NUGET. Hiển thị tất cả bài đăng

[CSHARP] Instructions for push notifications using One Signal API

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách push notification cho website sử dụng API One Signal C#.

[CSHARP] Hướng Dẫn Push Notification Sữ Dụng API One Signal

One Signal giúp chúng ta dễ dàng gởi thông báo đến tất cả các webclient đã đăng ký nhận thông báo từ ứng dụng web của chúng ta.

Sử dụng One Sign sẽ giúp tăng SEO cho website của chúng ta, mỗi khi có bài viết mới thì người dùng dễ dàng nhận được thông báo một cách nhanh chóng.

Dưới đây là giao diện demo ứng dụng:


Trong ứng dụng trên, mình chỉ push các thông tin cơ bản, bao gồm:
 
Tiêu đề, nội dung, link khi mở vào, và hình ảnh bài viết (chỉ tích hợp chạy trên chrome).
Khi các bạn nhấn nút Push vào thì ứng dụng sẽ gởi thông báo đến tất cả các client đã đăng ký như hình bên dưới.

Đầu tiên, các bạn cần import thư viện vào từ Nuget:
PM> Install-Package OneSignal.CSharp.SDK

Các bạn cần lấy ID app, API Sercet key từ setting của onesignal để thêm vào ứng dụng nhé.

Và dưới đây là source code khi click vào button Push Notification:
using OneSignal.CSharp.SDK;
using OneSignal.CSharp.SDK.Resources;
using OneSignal.CSharp.SDK.Resources.Notifications;
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 Push_Notification_OneSignal
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_push_Click(object sender, EventArgs e)
        {
            var client = new OneSignalClient("Nhập Serect key của bạn"); // Nhập API Serect Key

            var options = new NotificationCreateOptions_new();

            options.AppId = new Guid("Nhập ID SignOne"); // Nhập My AppID của bạn
            options.IncludedSegments = new List<string> { "All" };
            options.Headings.Add(LanguageCodes.English, txt_title.Text);
            options.Contents.Add(LanguageCodes.English, txt_content.Text);
            options.Url = txt_link.Text;
            options.ChromeWebImage = txt_url_image.Text;
            var result =  client.Notifications.Create(options);
            MessageBox.Show(result.ToString());
        }
    }
}

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

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN 

on Thứ Sáu, 5 tháng 7, 2024 | , , , , | A comment?

[CSHARP] How to Save and Get Password in Credential Manager Windows

[CSHARP] Hướng dẫn lưu trữ mật khẩu ở Credential Manage Windows

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách lưu trữ mật khẩu ứng dụng vào Credential Manager trên Windows.

[CSHARP] Hướng dẫn lưu trữ mật khẩu ở Credential Manage Windows

Trên Microsoft Windows, có một ứng dụng Credential Manager dùng để lưu trữ thông tin username và password của một ứng dụng hoặc Website.
Để truy cập vào Credential Manager:
Các bạn vào ControlPanel > All Control Panel Items > Credential manger như hình bên dưới.
Bài viết này mình sẽ hướng dẫn các bạn cách lưu trữ mật khẩu ứng dụng vào đây, như hình bên dưới:
Ở hình trên, các bạn thấy mình đã lưu trữ ứng dụng: laptrinhvbApp Để thực hiện, các bạn cần cài đặt thư viện Credentials từ Nuget:
PM> NuGet\Install-Package Credentials -Version 2.0.0.30

Bước 1: Tạo một class PasswordRepository chứa hai phương thức: SavePassword và GetPassword

public class PasswordRepository
{      

    public void SavePassword(string AppName, string password)
    {
        using (var cred = new Credential())
        {
            cred.Password = password;
            cred.Target = AppName;
            cred.Type = CredentialType.Generic;
            cred.PersistanceType = PersistanceType.LocalComputer;
            cred.Save();
        }
    }

    public string GetPassword(string AppName)
    {
        using (var cred = new Credential())
        {
            cred.Target = AppName;
            cred.Load();
            return cred.Password;
        }
    }
}

Bước 2: Sử dụng hàm trên để lưu trữ mật khẩu

private void button1_Click(object sender, EventArgs e)
{
    var AppName = "laptrinhvbApp";
    new PasswordRepository().SavePassword(AppName, "Laptrinhvb.net");
    var data = new PasswordRepository().GetPassword(AppName);
}
Chúc các bạn thành công với thủ thuật lưu mật khẩu trên, và không lo việc quên mật khẩu nữa.

on Thứ Sáu, 28 tháng 6, 2024 | , , | A comment?

[C#] How to convert HTML to PDF in Netcore

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách chuyển đổi mã code HTML sang tập tin PDF file trên NET Core.

[C#] Hướng dẫn convert HTML code sang PDF File trên NetCore 7 Winform

Mình cũng đã có bài viết về cách chuyển đổi này tuy nhiên nó làm việc trên Netframework.
Nếu bạn nào đang dùng netcore thì thực hiện theo bài viết này nhé.

Đầu tiên, các bạn cài đặt cho mình thư viện DinktoPDF từ nuget:

NuGet\Install-Package DinkToPdf -Version 1.0.8

Khi các bạn thực hiện tạo pdf trên thư viện này nó xảy ra lỗi như sau.

DllNotFoundException: Unable to load DLL 'libwkhtmltox' or one of its dependencies: The specified module could not be found. (0x8007007E)

Bạn cần import thư viện libwkhtmltox.dll từ source code mình về vào chép vào thư mục chạy ứng dụng.

Ở tập tin program.cs: các bạn load dll dynamic vào như code mình bên dưới:

using System.Runtime.InteropServices;

namespace HTMLTOPDFDemo
{
    internal static class Program
    {

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool SetDllDirectory(string lpPathName);

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr LoadLibrary(string lpFileName);

        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            string dllPath = Path.Combine(Directory.GetCurrentDirectory(), "NativeLibraries");
            if (!SetDllDirectory(dllPath))
            {
                Console.WriteLine($"Failed to set DLL directory: {Marshal.GetLastWin32Error()}");
                return;
            }

            // Load the required native library
            string libraryName = "libwkhtmltox.dll";
            IntPtr libHandle = LoadLibrary(libraryName);
            if (libHandle == IntPtr.Zero)
            {
                Console.WriteLine($"Failed to load library '{libraryName}': {Marshal.GetLastWin32Error()}");
                return;
            }

            Console.WriteLine("Library loaded successfully!");

            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();
            Application.Run(new Form1());
        }
    }
}

Tiếp đến, các bạn tạo file PDFHelper.cs class

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

namespace HTMLTOPDFDemo
{
    public class PDFHelper
    {
        private  readonly SynchronizedConverter _converter;
        public PDFHelper()
        {
            _converter = new SynchronizedConverter(new PdfTools());
        }
        public  string ConvertHtmlToPdf(string htmlContent)
        {
            try
            {
              
                var customSize = new PechkinPaperSize("150", "220");

                var globalSettings = new GlobalSettings
                {
                    PaperSize = customSize,
                    Orientation = DinkToPdf.Orientation.Portrait,
                    DPI = 300,
                    Margins = new MarginSettings { Top = 5, Bottom = 5, Left = 5, Right = 5 }
                };

                var objectSettings = new ObjectSettings
                {
                    PagesCount = true,
                    HtmlContent = htmlContent,
                    // WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "styles.css") }
                    WebSettings = { DefaultEncoding = "utf-8" }
                };

                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects = { objectSettings }
                };

                byte[] pdfBytes = _converter.Convert(pdf);
                string pdfPath = Path.Combine(Application.StartupPath + "\\pdfExport", $"{Guid.NewGuid()}.pdf");
                File.WriteAllBytes(pdfPath, pdfBytes);

                return pdfPath;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error converting HTML to PDF: {ex.Message}");
                return "";
            }
        }
    }
}

Ở form1.cs, các bạn chỉ cần gọi để sử dụng

using DinkToPdf;
using System.Diagnostics;
using System.Drawing.Printing;
using System.IO.Packaging;
using System.Windows.Forms;

namespace HTMLTOPDFDemo
{
    public partial class Form1 : Form
    {
        //NuGet\Install-Package DinkToPdf -Version 1.0.8
      
        public Form1()
        {
            InitializeComponent();
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var htmlText = File.ReadAllText("invoice.html");
            var pdfFile = new PDFHelper(). ConvertHtmlToPdf(htmlText);
            Process.Start(new ProcessStartInfo(pdfFile) { UseShellExecute = true });
           
        }
       
    }
}

Chúc các bạn thành công với tiện ích trên.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Ba, 19 tháng 3, 2024 | , , , , | A comment?

[C#] How to make chat with Gemini AI Google Winform

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách kết nối trò chuyện Chat Gemini AI Google bằng C#, Winform.


[C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform

[C#] How to make chat with Gemini AI Google Winform

Gemini AI là gì?

Gemini AI dòng mô hình ngôn ngữ lớn mới nhất của Google, cung cấp tất cả thông tin cần thiết để bắt đầu tạo ứng dụng bằng Gemini.

Đầu tiên, các bạn cần tạo một tài khoản API key.

Các bạn truy cập vào địa chỉ sau: https://aistudio.google.com/

Tiếp đến, các bạn tạo một API key để sử dụng như hình bên dưới:
[C#] How to make chat with Gemini AI Google Winform

Tiếp đến, các bạn tạo project C#, vào cài đặt thư viện Google_GenerativeAI từ nuget:
PM> Install-Package Google_GenerativeAI

Thiết kế giao diện chat Winform như hình bên dưới:
[C#] How to make chat with Gemini AI Google Winform

Full source code C#:

using GenerativeAI.Methods;
using GenerativeAI.Models;
using GenerativeAI.Types;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GeminiAIDemo
{
    public partial class Form1 : Form
    {
        ChatSession chatSession;
        public string apiKey = "AIzaSyCjhe255nXjOQwst6NM6RrXCbz03xl66HM";
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnSend_Click(object sender, EventArgs e)
        {
            var message = txtMessage.Text.Trim();
            await SendMessageAsync(message);

        }

        private async Task SendMessageAsync(string message)
        {
            if (btnSend.Text != "Send message") return;

            if (message.Length > 0)
            {
                txtMessage.Text = "";
                btnSend.Text = "Waiting...";

                txtBody.SelectionAlignment = HorizontalAlignment.Left;
                txtBody.SelectionColor = Color.Blue;
                txtBody.AppendText($"Me: {message}\n");

                txtBody.SelectionAlignment = HorizontalAlignment.Right;
                txtBody.SelectionColor = Color.Red;
                var result = await chatSession.SendMessageAsync(message);
                txtBody.AppendText($"Gemini AI: {result}\n");

                txtBody.SelectionAlignment = HorizontalAlignment.Left;
                txtBody.SelectionColor = txtBody.ForeColor;
               
                btnSend.Text = "Send message";
                txtBody.ScrollToCaret();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {    
            var model = new GenerativeModel(apiKey);
            chatSession = model.StartChat(new StartChatParams());

        }

        private async  void txtMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var message = txtMessage.Text.Trim();
                await SendMessageAsync(message);
            }
        }

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


Chúc các bạn thành công với thủ thuật trên, để tạo cho mình một ứng dụng chat AT tốt nhất nhé
 

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN 

on Thứ Sáu, 15 tháng 3, 2024 | , , | A comment?

[C#] Show log to console Winform

Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn sử dụng Serialog để show log ra Richtextbox giống trên console windows.

[C#] Hướng dẫn ghi log ra RichTextBox giống Console trên Winform sử dụng thư viện Serilog

Dưới đây, là hình ảnh demo ứng dụng:
Đầu tiên, các bạn cài đặt cho mình thư viện Serilog bên dưới từ Nuget.
NuGet\Install-Package Serilog.Sinks.RichTextBox.WinForms.Colored -Version 1.2.0

Giao diện show log ứng dụng:


Các bạn có thể show nhiều định dạng log như: Error, Warning, Information, Faltal...

Xem video hướng dẫn thực hiện step by step.


Full source code C# Form1.cs:

using Serilog.Events;
using Serilog.Sinks.RichTextBoxForms.Themes;
using Serilog.Sinks.RichTextBoxForms;
using Serilog;
using System.Windows.Forms;

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

        private RichTextBoxSinkOptions _options = null!;

        private void Initialize()
        {
            _options = new RichTextBoxSinkOptions(ThemePresets.Dark, 200, 5, true);
            var sink = new RichTextBoxSink(richTextBox1, _options);
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Verbose()
                .WriteTo.Sink(sink, LogEventLevel.Verbose)
                .CreateLogger();

            Log.Debug("Started logger.");

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Initialize();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Log.Error("Error messge Oops....");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Log.Information("Error messge Oops....");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Log.Warning("Error messge Oops....");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var frm = new Form2();
            frm.Show();
        }
    }
}

Source code Form2.cs

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 Serilog;

namespace SerilogDemo
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    Log.Information($"Processing line: {i}");
                    Thread.Sleep(300);

                    Log.Fatal($"Falal line: {i}");
                    Thread.Sleep(300);
                }
            });
        }
    }
}

Chúc các bạn thành công với thủ thuật trên.

DOWNLOAD FULL SOURCE


PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Ba, 20 tháng 2, 2024 | , , | A comment?

[C#] Cách thanh toán qua mã vạch VietQR sử dụng payOS API

Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn cách tạo thanh toán hóa đơn trực tiếp qua mã vạch VietQR sử dụng payOS API.


[C#] Hướng dẫn tạo thanh toán đơn hàng qua mã vạch VietQR sử dụng API PayOS hoàn toàn miễn phí

Các bạn có thể đăng ký api payOS hoàn toàn miễn phí tại website.
https://payos.vn


Các bạn, thường mua hàng ở các website, khi thanh toán các bạn thường gặp có thể thanh toán trực tiếp bằng cách quét mã vạch như: Momo, Zalopay, Viettel money...

Những Api này thường bạn đăng ký phải là tổ chức doanh nghiệp.

Với payOS, mình có thể đăng ký một tài khoản cá nhân bình thường, cách bước thực hiện các bạn đăng nhập vào website và tạo một tài khoản và liên kết ngân hàng như hướng dẫn.

Để viết bài này, mình đã đăng ký một tài khoản Ngân Hàng Phương Đông (OCB) để liên kết với payOS.

Khi các bạn đăng ký thành công, có bạn sẽ có các thông tin: clientID, apiKey, checkSumKey.
Để các bạn sử dụng gọi API.

Khi tạo một kênh thanh toán, sẽ có thông tin như hình bên dưới:

Và ở C# chúng ta sẽ cài đặt thư viện payOS từ nuget:
dotnet add package payOS --version 1.0.2

Các bạn khai báo thông tin cấu hình vào:
namespace DemoPayOS
{
    public  class Constants
    {
       public static string clientId = "";
        public static string  apiKey = "";
        public static string  checksumKey = "";
    }
}

Dưới đây là source code ứng dụng demo, thường các bạn sẽ build trên Website, nhưng bài viết này mình demo ở Winform netCore 6
using Net.payOS;
using Net.payOS.Types;
using System.Diagnostics;

namespace DemoPayOS
{
    public partial class Form1 : Form
    {
        PayOS payOS;
      
        public Form1()
        {
            InitializeComponent();
            payOS = new PayOS(Constants.clientId, Constants.apiKey, Constants.checksumKey);
        }

        private async void btnTaoLinkTT_ClickAsync(object sender, EventArgs e)
        {
            var name = txtSanPham.Text;
            var soluong = Convert.ToInt32(txtSoluong.Text);
            var thanhtien = Convert.ToInt32(txtThanhTien.Text);
           
            ItemData item = new ItemData(name, soluong, thanhtien);
            List<ItemData> items = new List<ItemData>();
            items.Add(item);

            var noidung = "Thanh toán tiền nhậu";
            var orderID = 2005;
            var tongGiaTien = 2000; // 2 ngàn vnđ

            PaymentData paymentData = new PaymentData(orderID, tongGiaTien, noidung,
                 items,  "https://localhost:3002",  "https://localhost:3002");

            CreatePaymentResult createPayment = await payOS.createPaymentLink(paymentData);

            var linkCheckOut = createPayment.checkoutUrl;
            Process.Start(new ProcessStartInfo
            {
                FileName =  @"C:\Program Files\Google\Chrome\Application\chrome.exe",
                Arguments = linkCheckOut
            });

        }
    }
}

Khi tạo thành công, chúng ta sẽ được một đường link api website thanh toán, và chúng ta sẽ mở cho khách hàng thanh toán. Giao diện thanh toán:

Các bạn có thể nhấn nút Hủy thanh toán, để hủy bỏ đơn hàng này.

payOS cũng cung cấp cho chúng ta http callback, để chúng ta có thể cập nhật tình trạng thông tin đơn hàng đã được thanh toán hay hủy bỏ vào cơ sở dữ liệu của mình.

Khi các bạn đăng ký thành công, payOS có tài liệu hướng dẫn các sử dụng cụ thể, chi tiết các bạn có thể tham khảo ở trên đó.
 
Video demo ứng dụng thanh toán VietQR via payOS api:


P/s: Bài viết chỉ mang tính hướng dẫn, không có tính quảng cáo cho payOS api hay vietQR gì, chi tiết các bạn đọc kỹ ở phần đăng ký payOS trên trang chủ.

Chúc các bạn thành công.

DOWNLOAD SOURCE CODE

Password Unzip: HUNG.PRO.VN

on Thứ Tư, 10 tháng 1, 2024 | , , , | A comment?

[C#] How to make Appbar in windows

Xin chào, các bạn bài viết hôm nay mình hướng dẫn cách viết ứng dụng Dock giao diện trên Windows giống Taskbar C#.


[C#] Hướng dẫn tạo ứng dụng dock windows giống Taskbar


Hiện nay, trên windows 11, chúng ta có Copilot bản preview, khi các bạn chạy ứng dụng, thấy app nào luôn neo ở góc bên phải, và chiếm luôn không gian đó của màn hình.

Trên C#, các bạn thực hiện đơn giản theo các bước sau:

Đầu tiên, các bạn cài thư viện tip2tail.WinFormAppBarLib từ Nuget:
NuGet\Install-Package tip2tail.WinFormAppBarLib -Version 1.2.1

VIDEO HƯỚNG DẪN:

Full source code 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 tip2tail.WinFormAppBarLib;

namespace AppBarDesktop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
          //  AppBarHelper.PreventShowDesktop(this.Handle);
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            AppBarHelper.AppBarMessage = "HUNG.PRO.VN";
            AppBarHelper.SetAppBar(this, AppBarEdge.None);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AppBarHelper.SetAppBar(this, AppBarEdge.None);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            AppBarHelper.SetAppBar(this, AppBarEdge.Left);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            AppBarHelper.SetAppBar(this, AppBarEdge.Right);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            AppBarHelper.SetAppBar(this, AppBarEdge.Bottom);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AppBarHelper.SetAppBar(this, AppBarEdge.Top);
        }
    }
}

Chúc cấc bạn thành công với thủ thuật trên.
DOWNLOAD SOURCE CODE

on Thứ Tư, 22 tháng 11, 2023 | , , | A comment?