UWInfo Blog
發表新文章
[Join] | [忘記密碼] | [Login]
搜尋

搜尋意見
文章分類-#Author#
[所有文章分類]
所有文章分類
  • ASP.NET (48)
  • ASP.NET2.0 (15)
  • ASP.NET4.0 (34)
  • JavaScript (49)
  • jQuery (26)
  • FireFox (4)
  • UW系統設定 (3)
  • SQL (39)
  • SQL 2008 (25)
  • mirror (4)
  • SVN (4)
  • IE (9)
  • IIS (20)
  • IIS6 (1)
  • 閒聊 (7)
  • W3C (6)
  • 作業系統 (9)
  • C# (24)
  • CSS (12)
  • FileServer (1)
  • HTML 5 (11)
  • CKEditor (3)
  • UW.dll (13)
  • Visual Studio (16)
  • Browser (8)
  • SEO (1)
  • Google Apps (3)
  • 網站輔助系統 (4)
  • DNS (5)
  • SMTP (4)
  • 網管 (11)
  • 社群API (3)
  • SSL (4)
  • App_Inventor (1)
  • URLRewrite (2)
  • 開發工具 (6)
  • JSON (1)
  • Excel2007 (1)
  • 試題 (3)
  • LINQ (1)
  • bootstrap (0)
  • Vue (3)
  • IIS7 (3)
  • foodpanda (2)
  • 編碼 (2)
  • 資安 (3)
  • Sourcetree (1)
  • MAUI (1)
  • CMD (1)
  • my sql (1)
最新回應
  • Newtonsoft.Json.JsonConvert.DeserializeObject 失敗的情況
    test...more
  • dotnet ef dbcontext scaffold
    ...more
  • [ASP.NET] 利用 aspnet_regiis 加密 web.config
    ...more
  • IIS ARR (reverse proxy) 服務安裝
    ...more
  • [錯誤訊息] 請加入 ScriptResourceMapping 命名的 jquery (區分大小寫)
    ...more
  • 用 Javascript 跨網頁讀取 cookie (Cookie cross page, path of cookie)
    ...more
  • 線上客服 - MSN
    本人信箱被盜用以致資料外洩,是否可以請貴平台予以協助刪除該信箱之使用謝謝囉...more
  • 插入文字到游標或選取處
    aaaaa...more
  • IIS 配合 AD (Active Directory) 認証, 使用 .Net 6.0
    太感謝你了~~~你救了我被windows 認證卡了好幾天QQ...more
  • PostgreSQL 的 monitor trigger
    FOR EACH ROW 可能要改為 FOR EACH STATEMENT ...more
標籤
  • 執行緒
  • let
  • 貝克街
  • html5
  • virtual
  • -5304
  • 黑貓 EGS
  • promise
  • Z2DfxURz
  • 476
  • 826
  • 80
  • 20
  • DxHizbmA
  • Contains
  • 4429
  • 466
  • LISTENING
  • aspx ORDER
  • validation
  • 12
  • ggx4yzki
  • inline
  • d8yl.com
  • remote
  • 218
  • WYvoIJMf
  • 696
  • DBCC
  • 0x71786b6b
  • write
  • exception
  • 0x42121121
  • 88.4raJb
  • ValidatePa
  • 6593
  • 6811
  • timeout212
  • 追踪
  • Fortigate
  • Shopee
  • CK
  • 0
  • 要求長度
  • wKFpHE57
  • ip21211211
  • .
  • ie
  • dependency
  • EGS
頁數 1 / 5 下一頁
搜尋 table 結果:
Chrome 連接藍芽 BLE 印表機(出單機),使用 ESC / POS 列印繁體中文和 Qrcode
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BLE Printer Test</title>
    <script src="https://cdn.jsdelivr.net/npm/iconv-lite-umd@0.6.10/lib/iconv-lite-umd.js"></script>
</head>
<body>
    <h1>BLE Printer Test 123</h1>
    <button id="printTestButton">Test Print</button>
    <button id="printAgain">Print Again</button>
    <pre id="log"></pre>
    <script>
        // Function to log messages on the page
        function logMessage(message) {
            const logElement = document.getElementById('log');
            logElement.textContent += message + '\n';
        }
        var device;
        var server;
        var service;
        var characteristic;
        var name = 'T58_6752'; // 藍芽設備的名稱
        var uuid = 0x1800; //service UUID (用 BLE Scanner 找到的)
        var characteristicUuid = 0x2A00; // characteristic UUID (用 BLE Scanner 找到的)
        // Function to connect to BLE printer and send test data

        async function connectAndTestPrint() {

            try {
                logMessage("Requesting Bluetooth device...");

                // Request the BLE device
                device = await navigator.bluetooth.requestDevice({
                    //acceptAllDevices: true,
                    filters: [
                        { name: name }
                    ],
                    optionalServices: [uuid] // Replace with the correct service UUID
                });

                logMessage(`Device selected: ${device.name}`);
                logMessage(`Device uuid: ${device.id}`);

                await printAgain();


            } catch (error) {
                logMessage(`Error: ${error.message}`);
            }
        }

        // 转码方法
        function stringToGbk(str) {
            const ranges = [
                [0xA1, 0xA9, 0xA1, 0xFE],
                [0xB0, 0xF7, 0xA1, 0xFE],
                [0x81, 0xA0, 0x40, 0xFE],
                [0xAA, 0xFE, 0x40, 0xA0],
                [0xA8, 0xA9, 0x40, 0xA0],
                [0xAA, 0xAF, 0xA1, 0xFE],
                [0xF8, 0xFE, 0xA1, 0xFE],
                [0xA1, 0xA7, 0x40, 0xA0],
            ]
            const codes = new Uint16Array(23940)
            let i = 0

            for (const [b1Begin, b1End, b2Begin, b2End] of ranges) {
                for (let b2 = b2Begin; b2 <= b2End; b2++) {
                    if (b2 !== 0x7F) {
                        for (let b1 = b1Begin; b1 <= b1End; b1++) {
                            codes[i++] = b2 << 8 | b1
                        }
                    }
                }
            }
            const cstr = new TextDecoder('gbk').decode(codes)

            // 编码表
            const table = new Uint16Array(65536)
            for (let i = 0; i < cstr.length; i++) {
                table[cstr.charCodeAt(i)] = codes[i]
            }
            const buf = new Uint8Array(str.length * 2)
            let n = 0

            for (let i = 0; i < str.length; i++) {
                const code = str.charCodeAt(i)
                if (code < 0x80) {
                    buf[n++] = code
                } else {
                    const gbk = table[code]
                    buf[n++] = gbk & 0xFF
                    buf[n++] = gbk >> 8
                }
            }
            u8buf = buf.subarray(0, n)
            // console.log(u8buf);
            return u8buf
        }

        async function printAgain() {
            // Connect to the GATT server
            server = await device.gatt.connect();
            logMessage("Connected to GATT server.");

            // Get the printer service
            service = await server.getPrimaryService(uuid); // Replace with your printer's service UUID
            logMessage("Printer service retrieved.");

            // Get the characteristic for writing data
            characteristic = await service.getCharacteristic(characteristicUuid); // Replace with the correct characteristic UUID
            logMessage("Printer characteristic retrieved.");

            // Prepare test print data
            const encoder = new TextEncoder();
            const testData = encoder.encode("TEST PRINT: Hello from Web Bluetooth!\n");
            const finalData = encoder.encode("--\n--\n \n \n");

            const setFontSize = new Uint8Array([0x1D, 0x21, 0x11]); // GS ! n
            const setFontSize2 = new Uint8Array([0x1D, 0x21, 0x22]); // GS ! n
            const setFontSize3 = new Uint8Array([0x1D, 0x21, 0x33]); // GS ! n

            // Write test data to the printer
            logMessage("Sending test data to printer...");

            await characteristic.writeValue(new Uint8Array([0x1D, 0x21, 0x00]));
            await characteristic.writeValue(encoder.encode("1x1!\n"));
            await characteristic.writeValue(setFontSize);
            await characteristic.writeValue(encoder.encode("2x2!\n"));
            await characteristic.writeValue(setFontSize2);
            await characteristic.writeValue(encoder.encode("3x3!\n"));
            await characteristic.writeValue(setFontSize3);
            await characteristic.writeValue(encoder.encode("4x4!\n"));


            const initPrinter = new Uint8Array([0x1B, 0x40]); // ESC @
            await characteristic.writeValue(initPrinter);

            // 3. 設置字符集為 GBK
            const setGBK = new Uint8Array([0x1B, 0x74, 0x11]); // ESC t 0x11 (GBK)
            await characteristic.writeValue(setGBK);

            const text = "繁體中文測試\n \n";
            const encodedText = stringToGbk(text);
            await characteristic.writeValue(encodedText);
            logMessage("Test data sent successfully!");

            // QrCode 列印
            const qrData = "https://example.com"; // Your QR code data
            const qrDataLength = qrData.length + 3;
            const pL = qrDataLength & 0xFF; // Low byte
            const pH = (qrDataLength >> 8) & 0xFF; // High byte

            const commands = [
                0x1B, 0x40, // Initialize printer
                0x1D, 0x28, 0x6B, pL, pH, 0x31, 0x50, 0x30, ...new TextEncoder().encode(qrData), // Store data
                0x1D, 0x28, 0x6B, 0x03, 0x00, 0x31, 0x51, 0x30 // Print QR code
            ];

            const buffer = new Uint8Array(commands);
            await characteristic.writeValue(buffer);
            logMessage("QrCode sent successfully!");

            await characteristic.writeValue(finalData);
            logMessage("finalData sent successfully!");

            // Disconnect the GATT server
            server.disconnect();
            logMessage("Disconnected from printer.");
        }

        // Bind the function to the button
        document.getElementById('printTestButton').addEventListener('click', connectAndTestPrint);
        document.getElementById('printAgain').addEventListener('click', printAgain);
    </script>
</body>
</html>
More...
Bike, 2025/1/2 下午 02:20:15
postgreSql 大型 table 跑 Count 非常慢
可參考本文章:

https://dba.stackexchange.com/questions/245990/postgresql-extremely-slow-count-with-index-simple-query

vacuum analyze insider_event;
執行了 7 分鐘

ALTER TABLE insider_event SET (autovacuum_vacuum_scale_factor = 0, autovacuum_analyze_scale_factor = 0,  autovacuum_vacuum_threshold = 10000, autovacuum_analyze_threshold = 10000);

跑了 1.2 分鐘

修改 work_mem:
https://www.pgmustard.com/blog/work-mem

記憶體調整
https://www.enterprisedb.com/postgres-tutorials/how-tune-postgresql-memory
More...
Bike, 2024/2/5 上午 06:55:40
查詢佔用 CPU 的排程
DECLARE @tblVariable TABLE(SPID INT, Status VARCHAR(200), [Login] VARCHAR(200), HostName VARCHAR(200), 
    BlkBy VARCHAR(200), DBName VARCHAR(200), Command VARCHAR(200), CPUTime INT, 
    DiskIO INT, LastBatch VARCHAR(200), ProgramName VARCHAR(200), _SPID INT, 
    RequestID INT)

INSERT INTO @tblVariable
EXEC Master.dbo.sp_who2

SELECT v.*, t.TEXT 
FROM @tblVariable v
INNER JOIN sys.sysprocesses sp ON sp.spid = v.SPID
CROSS APPLY sys.dm_exec_sql_text(sp.sql_handle) AS t
ORDER BY BlkBy DESC, CPUTime DESC

kill xxx

參考: https://learn.microsoft.com/en-us/answers/questions/842347/sql-server-how-to-find-out-who-lock-my-specific-ta
More...
Bike, 2023/8/17 上午 10:44:05
Entity Framework 用起來和 Daper 越來越像了
Entity Framework 提供了 ExecuteSqlRawAsync 和 FromSqlRaw  之後,可以和 Dapper 非常類似的用法。

我們在用 Dapper 時。最常用的就是 sql command 加上一個物件做為參數,就可以執行 CRUD 的動作。

其實用 Entity Framework 的 ExecuteSqlRawAsync 和 FromSqlRaw 也可以逹到幾乎一樣的效果。

ExecuteSqlRawAsync 和 FromSqlRaw 接受的參數是 object array (其實是 Microsoft.Data.SqlClient.SqlParameter 的 array)

所以我們先做一個 Object to Microsoft.Data.SqlClient.SqlParameter Array 的擴充, 可參考: https://gist.github.com/aliozgur/75182b2e9b0a58b83443

不過很奇怪的是,原作者提供的擴充轉出來的會是 System.Data.SqlClient.SqlParameter  Array 無法直接使用於 ExecuteSqlRawAsync 和 FromSqlRaw,所以要稍微改一下,把 using System.Data.SqlClient; 改為 using Microsoft.Data.SqlClient; 即可:



另外,我們再自行 對 DbContext 做一個擴充如下:

        /// <summary>
        /// 會把物件 Parameter 的各 Property 帶入 SQL 中.
        /// </summary>
        /// <param name="dbct"></param>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static async Task<int> ExecuteParameterSqlAsync(this DbContext dbct, string sql, object parameters)
        {
            return await dbct.Database.ExecuteSqlRawAsync(sql, parameters.ToSqlParamsArray());
        }



最後的結果可以做到以下的效果: (res3 和 res4 是配合 FormattableString 的範例 )

 
範例程式碼:
        public async Task<object> EfTest()
        {
            var dbct = Ds.NewContext.GvContext;
            var insertSql = @"Insert into ProfileEvent(JobId,[Name],GvShoplineId,LiShoplineId,Phone,Email,LineId,GaClientId)
            Values(@JobId, @Name, null , null , null , @Email, @GaClientId , @GaClientId )";

            //執行 SQL 的原生寫法
            await dbct.Database.ExecuteSqlRawAsync(insertSql, new object[]
            {
                new SqlParameter("@JobId", 10),
                new SqlParameter("@Email", "XX'TT"),
                new SqlParameter("@Name", "AA'BB"),
                new SqlParameter("@GaClientId", "GaClientId"),
            });

            //執行 SQL 的擴充寫法
            await dbct.ExecuteParameterSqlAsync(insertSql, new
            {
                JobId = 10,
                Email = "XX'TT",
                Name = "AA'BB",
                GaClientId = "GaClientId"
            });

            //關於查詢
            string name = "%'B%";
            //原生寫法
            var res1 = await dbct.ProfileEvents.FromSqlRaw("Select top 100 * from ProfileEvent where Name like @name",
                new object[]
                    {
                        new SqlParameter("@name", "%'B%")
                    })
                .ToListAsync();

            //擴充, object to SqlParameter array
            var res2 = await dbct.ProfileEvents.FromSqlRaw("Select top 100 * from ProfileEvent where Name like @name",
                new { name }.ToSqlParamsArray())
                .ToListAsync();

            var res3 = await dbct.ProfileEvents.FromSql($"Select top 100 * from ProfileEvent where Name like {name}")
                .ToListAsync();

            var res4 = await dbct.ProfileEvents.FromSqlInterpolated($"Select top 100 * from ProfileEvent where Name like {name}")
                .ToListAsync();

            return new { res1, res2, res3, res4 };
        }

 
More...
Bike, 2023/5/6 下午 05:37:19
Visual Studio DbContext Scaffold
關於Scaffold的參數,官網雖然有文件但不是很好找,因此在此紀錄一下。
(於PM Console輸入'dotnet ef dbcontext scaffold -h'也可以查看)

-d | --data-annotations : 使用屬性定義模型
-c | --context <NAME> : 產生的DbContext名稱
--context-dir <PATH> : 產生的DbContext位置
-f | --force : 覆寫現有檔案
-o | --output-dir <PATH> : 產生的Entity Model位置
--schema <SCHEMA_NAME1>, <SCHEMA_NAME2>... : 指定Schemas產生Entity
-t | --table <TABLE_NAME1>, <TABLE_NAME2>... : 指定Table產生Entity
--use-database-names : 強制使用DB中Table與Column Name
--json : 輸出Json格式資料表於PM Console
-n | --namespace <NAMESPACE> : 指定命名空間,預設會依照專案與資料夾命名
--context-namespace <NAMESPACE> : 指定DbContext命名空間,預設會依照專案與資料夾命名
--no-onconfiguring : 不產生DbContext中的OnConfiguring
--no-pluralize : 關閉自動複數判別
-p | --project <PROJECT> : 指定專案
-s | --startup-project <PROJECT> : 指定指令執行時起始專案
--framework <FRAMEWORK> : 指定框架版本
--configuration <CONFIGURATION> : 指定配置
--no-build : 跳過專案建置
More...
梨子, 2022/12/15 下午 12:12:11
Orable table lock soluiton
當發現於Developer下Script時,ScriptRunner一直在跑都不會停的時候,請先暫停該Query。

1. 查出哪隻Session將Table lock住了
select b.owner,b.object_name,a.session_id,a.locked_mode from v$locked_object a,dba_objects b where b.object_id = a.object_id;

2. 取得該Session SID與SERIAL#,順便可以看是哪個SQL帳號Lock的
select b.username,b.sid,b.serial#,logon_time from v$locked_object a,v$session b where a.session_id = b.sid order by b.logon_time;

3. 使用下面這段SQL,帶入SID與SERIAL#即可將該Session Kill
alter system kill session'{SID}, {SERIAL#}';
More...
梨子, 2022/10/26 下午 08:35:31
資料庫 where 條件要注意的兩件事
最近剛好發生跟 MS SQL 有關的狀況,所以就記錄一下

1. where 字串欄位要不要加 N''  (unicode)
    範例: Select * from OrderDetail where OrderDetailId= N'20220923084533'
    基本上,欄位是 char、varchar 就不需要。nvarchar nchar 就要加 N
    這好像是廢話,但往往寫程式會沒注意,甚至是會覺得通通加 N 比較沒問題
    但如果欄位牽涉到 index 就會影響搜尋 ,所以寫程式當下要注意
-- 假設 OrderDetailId 是 varchar(20)
-- OrderDetail 有千萬筆資料

Select * from OrderDetail where OrderDetailId= N'20220923084533'
-- 結果跑超級久 (未使用 PK 找,掃整個 table)
Select * from OrderDetail where OrderDetailId= '20220923084533'
-- 結果一下就出來 (使用 PK 找)
-- **資料庫設計最好以數值來當 key 比較好

    
2.  當欄位有 null 值,where [clumnName] not in ('A')  也會排除 null 的狀況
     直覺上,只要下 not in (..)  那會其他項目都會抓出,但是實際上,該欄位是 null的資料也會被排除
     因為資料庫一旦你對某欄位下條件,他就會排除 null 的欄位,除非你指定  [clumnName] is null 才會有資料
 
More...
darren, 2022/9/23 下午 04:06:22
PostgreSQL 的 monitor trigger
--建立 table (要記得改 XXX)
CREATE TABLE IF NOT EXISTS public.table_monitor
(
    table_name text COLLATE pg_catalog."default" NOT NULL,
    update_at timestamp without time zone NOT NULL DEFAULT now(),
    update_count bigint NOT NULL DEFAULT 0,
    CONSTRAINT table_monitor_pkey PRIMARY KEY (table_name)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public.table_monitor
    OWNER to XXX;

-- 這一段只要執行一次
CREATE OR REPLACE FUNCTION public.table_monitor_trigger_fnc()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF
AS $BODY$
BEGIN
     Update public.table_monitor Set update_count = update_count + 1, update_at = now()  Where table_name = TG_TABLE_NAME; 
RETURN NEW;
END;
$BODY$;

ALTER FUNCTION public.table_monitor_trigger_fnc()
    OWNER TO XXX;

-- 對於被監控的 table, 要執行以下的指令,記得 monitor_table_name 要改為 table 的名字(要符合大小寫)
INSERT INTO public.table_monitor (table_name, update_at, update_count) VALUES ('monitor_table_name', '2000-01-01', 0) ON CONFLICT DO NOTHING;

CREATE OR REPLACE TRIGGER table_monitor_trigger
    AFTER INSERT OR DELETE OR UPDATE 
    ON monitor_table_name
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.table_monitor_trigger_fnc();

監控用的程式碼:
public static void UpdateTableCache()
{
    //標記自已是正在執行的 Thread. 讓舊的 Thread 在執行完畢之後, 應該會自動結束. 以防舊的 Thread 執行超過 10 秒.
    CurrentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

    try
    {
        //確認自已是正在執行的 Thread, 重覆執行. (另一個 Thread 插入執行)
        while (CurrentThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId)
        {
            LastUpdateDate = DateTime.Now;

            foreach (var dbId in CachedDbs)
            {
                var sql = @"select * from table_monitor";

                var dt = Su.PgSql.DtFromSql(sql, dbId);

                foreach (DataRow row in dt.Rows)
                {
                    string changeId = row["update_count"].DBNullToDefault();
                    string CacheKey = TableCacheKey(dbId, row["table_name"].DBNullToDefault());
                    ObjectCache cache = MemoryCache.Default;

                    string OldValue = (string)cache[CacheKey];

                    if (OldValue == null)
                    {
                        cache.Set(CacheKey, changeId, DateTime.MaxValue);
                    }
                    else
                    {
                        if (changeId != OldValue)
                        {
                            cache.Remove(CacheKey);
                            cache.Set(CacheKey, changeId, DateTime.MaxValue);
                        }
                    }
                }
            }

            //每兩秒檢查一次
            System.Threading.Thread.Sleep(2000);
        }
    }
    catch (Exception)
    {
        //依經驗, 只要 DB 能通, 這裡幾乎不會有問題, 所以這裡暫時不處理, 未來有問題時可以考慮寫入文字檔比較好.
    }
}
More...
Bike, 2022/7/20 上午 10:05:39
資料存取架構比較 Entity Framework, Data Table, Dapper
比較方式: 對相同的資料表讀取 1000 次,來比較速度。
資料庫為 MS SQL

這裡做了 4 個 Case:

Case 1: 
使用 Entity Framework,DbContext 為每次 new 一個。

Case 2:
使用 Entity Framework,使用同一個 DbContext。

Case 3:
用 DAO,轉為 Data Table 的格式 (使用 DtFromSql)。

Case 4:
使用 Dapper。

專案啟動時的記憶體使用量約為:  123 MB



測試一:
第一次讀取
Case 1, 時間: 3673.0303 ms, 記憶體: 566 MB

Case 2, 時間:  3889.9379 ms, 記憶體: 304 MB  (這個時間有時會測試到 3000 ms)

Case 3, 時間:  1665.7748 ms, 記憶體: 205 MB

Case 4, 時間:  1639.7211 ms, 記憶體: 193 MB

讀取五次
Case 1, 時間: 1984.6395, 記憶體: 544MB (有發生 GC)


Case 2, 時間:  2367.9792 ms, 記憶體: 627 MB (沒有發生 GC)


Case 3, 時間:  1395.1132 ms, 記憶體: 280 MB (有發生 GC)



Case 4, 時間:  1531.3555 ms, 記憶體: 271 MB


結果: Dapper 看來完勝,速度上和直接使用 DAO 轉進 Data Table 的速度相近。但 Dapper 傳回的結果已經轉換為物件 List, 操作上會更為方便。

Entity Framework 一如預期的較慢,且花費較多的記憶體。但和想像中最大的差異是,使用同一個 DbContext 比 new 1000 個 DbContext  的速度還要慢, 花費的記憶體在 GC 之後,差異不大。

所以不一定要用 DI 注入 DbContext, 在各 function 中一直傳遞 DbContext. 在 Static 的 function 中,可以安心的 new 一個 DbContext 出來使用吧,只是要記得用 using 哦,否則可能會有 connection 沒有關閉的問題。


 
More...
Bike, 2022/7/18 上午 09:46:34
使用 Gmail API 及 Google API 憑證的取得流程
這裡是我測試 Gmail API 和 Google API 憑証的一些記錄。

如果你的目的是要使用 Gmail Api 取代舊的 Gmail SMTP 來發送通知信,建議你先跳到最下方看一下結論。

如果你是想要看一下 Gmail API 和 Google API 憑証的使用方法,可以看一下這篇文章。

1. 在 google cloud platform 建立新的專案.
https://console.cloud.google.com/

 
 



啟用 Gmail API







 



 


 
 



因為我們要透過 OAuth  取得使用者授權,所以要設定使用 OAuth 的同意畫面。

 
指定授權的範圍
 

 
因為剛建立的專案,不會被公開,所以要指定測試使用者
 
如果要給任意使用者,必需經過發布的流程,但準備工作有點麻煩,所以這次就不發布了。
 




建立 OAuth 2.0 用戶端 ID 憑証
 
這裡除了名稱外,還有一個設定重導 Uri 的項目。現在不填寫,但稍後要回來補這個資料。
 
 
 下載 json 之後,命名為 client_secret.json 保留後續使用。


再來就要建立專案了. 用 VS2022 建立一個新專案
  


 




記錄網址, 本測試專案是 https://localhost:44340/ ,請依實際網址為準。



回到 OAuth 2.0 用戶端 ID 的設定頁. 在已授權的重新導向 URI 中填入 https://localhost:44340/Home/AuthReturn (填入的網址依實際專案的狀況,可能會有變化)
 
 

在 VS2022 中,使用 Nuget 安裝套件: (有漏的再麻煩和我說)
Google.Apis.Gmail.v1
Google.Apis.Auth
MimeKit (發送 gmail 時使用)

建立認証用的網址:
建立一個 Action, 用來取得認証用的網址:
        /// <summary>
        /// 取得授權的項目
        /// </summary>
        static string[] Scopes = { GmailService.Scope.GmailSend };

        // 和登入 google 的帳號無關
        // 任意值,若未來有使用者認証,可使用使用者編號或登入帳號。
        string Username = "ABC";

        /// <summary>
        /// 存放 client_secret 和 credential 的地方
        /// </summary>
        string SecretPath = @"D:\project\GmailTest\Data\Secrets";

        /// <summary>
        /// 認証完成後回傳的網址, 必需和 OAuth 2.0 Client Id 中填寫的 "已授權的重新導向 URI" 相同。
        /// </summary>
        string RedirectUri = $"https://localhost:44340/Home/AuthReturn";

        /// <summary>
        /// 取得認証用的網址
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetAuthUrl()
        {
            using (var stream = new FileStream(Path.Combine(SecretPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                FileDataStore dataStore = null;
                var credentialRoot = Path.Combine(SecretPath, "Credentials");
                if (!Directory.Exists(credentialRoot))
                {
                    Directory.CreateDirectory(credentialRoot);
                }

                //存放 credential 的地方,每個 username 會建立一個目錄。
                string filePath = Path.Combine(credentialRoot, Username);
                dataStore = new FileDataStore(filePath);

                IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
                    Scopes = Scopes,
                    DataStore = dataStore
                });

                var authResult = await new AuthorizationCodeWebApp(flow, RedirectUri, Username)
                .AuthorizeAsync(Username, CancellationToken.None);

                return authResult.RedirectUri;
            }
        }


執行結果:
 
用 chrome 開啟產生的網址: 


選取任一帳號,如果出現以下錯誤,請回到 "OAuth 同意畫面" 去新增測試使用者


 
因為應用程式尚未發布,所以會看到警告,勇敢的繼續下去


這裡會要求授權使用你的名義發送信件。(這是在程式中取得授權的項目 Scopes 中所指定的)


再繼續之後,會被重導至我們在 redirectUri  指定的網址。因為我們尚未完成,所以會看到錯誤,順便也可以看一下,會帶回哪一些參數。有 state, code, scope,共三個。


順便看一下,google 的套件會在 Credentials 的目錄下幫使用者建立一個目錄,在完成驗証前,會先放一個 System.String-oauth_XXX 的檔案,裡面的值和回傳的 state 是一樣的,這個應該是用來驗証回傳資料的。



接下來我們要新增 Action "AuthReturn" 如下:

        public async Task<string> AuthReturn(AuthorizationCodeResponseUrl authorizationCode)
        {
            string[] scopes = new[] { GmailService.Scope.GmailSend };

            using (var stream = new FileStream(Path.Combine(SecretPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                //確認 credential 的目錄已建立.
                var credentialRoot = Path.Combine(SecretPath, "Credentials");
                if (!Directory.Exists(credentialRoot))
                {
                    Directory.CreateDirectory(credentialRoot);
                }

                //暫存憑証用目錄
                string tempPath = Path.Combine(credentialRoot, authorizationCode.State);            

                IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
                    Scopes = scopes,
                    DataStore = new FileDataStore(tempPath)
                });

                //這個動作應該是要把 code 換成 token
                await flow.ExchangeCodeForTokenAsync(Username, authorizationCode.Code, RedirectUri, CancellationToken.None).ConfigureAwait(false);

                if (!string.IsNullOrWhiteSpace(authorizationCode.State))
                {                
                    string newPath = Path.Combine(credentialRoot, Username);
                    if (tempPath.ToLower() != newPath.ToLower())
                    {
                        if (Directory.Exists(newPath))
                            Directory.Delete(newPath, true);

                        Directory.Move(tempPath, newPath);
                    }
                }

                return "OK";
            }
        }


再跑一次上面的流程,最後回到 AuthReturn

在 D:\project\GmailTest\Data\Secrets\Credentials\ABC 裡面會產生一個檔案: 這個就是我們的 token 了。


看一下裡面的內容, 有 access_token, refresh_token, scope 等等, 用途應該很好猜了.. 不知道各項目的目途也沒有關係。只要有這個 token 就可以了。


refresh_token 的效期請參考以下文件:
https://developers.google.com/identity/protocols/oauth2 。也可以參考下圖, 若是要用 gmail api 來發送通知信(例如連絡我們),紅色的地方是比較令人困擾的,例如 6 個月以上,沒有人留言,原來留下的 refresh_token 就失效了。使用者必需重新建立一個 refresh_token 。

 
最後來使用 gmail api 發送通知信, 直接看程式碼如下: 在這個過程中遇到最大的問題除了憑証問題之外,另一個問題是編碼。直到最後找到可以用 MimeKit 把 System.Net.Mail.MailMessage 編碼成 Gmail API 的格式才解決。程式碼如下:

        public async Task<bool> SendTestMail()
        {
            var service = await GetGmailService();

            GmailMessage message = new GmailMessage();
            message.Subject = "標題";
            message.Body = $"<h1>內容</h1>";
            message.FromAddress = "bikehsu@gmail.com";
            message.IsHtml = true;
            message.ToRecipients = "bikehsu@gmail.com";
            message.Attachments = new List<Attachment>();

            string filePath = @"C:\Users\bike\Pictures\Vegetable_pumpkin.jpg";    //要附加的檔案
            Attachment attachment1 = new Attachment(filePath);
            message.Attachments.Add(attachment1);

            SendEmail(message, service);
            Console.WriteLine("OK");

            return true;
        }

        async Task<GmailService> GetGmailService()
        {
            UserCredential credential = null;

            var credentialRoot = Path.Combine(SecretPath, "Credentials");
            if (!Directory.Exists(credentialRoot))
            {
                Directory.CreateDirectory(credentialRoot);
            }

            string filePath = Path.Combine(credentialRoot, Username);

            using (var stream = new FileStream(Path.Combine(SecretPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                Username,
                CancellationToken.None,
                new FileDataStore(filePath));
            }

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Send Mail",
            });

            return service;
        }


        public class GmailMessage
        {
            public string FromAddress { get; set; }
            public string ToRecipients { get; set; }

            public string Subject { get; set; }
            public string Body { get; set; }
            public bool IsHtml { get; set; }

            public List<System.Net.Mail.Attachment> Attachments { get; set; }
        }


        public static void SendEmail(GmailMessage email, GmailService service)
        {
            var mailMessage = new System.Net.Mail.MailMessage();
            mailMessage.From = new System.Net.Mail.MailAddress(email.FromAddress);
            mailMessage.To.Add(email.ToRecipients);
            mailMessage.ReplyToList.Add(email.FromAddress);
            mailMessage.Subject = email.Subject;
            mailMessage.Body = email.Body;
            mailMessage.IsBodyHtml = email.IsHtml;

            if (email.Attachments != null)
            {
                foreach (System.Net.Mail.Attachment attachment in email.Attachments)
                {
                    mailMessage.Attachments.Add(attachment);
                }
            }

            var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage);

            var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
            {
                Raw = Encode(mimeMessage)
            };

            Google.Apis.Gmail.v1.UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, "me");

            request.Execute();
        }

        public static string Encode(MimeMessage mimeMessage)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                mimeMessage.WriteTo(ms);
                return Convert.ToBase64String(ms.GetBuffer())
                    .TrimEnd('=')
                    .Replace('+', '-')
                    .Replace('/', '_');
            }
        }



收到的信件:



結論:
使用 Gmail API 最大的原因是要增加安全性,和舊的 smtp 不同的地方是,使用 gmail api 之後,客戶不需要提供 gmail 的帳號和密碼就可以讓系統使用 gmail 發送信件,不過由於 refresh_token 的效期問題,可能會造成無法發送通知信而沒有任何人發現的情況,整個實用性會變的很低。

另一個還沒有測試的部份是應用程的啟用。這個審核不知道會不很麻煩,不過可以而知的時,整個流程會花更多的時間。

取代的做法: 可能要改用 Amazon 的 SES 來寄信,而且為了避免每個小網站都要跑 SES 的建立流程,準備來寫一個 API 給各網站使用,可以發送簡單的通知信。

以上的程式碼可以在這裡下載: https://github.com/bikehsu/GmailTest
More...
Bike, 2022/4/10 下午 09:31:15
|< 12345 >|
頁數 1 / 5 下一頁
~ Uwinfo ~