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
標籤
  • web
  • scaffo
  • ORM
  • .
  • aspnet
  • html
  • server
  • ad
  • a
  • CK,
  • viewstate
  • sp_
  • 1
  • git
  • fb
  • 5151
  • 防火牆
  • 26
  • 992
  • reserve AP
  • 必學
  • 12
  • 28
  • CS
  • 0
  • if
  • Config
  • 筆記
  • 134 ORDER
  • 172
  • ef
  • 9818
  • 字串
  • c
  • dotnet
  • en21211211
  • -6716
  • User
  • -3089
  • code
  • mod ORDER
  • json
  • web.config
  • ie
  • http 錯èª
  • 102
  • -7160
  • FORT
  • jquery
  • EN
頁數 1 / 10 下一頁
搜尋 end 結果:
AWS SES 建立 SNS 通知
在 powershell 執行以下的指令


# List of SES identities
$identities = @(
    "wztech.com.tw",
    "s3.com.tw",
    "jdcard.com.tw",
    "mskcable.com",
    "uwinfo.com.tw",
    "bike.idv.tw",
    "richwave.com.tw",
    "ctcn.com.tw",
    "jcard.com.tw",
    "bike@bike.idv.tw",
    "ee@ier.org.tw"
)

foreach ($identity in $identities) {
    # Convert identity to a valid topic name by replacing '@' and '.' with '_'
    $safeIdentity = $identity -replace "@", "_" -replace "\.", "_"
    $topicName = "SES_NOTIFY_$safeIdentity"
    $endpoint = "https://working.uwinfo.com.tw/aws/api/sns/receive?topic=$topicName"

    # Validate topic name format
    if ($topicName -notmatch '^[a-zA-Z0-9_\-\$]+$') {
        Write-Host "❌ Invalid topic name: $topicName"
        continue
    }

    # 1. Create SNS topic
    $topicArn = aws sns create-topic `
        --name $topicName `
        --query 'TopicArn' `
        --output text

    Write-Host "✔ Created topic: $topicArn"

    # 2. Subscribe webhook
    aws sns subscribe `
        --topic-arn $topicArn `
        --protocol https `
        --notification-endpoint $endpoint

    Write-Host "✔ Subscribed webhook: $endpoint"

    # 3. Link SES notifications
    foreach ($type in @("Delivery", "Bounce", "Complaint")) {
        aws ses set-identity-notification-topic `
            --identity $identity `
            --notification-type $type `
            --sns-topic $topicArn
        Write-Host "✔ $type linked to $topicName"
    }

    Write-Host "✅ Setup complete for $identity\n"
}

Write-Host "🎉 All identities processed."



收到的 log 會放在這裡: E:\WebBackup\195\ASP.NET Project\working\Data\Log\sns

 
 
More...
Bike, 2025/4/16 上午 10:40:39
AWS SES 建立 SNS 通知
在 powershell 執行以下的指令

# List of SES identities
$identities = @(
    "wztech.com.tw",
    "s3.com.tw",
    "jdcard.com.tw",
    "mskcable.com",
    "uwinfo.com.tw",
    "bike.idv.tw",
    "richwave.com.tw",
    "ctcn.com.tw",
    "jcard.com.tw",
    "bike@bike.idv.tw",
    "ee@ier.org.tw"
)

foreach ($identity in $identities) {
    # Convert identity to a valid topic name by replacing '@' and '.' with '_'
    $safeIdentity = $identity -replace "@", "_" -replace "\.", "_"
    $topicName = "SES_NOTIFY_$safeIdentity"
    $endpoint = "https://working.uwinfo.com.tw/aws/api/sns/receive?topic=$topicName"

    # Validate topic name format
    if ($topicName -notmatch '^[a-zA-Z0-9_\-\$]+$') {
        Write-Host "❌ Invalid topic name: $topicName"
        continue
    }

    # 1. Create SNS topic
    $topicArn = aws sns create-topic `
        --name $topicName `
        --query 'TopicArn' `
        --output text

    Write-Host "✔ Created topic: $topicArn"

    # 2. Subscribe webhook
    aws sns subscribe `
        --topic-arn $topicArn `
        --protocol https `
        --notification-endpoint $endpoint

    Write-Host "✔ Subscribed webhook: $endpoint"

    # 3. Link SES notifications
    foreach ($type in @("Delivery", "Bounce", "Complaint")) {
        aws ses set-identity-notification-topic `
            --identity $identity `
            --notification-type $type `
            --sns-topic $topicArn
        Write-Host "✔ $type linked to $topicName"
    }

    Write-Host "✅ Setup complete for $identity\n"
}

Write-Host "🎉 All identities processed."

--

收到的 log 會放在這裡: E:\WebBackup\195\ASP.NET Project\working\Data\Log\sns

 
 
More...
Bike, 2025/4/16 上午 10:40:31
Line 登入,出現 "由於無法取得官方帳號的資訊,因此無法新增好友。" 錯誤訊息。
Line 登入時,若是指定了 bot_prompt=aggressive ,但沒有在 Login Channel 指定相對應的 Official Account ,就會看到 "由於無法取得官方帳號的資訊,因此無法新增好友。" 的錯誤訊息,如下圖:



此時要去 Line Login Channel 的 Add friend option 中,指定 Linked LINE Official Account,如下圖:

可參考: https://developers.line.biz/en/docs/line-login/link-a-bot/#link-a-line-official-account




 
More...
Bike, 2025/2/25 上午 08:09:03
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
查詢所有執行中的 SQL (mssql) keyword: 長時間, 總時間
用以下指令可以對 Ms-SQL Server 查出所有正在執行的 SQL 指令,並且依 執行總時間 反向排序

SELECT      r.scheduler_id as 排程器識別碼,
            status         as 要求的狀態,
            r.session_id   as SPID,
            r.blocking_session_id as BlkBy,
            substring(
                ltrim(q.text),
                r.statement_start_offset/2+1,
                (CASE
                 WHEN r.statement_end_offset = -1
                 THEN LEN(CONVERT(nvarchar(MAX), q.text)) * 2
                 ELSE r.statement_end_offset
                 END - r.statement_start_offset)/2)
                 AS [正在執行的 T-SQL 命令],
            r.cpu_time      as [CPU Time(ms)],
            r.start_time    as [開始時間],
            r.total_elapsed_time as [執行總時間],
            r.reads              as [讀取數],
            r.writes             as [寫入數],
            r.logical_reads      as [邏輯讀取數],
            -- q.text, /* 完整的 T-SQL 指令碼 */
            d.name               as [資料庫名稱]
FROM        sys.dm_exec_requests r 
            CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS q
            LEFT JOIN sys.databases d ON (r.database_id=d.database_id)
WHERE       r.session_id <> @@SPID
ORDER BY    r.total_elapsed_time desc
More...
Bike, 2024/12/2 下午 04:44:39
使用 Dependency Injection 的優缺點
優點:
1. 易於單元測試 
2. ??

缺點:
1. 所有的 function 必需先建立 Interface, 暫麻煩.
2. debug 時必需先 trace 到 interface 再 trace 到實際 implement 的 code.
More...
Bike, 2024/2/8 下午 04:38:17
Restful 的 API 範例
Restful 的 API 範例,比較特別的是取得單一筆資料時,不是用一般常見的 {id} 而是用 get?id=xxx 的方式,以避免 XXS 的功擊。(不要把原網頁中的參數拼入 API 網址,要改用 Query String 的方式傳給 API)

using Ds;
using Ds.Gv;
using iText.Kernel.Geom;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Util;
using Su;
using System.Linq.Expressions;

namespace CallCampaign.Api
{
    /// <summary>
    /// 行銷活動
    /// </summary>
    [Route("api/call-campaign")]
    [ApiController]
    [SetAuthorizationFilter(Sh.AuthCode.不設限)]
    public class ReserveCampaignController : Controller
    {
        /// <summary>
        /// 取得行銷活動列表
        /// </summary>
        /// <param name="reserveCampaignName"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderByName"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("")]
        public async Task<object> ListAsync([FromQuery] string reserveCampaignName = "", [FromQuery] int? currentPage = 1, [FromQuery] int? pageSize = 20, [FromQuery] string orderByName = "OrderNo", [FromQuery] string sort = "asc")
        {
            if (pageSize > 500)
            {
                pageSize = 500;
            }

            if (!(sort == "asc" || sort == "desc"))
            {
                throw new CustomException(System.Net.HttpStatusCode.BadRequest, "sort只能是asc或desc");
            }

            var temp = new V_ReserveCampaign().GetType().GetProperty(orderByName);
            if (temp == null)
            {
                throw new CustomException(System.Net.HttpStatusCode.BadRequest, "不存在欄位");
            }

            Expression<Func<V_ReserveCampaign, bool>> q = p => p.Is_Deleted == "N"
                    && (string.IsNullOrEmpty(reserveCampaignName) || (p.ReserveCampaignName != null && p.ReserveCampaignName.Contains(reserveCampaignName)))
                    ;

            if (orderByName.ToLower().Trim() != "id")
            {
                orderByName += " " + sort + ", id desc";
            }
            else
            {
                orderByName += " " + sort;
            }

            var ct = NewContext.GvContext;
            var list = await ct.GetPageListAsync(q, columns: "Id, ReserveCampaignName, OrderNo, StartAt, EndAt, ModifierName, ModifyDate, CreatorName, CreateDate", page: currentPage ?? 1, pageSize: pageSize ?? 20, orderByName);
            //var list = await ct.GetPageListAsync(q, page: currentPage ?? 1, pageSize: pageSize ?? 20, orderByName + " " + sort);
            return list;
        }

        /// <summary>
        /// 取得行銷活動
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("get")]
        public async Task<dynamic> GetAsync([FromQuery] int Id)
        {
            var res = await Ds.NewContext.GvContext.ReserveCampaigns.Where(r => r.Id == Id)
                .FirstOrDefaultAsync();

            if (res == null)
            {
                throw new CustomException(System.Net.HttpStatusCode.BadRequest, "查無資料 " + Id.ToString());
            }
            return res;
        }
                
        /// <summary>
        /// 建立行銷活動
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpPost("")]
        public async Task<object> CreateAsync(Dtos.CreateReserveCampaign dto)
        {
            var ct = NewContext.GvContext;
            var res = await Models.ReserveCampaignHelper.CreateReserveCampaignAsync(ct, dto);
            return res;
        }

        /// <summary>
        /// 編輯行銷活動
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpPatch("")]
        public async Task<object> UpdateAsync(Dtos.UpdateReserveCampaign dto)
        {
            var ct = NewContext.GvContext;
            var res = await Models.ReserveCampaignHelper.UpdateReserveCampaignAsync(ct, dto);
            return res;
        }

        /// <summary>
        /// 刪除行銷活動
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpDelete("")]
        public async Task<object> DeleteAsync([FromQuery] int id)
        {
            var res = await Ds.NewContext.GvContext.MarkDeleteAsync<Ds.Gv.ReserveCampaign>(id, Sh.ModifyInfo);
            return res;
        }
    }
}



再增加一個同步範例(只例出 action)


        /// <summary>
        /// 取得列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderByName"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpGet("")]
        public object List([FromQuery] string name = "", [FromQuery] int? currentPage = 1, [FromQuery] int? pageSize = 20, [FromQuery] string orderByName = "OrderNo", [FromQuery] string sort = "asc")
        {
            return "";
        }

        /// <summary>
        /// 取得明細資料
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet("get")]
        public object Get([FromQuery] int id)
        {
            return "";
        }

        /// <summary>
        /// 建立
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpPost("")]
        public object Create(Dtos.PhysicalCheckUpType dto)
        {
            return "";
        }

        /// <summary>
        /// 編輯
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpPatch("")]
        public object Update(Dtos.PhysicalCheckUpType dto)
        {
            return "";
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpDelete("")]
        public object Delete([FromQuery] int id)
        {
            return 1;
        }
More...
Bike, 2023/12/13 上午 08:54:28
前端 頁面讀入 API取值工具

PromiseAll: async function (array) {
    let taskList = [];
    let propList = [];
    for (let obj of array) {
        for (let prop in obj) {
            taskList.push(obj[prop]);
            propList.push(prop);
        }
    }
    let resp = await Promise.all(taskList);
    let result = {};
    let counter = 0;
    for (let prop of propList) {
        result[prop] = resp[counter];
        counter += 1;
    }
    return result;
}

PromiseAll 是將API一次發送並接收回傳值的工具
使用方法範例:

const taskList = [{
    adPosition : BannerPositionDataService.GetList(),
    big : BannerDataService.GetList(100),
    smallTop : BannerDataService.GetOne(200),
    smallBottom : BannerDataService.GetOne(300),
    section2 : BannerDataService.GetList(400),
    section3 : BannerDataService.GetList(500),
    section4 : BannerDataService.GetList(600),
    recommends : ProductDataService.GetRndList()
}];

let resps = await UJ.PromiseAll(taskList);

要特別記得TaskList中的Method不需要做await,不然就沒有意義了


DeepBinding: function (vueData, data) {

    if (Array.isArray(data)) {
        if (!Array.isArray(vueData)) {
            vueData = [];
        } else {
            vueData.splice(0);
        }
        for (let prop in data) {
            vueData.push(data[prop]);
        }
    }
    else if (typeof (data) === 'object') {
        if (Object.keys(data).length === 0) {
            return;
        }
        for (let prop in data) {
            if (vueData[prop] === undefined || data[prop] === null ||
                (!Array.isArray(vueData[prop] && vueData !== null && typeof (data) !== 'object'))) {
                vueData[prop] = data[prop];
            } else {
                this.DeepBinding(vueData[prop], data[prop]);
            }
        }
    } else {
        vueData = data;
    }
}

在資料回傳後要Binding到Vue Data上面或是任意Object的Property上可以使用這個,
不使用DeepBinding是因為瀏覽器版本限制,這個方式不受瀏覽器版本限制,但是只有提供一階,需要多階請自行改寫.
使用方法範例:

UJ.DeepBinding(this, resp);

這邊的this代表的是Vue的Data
 
More...
梨子, 2023/11/24 上午 11:05:08
平行序處理多筆資料
由於匯入91訂單,如果是一筆一筆抓,會耗費比較久的時間
下列寫法是,開兩條 thread 平行處理,可以節省約一半時間

public ConcurrentBag<V2SalesOrderGetDataList> ConcurencyGetApp91OrderDetails(List<string> TMCodes, int shopId, ref ConcurrentBag<string> orderErrMsgs)
        {
            #region 平行查詢
            ConcurrentBag<V2SalesOrderGetDataList> result = new ConcurrentBag<V2SalesOrderGetDataList>();
            ConcurrentBag<string> errs = new ConcurrentBag<string>();
            ConcurrentQueue<string> TMCodeQueues = new ConcurrentQueue<string>();
            TMCodes.ForEach(x => TMCodeQueues.Enqueue(x));

            Action searchOrderDetail = () =>
            {
                if (!TMCodeQueues.IsEmpty)
                {
                    string TMCode = string.Empty;

                    while (TMCodeQueues.TryDequeue(out TMCode))
                    {
                        V2SalesOrderGetReqModel reqModel = new V2SalesOrderGetReqModel()
                        {
                            ShopId = shopId,
                            TGCode = null,
                            TMCode = TMCode,
                            TSCode = null,
                        };

                        try
                        {
                            V2SalesOrderGet91API req = new V2SalesOrderGet91API();
                            var resp = req.Execute(reqModel, shopId);

                            if (resp.Status == "Success")
                            {
                                foreach (var l in resp.Data.List)
                                {
                                    result.Add(l);
                                }
                            }
                            else
                            {
                                //主單編號 , 錯誤原因
                                errs.Add(TMCode + " , " + resp.ErrorMessage);
                            }
                        }
                        catch (Exception ex)
                        {
                            errs.Add(TMCode + " , " + ex.Message);
                        }
                    }
                }
            };

            //指派Thread
            Parallel.Invoke(searchOrderDetail, searchOrderDetail);
            #endregion

            //查詢失敗
            orderErrMsgs = errs;

            return result;
        }
More...
darren, 2023/6/19 下午 04:47:30
關於 Entity Framework Extensions 的 UpdateFromQueryAsync
這個指令還是會把所有的資料 Select 出來,再更新

原指令:

UPDATE Job Set En_Status = 200 Where En_Status = 100 and LastTouchAt < '2023-05-06 12:34:56'
其中  '2023-05-06 12:34:56' 是 DateTime.Now.AddMinutes(-2) 的結果(Web Server 端的時間扣 2 分鐘)

但,若是改使用 UpdateFromQueryAsync 如下:
var c = await Ds.NewContext.GvContext.Jobs.Where(j => j.En_Status == Cst.Job.Status.Running && j.LastTouchAt < DateTime.Now.AddMinutes(-2))
                .UpdateFromQueryAsync(j => new Ds.Gv.Job { En_Status = Cst.Job.Status.ReStarting });

產生的 SQL 如下:
UPDATE A 
SET A.[En_Status] = @zzz_BatchUpdate_0
FROM [Job] AS A
INNER JOIN ( SELECT [j].[Id], [j].[CancelledAt], [j].[CancelledBy], [j].[En_Status], [j].[EndAt], [j].[Exception], [j].[Filename], [j].[InformationJson], [j].[InitAt], [j].[Is_CheckOnly], [j].[LastTouchAt], [j].[LastTouchMessage], [j].[LoopStartAt], [j].[Name], [j].[ScheduleId], [j].[TotalTouch], [j].[TouchCount]
FROM [Job] AS [j]
WHERE [j].[En_Status] = 100 AND [j].[LastTouchAt] < DATEADD(minute, CAST(-2.0E0 AS int), GETDATE())
           ) AS B ON A.[Id] = B.[Id]

有兩個要注意的地方:
1. 它會先 Select 全欄位,再做更新

2. 它的時間是 DB Server 的現在時間。不是 Web Server 端的時間。


順便記錄一下。若是要執行 Update xx Ser cc = cc + 1 Where ...

EF 可寫為:
var c = await Ds.NewContext.GvContext.Jobs.Where(j => j.En_Status == Cst.Job.Status.Running && j.LastTouchAt < DateTime.Now.AddMinutes(-2))
                .UpdateFromQueryAsync(j => new Ds.Gv.Job { TotalTouch = j.TotalTouch + 1 });

轉換的 SQL 為:
UPDATE A 
SET A.[TotalTouch] = B.[TotalTouch] + 1
FROM [Job] AS A
INNER JOIN ( SELECT [j].[Id], [j].[CancelledAt], [j].[CancelledBy], [j].[En_Status], [j].[EndAt], [j].[Exception], [j].[Filename], [j].[InformationJson], [j].[InitAt], [j].[Is_CheckOnly], [j].[LastTouchAt], [j].[LastTouchMessage], [j].[LoopStartAt], [j].[Name], [j].[ScheduleId], [j].[TotalTouch], [j].[TouchCount]
FROM [Job] AS [j]
WHERE [j].[En_Status] = 100 AND [j].[LastTouchAt] < DATEADD(minute, CAST(-2.0E0 AS int), GETDATE())
           ) AS B ON A.[Id] = B.[Id]
More...
Bike, 2023/4/29 下午 08:44:31
|< 12345678910 >|
頁數 1 / 10 下一頁
~ Uwinfo ~