Thứ Năm, 28 tháng 10, 2021

Download file C# chuẩn

 //Download file C# chuẩn:

//==============================

public static string DownloadFile(string url, string folderName, string filename)

{

    //sample: https://vnn-imgs-f.vgcloud.vn/2021/10/19/22/ngam-ve-than-phan-phu-nu-xua-va-nay-3-240x160.jpg

    try

    {

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


        HttpWebResponse resp;


        try

        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Proxy = null;

            req.UserAgent = "Mozilla/5.0";

            //string tt = resp.ContentEncoding.ToUpperInvariant(); //GZIP or DEFLATE

            req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            resp = (HttpWebResponse)req.GetResponse();

            

        }

        catch (Exception)

        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Proxy = null;

            req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            resp = (HttpWebResponse)req.GetResponse();

        }


        using (resp)

        {

            string folderPath = folderName;

            if (!Directory.Exists(folderPath))

            {

                Directory.CreateDirectory(folderPath);

            }


            string filePath = folderName + ChuyenTuCoDauSangKoDau(HttpUtility.UrlDecode(filename, Encoding.UTF8));


            using (FileStream outputFileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))

            {

                resp.GetResponseStream().CopyTo(outputFileStream);

            }

        }

        return "";

    }

    catch (Exception ex)

    {

        return ex.Message;

    }

}


public static void Download111(string url, string  filename)

{

    using (WebDownload client = new WebDownload())

    {

        client.Headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

        client.DownloadFile(new Uri(url), filename);

    }

}

private static string ChuyenTuCoDauSangKoDau(string strUrl)

        {

            string str = strUrl.Trim().ToLower();

            while (str.LastIndexOf("  ") > 0)

                str = str.Replace("  ", "");

            return str.Replace(" ", "-").Replace("~", "").Replace("`", "").Replace("!", "").Replace("@", "").Replace("#", "").Replace("$", "").Replace("%", "").Replace("^", "").Replace("&", "-").Replace("=", "").Replace("(", "").Replace(")", "").Replace("+", "").Replace(",", "").Replace(">", "").Replace("<", "").Replace("'", "").Replace("đ", "d").Replace("á", "a").Replace("à", "a").Replace("ạ", "a").Replace("ả", "a").Replace("ã", "a").Replace("ă", "a").Replace("ắ", "a").Replace("ằ", "a").Replace("ặ", "a").Replace("ẳ", "a").Replace("ẵ", "a").Replace("â", "a").Replace("ấ", "a").Replace("ầ", "a").Replace("ậ", "a").Replace("ẩ", "a").Replace("ẫ", "a").Replace("ạ", "a").Replace("ê", "e").Replace("ế", "e").Replace("ề", "e").Replace("ể", "e").Replace("ễ", "e").Replace("ệ", "e").Replace("e", "e").Replace("é", "e").Replace("è", "e").Replace("ẹ", "e").Replace("ẻ", "e").Replace("ẽ", "e").Replace("i", "i").Replace("í", "i").Replace("ì", "i").Replace("ị", "i").Replace("ỉ", "i").Replace("ĩ", "i").Replace("o", "o").Replace("ó", "o").Replace("ò", "o").Replace("ọ", "o").Replace("ỏ", "o").Replace("õ", "o").Replace("ô", "o").Replace("ố", "o").Replace("ồ", "o").Replace("ộ", "o").Replace("ổ", "o").Replace("ỗ", "o").Replace("ơ", "o").Replace("ớ", "o").Replace("ờ", "o").Replace("ợ", "o").Replace("ở", "o").Replace("ỡ", "o").Replace("u", "u").Replace("ú", "u").Replace("ù", "u").Replace("ụ", "u").Replace("ủ", "u").Replace("ũ", "u").Replace("ư", "u").Replace("ứ", "u").Replace("ừ", "u").Replace("ự", "u").Replace("ử", "u").Replace("ữ", "u").Replace("y", "y").Replace("ý", "y").Replace("ỳ", "y").Replace("ỵ", "y").Replace("ỷ", "y").Replace("ỹ", "y").Replace("/", "-").Replace("?", "-").Replace("\"", "").Replace(":", "-").Replace(";", "-").Replace("--", "-");

        }

//========= Class webdownload

public class WebDownload : WebClient

{

    protected override WebRequest GetWebRequest(Uri address)

    {

        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);

        if (request != null)

        {

            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        }

        return request;

    }

}

Thứ Hai, 27 tháng 9, 2021

Fix Visual Studio 2019 freezing (crashing) while loading solution

 Fix Visual Studio freezing (crashing) while loading solution

===================

https://stackoverflow.com/questions/39703475/visual-studio-freezing-crashing-while-loading-solution


The issue reappeared after a few days, so I located the user settings for Visual Studio 2019:

%USERPROFILE%\AppData\Roaming\Microsoft\VisualStudio\16.0_f124b472

and deleting the following files seemed to have reset VS to a normal state:

Delete only: User.vsk

It works!!


 // Current.vsk

 // ObjBrowEx.dat


Please close all your solutions before deleting the files

Thứ Năm, 9 tháng 9, 2021

Tạo CRC-8 với giá trị hexadecimal (hệ 16) value dựa trên Poly trong C#

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ReadEpubHtml

{

    public class CrcCalculator

    {

        /// <summary>

        /// Get CRC-8

        /// </summary>

        /// <param name="input"></param>

        /// <returns></returns>

        public static string GetValue(string input)

        {

            return ComputeChecksum(Encoding.ASCII.GetBytes(input)).ToString("X2");

        }


        //Tạo Table dựa trên poly (https://crccalc.com/)

        private static byte poly = 0x07; //0xd5;

        static byte[] table = new byte[256];

        private static byte[] Crc8Table()

        {

            for (int i = 0; i < 256; ++i)

            {

                int temp = i;

                for (int j = 0; j < 8; ++j)

                {

                    if ((temp & 0x80) != 0)

                    {

                        temp = (temp << 1) ^ poly;

                    }

                    else

                    {

                        temp <<= 1;

                    }

                }

                table[i] = (byte)temp;

            }

            return table;

        }


        // vị trí trong CRCtable

        private static byte ComputeChecksum(params byte[] bytes)

        {

            Crc8Table();


            byte crc = 0;

            if (bytes != null && bytes.Length > 0)

            {

                foreach (byte b in bytes)

                {

                    crc = table[crc ^ b];

                }

            }

            return crc;

        }

    }

}


Thứ Tư, 18 tháng 8, 2021

Redis cache data C#

 

1. Cài  Redis: https://github.com/microsoftarchive/redis/releases

2. Sau khi cài Redis, mở Terminal gõ: redis-cli nếu hiện vd: 127.0.0.1:6379> là OK

3. Một số lện Redis trên Terminal:

redis-cli

info memory

config get maxmemory

config set maxmemory 128M

4. Tắt/Bật redis thì vào services.msc tới tiến trình Redis

5. Cài nuget package:  Install-Package StackExchange.Redis -Version 1.2.6

(dành cho phiên bản .NET 4.5)

Lưu ý: không dùng Package ServiceStack.Redis vì tính phí (giới hạn 6000 request)

6. Trình quản lý giao diện: cài Another-Redis-Desktop-Manager.1.4.8

7. Code demo:

public string GetRedisValue()

        {

            //-- Install-Package StackExchange.Redis -Version 1.2.6

            var cachedKey = "key";

            string value;

            // cách 1: var redisDb = RedisConnectorHelper.Connection.GetDatabase();

           //cách 2:

         using (var redis = ConnectionMultiplexer.Connect("localhost:6379"))

            {

                IDatabase db = redis.GetDatabase();

                

                if (!db.KeyExists(cachedKey))

                {

                    value = DateTime.Now.ToString();

                    //set new value

                    db.StringSet(cachedKey, value, TimeSpan.FromSeconds(18));

                }

                else

                {

                    //get cached value

                    value = db.StringGet(cachedKey);

                }

            }

            return value;

        }

+ Theo cách 1: tạo thêm 1 class: RedisConnectorHelper

/// <summary>

    /// Usage: var redisDb = RedisConnectorHelper.Connection.GetDatabase();

    /// </summary>

    public class RedisConnectorHelper

    {

        static RedisConnectorHelper()

        {

            lazyConnection = new Lazy<ConnectionMultiplexer>(() =>

            {

                return ConnectionMultiplexer.Connect("localhost");

            });

        }

        private static Lazy<ConnectionMultiplexer> lazyConnection;

        public static ConnectionMultiplexer Connection

        {

            get

            {

                return lazyConnection.Value;

            }

        }

    }




Thứ Tư, 30 tháng 6, 2021

Cấu hình chạy flutter trên Ubuntu 16.04 LTS

Cấu hình đường dẫn flutter trên Ubuntu:

Trong Terminal: 

1. Cài vim:

sudo apt-get update

sudo apt-get install vim


2. Kiểm tra vim đã được cài đặt thành công hay chưa

vim -v


3. Tải flutter và giải nén, trỏ đến đường dẫn của flutter/bin tải về:

cd /home/YOUR_NAME/Downloads/flutter/bin

pwd

  được đường dẫn: /home/YOUR_NAME/Downloads/flutter/bin


vim ~/.bashrc

Nhấn enter và cuối dòng ta có được: export PATH="$PATH:/home/YOUR_NAME/Downloads/flutter/bin"

Cấu hình chạy flutter trên MacOs Catalina

Trong terminal, gõ từng lệnh sau:

touch ~/.zshrc

open ~/.zshrc

Trong file .zshrc vừa tạo, thêm dòng sau và lưu lại:

export PATH="/Users/YOUR_NAME/Downloads/flutter/bin:$PATH"

(với YOUR_NAME là tên thư mục của bạn)

Thứ Năm, 4 tháng 3, 2021

Fix lỗi cài Visual Studio 2019

 Fix lỗi cài Visual Studio 2019:

------------------------------

Mở CMD gõ lần lượt từng lệnh:


%windir%\system32\msiexec.exe /unregister

%windir%\system32\msiexec.exe /regserver

%windir%\syswow64\msiexec.exe /unregister

%windir%\syswow64\msiexec.exe /regserver

Thứ Tư, 17 tháng 2, 2021

Multi language Flutter

 

Multi language Flutter

 


import 'dart:io';
import
'package:flutter/material.dart';
import
'package:flutter_localizations/flutter_localizations.dart';

void main() async {
 
WidgetsFlutterBinding.ensureInitialized();

 
// Get the initial locale values
 
final String defaultSystemLocale = Platform.localeName;
 
final List<Locale> systemLocales = WidgetsBinding.instance.window.locales;

 
// Define locales that our app supports (no country codes, see comments below)
 
final appSupportedLocales = <Locale>[
   
Locale('ru'),
   
Locale('en'),
  ];

 
final MyApp myApp = MyApp(defaultSystemLocale, systemLocales);

  runApp(
     
MaterialApp(
        title:
'MyApp',
        home:
myApp,
        supportedLocales:
appSupportedLocales,
        localizationsDelegates: [
          
// These are default localization delegates that implement the very basic translations for standard controls and date/time formats.
         
GlobalMaterialLocalizations.delegate,
         
GlobalWidgetsLocalizations.delegate,
        ],
      )
  );
}

class MyApp extends StatefulWidget {
 
// Store initial locale settings here, they are unchanged
 
final String initialDefaultSystemLocale;
 
final List<Locale> initialSystemLocales;

 
MyApp(this.initialDefaultSystemLocale, this.initialSystemLocales);

 
@override
 
_MyAppState createState() => _MyAppState();
}


class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
 
// Store dynamic changeable locale settings here, they change with the system changes
 
String currentDefaultSystemLocale;
 
List<Locale> currentSystemLocales;

 
// Here we read the current locale values
 
void setCurrentValues() {
   
currentSystemLocales = WidgetsBinding.instance.window.locales;
   
currentDefaultSystemLocale = Platform.localeName;
  }

 
@override
 
void initState() {
   
// This is run when the widget is first time initialized
   
WidgetsBinding.instance.addObserver(this); // Subscribe to changes
   
setCurrentValues();
   
super.initState();
  }

 
@override
 
void didChangeLocales(List<Locale> locale) {
   
// This is run when system locales are changed
   
super.didChangeLocales(locale);
   
// Update state with the new values and redraw controls
   
setState(() {
      setCurrentValues();
    });
  }

 
@override
 
Widget build(BuildContext context) {
   
return Scaffold(
      appBar:
AppBar(),
      body:
Column(
        crossAxisAlignment:
CrossAxisAlignment.start,
        mainAxisAlignment:
MainAxisAlignment.start,
        children: <
Widget>[
         
Text('Initial system default locale: ${widget.initialDefaultSystemLocale}.'),
         
Text('Initial language code: ${widget.initialDefaultSystemLocale.split('_')[0]}, country code: ${widget.initialDefaultSystemLocale.split('_')[1]}.'),
         
Text('Initial system locales:'),
         
for (var locale in widget.initialSystemLocales) Text(locale.toString()),
         
Text(''),
         
Text('Current system default locale: ${currentDefaultSystemLocale}.'),
         
Text('Current system locales:'),
         
for (var locale in currentSystemLocales) Text(locale.toString()),
         
Text(''),
         
Text('Selected application locale: ${Localizations.localeOf(context).toString()}.'),
         
Text(''),
         
Text('Current date: ${Localizations.of<MaterialLocalizations>(context, MaterialLocalizations).formatFullDate(DateTime.now())}.'),
         
Text('Current time zone: ${DateTime.now().timeZoneName} (offset ${DateTime.now().timeZoneOffset}).'),
        ],
      ),
    );
  }
}

 

Custom Lang class:

1. BaseLanguage.dart

import 'dart:io';

import 'lang_en.dart';
import 'lang_vi.dart';

abstract class BaseLanguage {
 
String hello;
}

/// Usage:
/// BaseLanguage lang;
/// @override
//   void initState() {
//     lang = LangUtils.getLang();
//     String testTitle = lang.hello;
//   }

class LangUtils {
 
static BaseLanguage getLang() {
   
String defaultLocale = Platform.localeName; //ex: en_US
   
print('defaultLocale = $defaultLocale');

   
switch (defaultLocale) {
     
case 'en_US':
       
return LangEn();
     
default:
       
return LangVi();
    }
  }
}

 

2. LangEn.dart

import 'BaseLanguage.dart';

// en_US
class LangEn implements BaseLanguage {
 
@override
 
String hello = 'hello';
}

 

3. LangVi.dart

import 'BaseLanguage.dart';

// vi_VN
class LangVi implements BaseLanguage {
 
@override
 
String hello = 'Xin chào';
}