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

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

[DEVEXPRESS] Search and Custom Highlight Text in Winform C#

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn cách tìm kiếm Tiếng Việt không dấu highlight có dấu trên Devexpress Winform C#.

[DEVEXPRESS] Tìm kiếm không dấu tô màu highlight có dấu trên C# Winform


Hình ảnh tìm kiếm không dấu có thể highlight có dấu Tiếng Việt:

Ở hình ảnh trên, các bạn thấy mình gõ vào từ khóa: cam thuy quang
=> kết quả nó tự hiểu và tìm kiếm Cam Thủy, Quảng Bình...

Video demo ứng dụng:


FULL SOURCE CODE CSHARP:

using DevExpress.XtraEditors.Controls;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Globalization;
using DevExpress.Utils.Paint;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils.Html.Internal;
using DevExpress.XtraPrinting.Native;
using DevExpress.XtraPrinting;
using DevExpress.XtraEditors;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace SearchHighLightNoneVietnamese
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        private List<DVHC> listDVHC = new List<DVHC>();
        public Color foreColorHighLight = Color.White;
        public Color backgroundColorHighLight = Color.YellowGreen;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            colorBackground.Color = backgroundColorHighLight;
            colorForeground.Color = foreColorHighLight;
        }
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            var jsonRawData = File.ReadAllText("data.json");
            listDVHC = JsonConvert.DeserializeObject<List<DVHC>>(jsonRawData);
            cb_diadiem.Properties.DataSource = listDVHC;
            cb_diadiem.AutoSuggest += repositoryItemGridLookUpEdit1_AutoSuggest;
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
            cb_diadiem.Properties.ValueMember = "maxa";
            cb_diadiem.Properties.DisplayMember = "diadiem";
            cb_diadiem.Properties.PopupFormSize = new System.Drawing.Size(cb_diadiem.Width, 300);
            cb_diadiem.BeforePopup += Cb_diadiem_BeforePopup;
            cb_diadiem.Popup += Cb_diadiem_Popup;
            LoadTinhThanh();
            LoadQuanHuyen();
            LoadPhuongXa();
            this.KeyPreview = true;
            this.KeyDown += Form1_KeyDown;
        }

        private void Cb_diadiem_Popup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell += cbDiadiem_CustomDrawCell;
        }

        private void Cb_diadiem_BeforePopup(object sender, EventArgs e)
        {
            gridLookUpEdit1View.CustomDrawCell -= cbDiadiem_CustomDrawCell;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.K)
            {
                cb_diadiem.Focus();
                cb_diadiem.SelectAll();
            }
        }

        public void LoadTinhThanh() {
            var dataTinhThanh = listDVHC.Select(x => new { matinh = x.matinh, tentinh = x.tentinh }).Distinct().ToList();
            cb_tinhthanh.Properties.DataSource = dataTinhThanh;
            cb_tinhthanh.Properties.ValueMember = "matinh";
            cb_tinhthanh.Properties.DisplayMember = "tentinh";
        }

        public void LoadQuanHuyen()
        {
            var dataQuanHuyen = listDVHC.Select(x => new { mahuyen = x.mahuyen, tenhuyen = x.tenhuyen }).Distinct().ToList();
            cb_quanhuyen.Properties.DataSource = dataQuanHuyen;
            cb_quanhuyen.Properties.ValueMember = "mahuyen";
            cb_quanhuyen.Properties.DisplayMember = "tenhuyen";
        }

        public void LoadPhuongXa()
        {
            var dataPhuongXa = listDVHC.Select(x => new { maxa = x.maxa, tenxa = x.tenxa }).Distinct().ToList();
            cb_phuongxa.Properties.DataSource = dataPhuongXa;
            cb_phuongxa.Properties.ValueMember = "maxa";
            cb_phuongxa.Properties.DisplayMember = "tenxa";
        }

        private void cbDiadiem_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {

            XPaint paint = new XPaint();
            MultiColorDrawStringParams drawParams = new MultiColorDrawStringParams(e.Appearance);


            var searchText = cb_diadiem.Text;



            if (e.DisplayText.Length < searchText.Length)
                return;

            
            drawParams.Bounds = e.Bounds;
            drawParams.Text = e.DisplayText;           
            string tmpStr = e.DisplayText;
           
            var searchIndexesListOrigin = getListIndexMatch(e.DisplayText, searchText);
            if (searchIndexesListOrigin.Count == 0) return;
          

            var searchIndexesList = searchIndexesListOrigin.OrderBy(x => x.Item2).ToList();
            if (searchIndexesList.Count() > 0)
            {
                drawParams.Ranges = new CharacterRangeWithFormat[searchIndexesList.Count() * 2 + 1];
                int currentStrIndex = 0;
                int i = 0;
                while (i < searchIndexesList.Count())
                {
                    drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, searchIndexesList[i].Item2 - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                    drawParams.Ranges[i * 2 + 1] = new CharacterRangeWithFormat(searchIndexesList[i].Item2, searchIndexesList[i].Item3 - searchIndexesList[i].Item2, foreColorHighLight, backgroundColorHighLight);
                    currentStrIndex = searchIndexesList[i].Item3;
                    i++;
                }
                drawParams.Ranges[i * 2] = new CharacterRangeWithFormat(currentStrIndex, e.DisplayText.Length - currentStrIndex, e.Appearance.ForeColor, e.Appearance.BackColor);
                drawParams.Ranges = drawParams.Ranges.Where(val => val.Length != 0).ToArray();
            }
            paint.MultiColorDrawString(new DevExpress.Utils.Drawing.GraphicsCache(e.Graphics), drawParams);
            e.Handled = true;
            
        }

        public  int AccentInsensitiveIndexOf(string source, string subStr)
        {
            // return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, subStr, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace);
            var keyword = BoDauTiengViet(subStr);

            //Regex.Match(source, $@"\W{keyword}\W").Index;
            var match = Regex.Match(source, $@"\b{keyword}\b");
            int index = match.Success ? match.Index : -1;
            return index;
        }

       
        public List<(string, int, int)> getListIndexMatch(string source, string subStr)
    {


            var listdata = new List<(string, int, int)>();


            string[] stringSeparators = new string[] { " " };
            var sourceArr = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

            var arrKeywork = subStr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

         

            foreach (string keyword in arrKeywork)
            {
                var start = AccentInsensitiveIndexOf(BoDauTiengViet( source), keyword);
                var end = start + keyword.Length;
                var item = (keyword, start, end);
                if(start >= 0)
                {

                    bool isStartBoundary = (start == 0) || char.IsWhiteSpace(source[start - 1]);
                    bool isEndBoundary = (end == source.Length) || char.IsWhiteSpace(source[end]);

                    //    var stringMatch = source.Substring(start, keyword.Length);

                    //    var isWordMatch = keyword == BoDauTiengViet(stringMatch);
                    //    if (isWordMatch)
                  //  if (isStartBoundary || isEndBoundary) {
                        listdata.Add(item);
                    //}
                   

                }
          

            }
            return listdata;
        }

        public Task<ICollection> QueryAsync(string keywords, CancellationToken cancellation)
        {

            return Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(keywords))
                {
                    return FilterDVHCByKeyWords(listDVHC, keywords) as ICollection;
                }
                else
                {
                    return listDVHC as ICollection;
                }

            });
        }

        private void repositoryItemGridLookUpEdit1_AutoSuggest(object sender, LookUpEditAutoSuggestEventArgs e)
        {
            e.SetMinimumAnimationDuration(TimeSpan.FromMilliseconds(100));
            e.QuerySuggestions = QueryAsync(e.Text, e.CancellationToken);
        }

       
        public List<DVHC> FilterDVHCByKeyWords(List<DVHC> data, string keyworks) {
            string[] pattern_split = new string[] { " " };
            string[] arr_keywords = keyworks.Split(pattern_split, StringSplitOptions.RemoveEmptyEntries);
            var cleanedKeywords = arr_keywords.Select(k => BoDauTiengViet(k));
            var regexPattern = string.Join(".*", cleanedKeywords.Select(Regex.Escape));
            var regex = new Regex(regexPattern, RegexOptions.IgnoreCase);

            return data.Where(item => regex.IsMatch(BoDauTiengViet(item.diadiem))).ToList();
        }

        public string BoDauTiengViet(string str)
        {
            str = str.ToLower().Trim();
            str = Regex.Replace(str, "[àáạảãâầấậẩẫăằắặẳẵ]", "a");
            str = Regex.Replace(str, "[èéẹẻẽêềếệểễ]", "e");
            str = Regex.Replace(str, "[ìíịỉĩ]", "i");
            str = Regex.Replace(str, "[òóọỏõôồốộổỗơờớợởỡ]", "o");
            str = Regex.Replace(str, "[ùúụủũưừứựửữ]", "u");
            str = Regex.Replace(str, "[ỳýỵỷỹ]", "y");
            str = Regex.Replace(str, "đ", "d");
          //  str = Regex.Replace(str, " ", "-");
            str = str.Replace(",", " ");
            str = str.Replace(".", " ");
            return str;
        }

        private void colorForeground_EditValueChanged(object sender, EventArgs e)
        {
            foreColorHighLight = colorForeground.Color;
        }

        private void colorBackground_EditValueChanged(object sender, EventArgs e)
        {
            backgroundColorHighLight = colorBackground.Color;
        }

        private void cb_diadiem_EditValueChanged(object sender, EventArgs e)
        {
            if (cb_diadiem.EditValue != null) {
                
                var selectedRow = cb_diadiem.GetSelectedDataRow() as DVHC; 
                cb_tinhthanh.EditValue = selectedRow.matinh;
                cb_quanhuyen.EditValue = selectedRow.mahuyen;
                cb_phuongxa.EditValue = selectedRow.maxa;
               
            }         

        }
    }



    public class DVHC { 
        public string diadiem { get; set; }
        public string maxa { get; set; }
        public string tenxa { get; set; }
        public string mahuyen { get; set; }
        public string tenhuyen { get; set; }
        public string matinh { get; set; }
        public string tentinh { get; set; }
    }
}

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

on Thứ Ba, 16 tháng 7, 2024 | , , , | A comment?

[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] Instructions for automatically generating OTP codes in Csharp programming

[CSHARP] Instructions for automatically generating OTP codes in Csharp programming
Chào các bạn trẻ thân mến, bài viết hôm nay mình sẽ hướng dẫn các bạn cách tạo mã OTP tự động trong lập trình C# (tạo password tự động).

[CSHARP] Hướng dẫn tạo mã tự động OTP trong lập trình Csharp

Vậy OTP là gì?

OTP là viết tắt của từ One Time Password, có nghĩa là mật khẩu sử dụng 1 lần.
Mã OTP là mã được các hệ thống thanh toán online mặc định gửi đến cho quý khách hàng để nhập vào trong thời gian thực hiện giao dịch để đảm bảo sự bảo mật một cách tối đa.

Nếu bạn nào thường sử dụng Internet Banking thì thường gặp mã OTP, khi giao dịch một dịch vụ nào, thì ngân hàng hàng sẽ gởi cho chúng ta một mã OTP và có thời gian sử dụng trong thời gian nhất định.

Trong ngôn lập lập trình .NET có hỗ trợ cho chúng ta tất cả là 3 hàm Random:
  1. Next() => hàm Next trả về cho chúng ta ngẫu nhiên một số
  2. NextBytes() => hàm trả về random cho chúng ta một mảng byte.
  3. NextDouble() => hàm random trả về cho chúng ta từ 0.0 - 1.0.
Để tạo random OTP, bao gồm các ký tự chữ hoa, chữ thường, số, và các ký tự đặc biệt.

Trong bài viết này, mình sẽ sử dụng hàm NextDouble() để thực hiện.

Dưới đây, mình sẽ viết hàm makeRandomPassword trả về cho chúng ta một dãy số ngẫu nhiên, và số ký tự trả về chúng ta sẽ truyền qua parametter.

Source code OTP C# viết bằng Console Application C#

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
namespace PasswordPractice {  
    class PasswordCreate {  
        //Tis function is making the Random Password  
        public string makeRandomPassword(int length) {  
            string UpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM";  
            string LowerCase = "qwertyuiopasdfghjklzxcvbnm";  
            string Digits = "1234567890";  
            string allCharacters = UpperCase + LowerCase + Digits;  
            //Random will give random charactors for given length  
            Random r = new Random();  
            String password = "";  
            for (int i = 0; i < length; i++) {  
                double rand = r.NextDouble();  
                if (i == 0) {  
                    password += UpperCase.ToCharArray()[(int) Math.Floor(rand * UpperCase.Length)];  
                } else {  
                    password += allCharacters.ToCharArray()[(int) Math.Floor(rand * allCharacters.Length)];  
                }  
            }  
            Console.WriteLine(password);  
            Console.ReadLine();  
            return password;  
        }  
        static void Main(string[] args) {  
            //User Input  
            Console.WriteLine("Enter length of password");  
            string len = Console.ReadLine();  
            PasswordCreate n = new PasswordCreate();  
            //Call the method in main method  
            n.makeRandomPassword(Convert.ToInt32(len));  
        }  
    }  
}  

Hình ảnh sau khi chạy chương trình.

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

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

[CSHARP] Drag drop file to RichTextBox

[CSHARP] Drag drop file to RichTextBox
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 Drag drop file Text vào RichTextBox trên C# winform.

[C#] Hướng dẫn Drag and Drop File vào RichTextBox

Dưới đây là hình ảnh demo mình kéo file text vào RichTextBox.

Source code C#:

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

 

        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.AllowDrop = true;
            richTextBox1.DragDrop += RichTextBox1_DragDrop;
        }

        private void RichTextBox1_DragDrop(object sender, DragEventArgs e)
        {
            var data = e.Data.GetData(DataFormats.FileDrop);
            if (data != null)
            {
                var fileNames = data as string[];
                if (fileNames.Length > 0) {
                    string myText = File.ReadAllText(fileNames[0], Encoding.UTF8);
                    richTextBox1.Text = myText;
                }
                
            }
        }

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

Các bạn chỉ cần Enable thuộc tính AllowDrop = true.

và viết sự kiện drapdrop trên richtextbox như source code ở trên.
Chúc các bạn thành công với thủ thuật trên.

[CSHARP] Instructions for checking whether Gmail exists or not in csharp programming

Bài viết hôm nay, mình sẽ hướng dẫn các bạn cách kiểm tra một email có tồn tại hay không trong lập trình C#?
 
Bài viết hướng dẫn dưới đây mình sử dụng thư viện: EmailValidator.NET

[CSHARP] Hướng dẫn kiểm tra Gmail có tồn tại hay không trong lập trình csharp

Thư viện EmailValidator.NET chỉ hỗ trợ kiểm tra email trên hệ thống google mail (Gmail) thôi các bạn nhé.

Nếu các bạn nào có cách validator được hết các email thì có thể để lại comment bên dưới, góp ý thêm cho mình.

- Cài đặt thư viện EmailValidator.NET.

Cài đặt từ Nuget với câu lệnh sau:
Install-Package EmailValidator.NET

Hướng dẫn sử dụng thư viện code C#:
EmailValidator emailValidator = new EmailValidator();
EmailValidationResult result;

if (!emailValidator.Validate(email, out result))
{
    Console.WriteLine("Unable to check email") // no internet connection or mailserver is down / busy
}

switch (result)
{
    case EmailValidationResult.OK:
        Console.WriteLine("Mailbox exists");
        break;

    case EmailValidationResult.MailboxUnavailable:
        Console.WriteLine("Email server replied there is no such mailbox");
        break;

    case EmailValidationResult.MailboxStorageExceeded:
        Console.WriteLine("Mailbox overflow");
        break;

    case EmailValidationResult.NoMailForDomain:
        Console.WriteLine("Emails are not configured for domain (no MX records)");
        break;
}

Chúc mọi người thành công với thủ thuật trên, để tạo cho bản thân một chương trình tốt.
Theo LapTrinhVB.Net

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

[C#] GET CPU TEMPERATURE 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 lấy nhiệt độ của CPU đang hoạt động bằng ngôn ngữ lập trình C#.

[C#] Hướng dẫn viết ứng dụng đo nhiệt độ CPU đang hoạt động

Trong bài viết này mình sử dụng thư viện Open Hardware Monitor để lấy nhiệt độ hoạt động của CPU.
Thư viện này hoàn toàn mở nhé các bạn, các bạn có thể lấy các thông tin dễ dàng.

Đầu tiên các bạn cần download phần mềm Open Hardware Monitor từ link sau về:
https://openhardwaremonitor.org/downloads/

Giao diện sau khi cài đặt ứng dụng đo nhiệt độ CPU:


Sau khi cài đặt xong, các bạn import thư viện OpenHardwareMonitorLib.dll từ thư mục vừa cài đặt xong vào project của mình.

Sau khi, import thư viện xong, các bạn code cho C# như sau:

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

namespace TempCPU
{
    class Program
    {
        public class UpdateVisitor : IVisitor
        {
            public void VisitComputer(IComputer computer)
            {
                computer.Traverse(this);
            }
            public void VisitHardware(IHardware hardware)
            {
                hardware.Update();
                foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
            }
            public void VisitSensor(ISensor sensor) { }
            public void VisitParameter(IParameter parameter) { }
        }
        static void GetSystemInfo()
        {
            UpdateVisitor updateVisitor = new UpdateVisitor();
            Computer computer = new Computer();
            computer.Open();
            computer.CPUEnabled = true;
            computer.Accept(updateVisitor);
            for (int i = 0; i < computer.Hardware.Length; i++)
            {
                if (computer.Hardware[i].HardwareType == HardwareType.CPU)
                {
                    for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                    {
                        if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                            Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                    }
                }
            }
            computer.Close();
        }
        static void Main(string[] args)
        {
            while (true)
            {
                GetSystemInfo();
                Thread.Sleep(1000);
            }
        }
    }
}

Lưu ý: để chạy được ứng dụng yêu cầu hệ thống phải chạy dưới quyền Run Administrator, để xin quyền truy cập hệ thống.

Kết quả khi chạy phần mềm:

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

DOWNLOAD SOURCE CODE

PASSWORD UNZIP: HUNG.PRO.VN

on Thứ Hai, 1 tháng 7, 2024 | , , | A comment?