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
標籤
  • PDQ
  • generater
  • 403.18
  • zindex
  • Ubuntu
  • requestenc
  • request.fo
  • 問題
  • 220
  • request.qu
  • window.ope
  • mrtg
  • CORS
  • .prop
  • U8l4WeN3
  • tim
  • deadlock
  • AD
  • -7160
  • CKED
  • localhost
  • 50
  • isnull
  • .animate
  • -3036
  • DBCC
  • -5229
  • OIDs
  • 衝碼
  • LinePay
  • abort
  • 36
  • sVN
  • List
  • -8908
  • window
  • [t]
  • uw
  • iuser
  • -1068
  • 728
  • Chrome
  • -4563
  • -3643
  • 88
  • -2912
  • permitt
  • ti
  • proxy
  • service un
頁數 1 / 13 下一頁
搜尋 sa 結果:
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
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
Line Official Account 和 Message API 的綁定
每次都找不到,在這裡記錄一下。

進入 Official Account Manager 之後,點右上方的 Setting,在左側選單有 Message API

 
 
More...
Bike, 2024/6/17 上午 10:22:44
win server 2022 架設 IIS6 的 SMTP 服務
如果網站需要有一個簡易的SMTP服務,最簡單的方式就是安裝SMTP服務


然後安裝後,記得要去 [服務] 把 [簡易郵件傳送通訊定(SMTP)]  啟動,並且記得要改為"自動啟動" (不然重開機不會啟動)
 
管理SMTP設定,要到這個介面的 IIS6 管理員


But, 如果你是用 win server 2022,就會出現掛掉無法編輯使用的狀況,不知為何win server 2022 會有這個奇怪的bug
請遵照下面步驟修改,就可以正常運作
1. Stop SMTPSVC service [Display Name: Simple Mail Transfer Protocol (SMTP)]
2. Stop IISADMIN service [Display name: IIS Admin Service]
3. Edit "C:\Windows\System32\inetsrv\MetaBase.xml"
4. Find: <IIsSmtpServer Location ="/LM/SmtpSvc/1"
5. Add (Settings are alphabetical): RelayIpList=""
6. Save file
7. Start IISAdmin Service
8. Start SMTPSVC service


開啟IIS6的管理介面後,還要設定一下 允許轉送清單,對於來源IP作管控
 
這樣大致上就可以正常運作
More...
darren, 2024/4/10 下午 03:18:35
前端 頁面讀入 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
AddPath優化
改寫成可輸入多參數,效能也比較好的版本。
以下為測試碼,請自行依照專案需求做修改。

var root = "C://wdqd/qwewq";
var addPath = @"//\\/fwef/qwf";
var addPath2 = @"5fwfef/qwf";
var addPath3 = @"//fwef/qwf";
var addPath4 = @"\\\fwef/qwf";
var addPath5 = @"\\\\\/fwef/qwf";


var result = root.AddPath(addPath, addPath2, addPath3, addPath4, addPath5);

Console.WriteLine(result);

public static class Helper
{
    public static string AddPath(this string value, params string[] addPaths)
    {
        if (string.IsNullOrEmpty(value))
        {
            throw new Exception("起始目錄不可以為空字串");
        }

        if (value.Contains("..") || addPaths.Any(x => x.Contains("..")))
        {
            throw new Exception($"value: {value}, addPaths: {addPaths.Where(x => x.Contains("..")).ToOneString()} 檔名與路徑不可包含 ..");
        }

        var paths = addPaths.Select(x => x.Substring(x.FindLastContinuousCharPosition('/', '\\') + 1).SafeFilename()).ToList();

        if (paths.Any(x => System.IO.Path.IsPathRooted(x)))
        {
            throw new Exception("不可併入完整路徑 ..");
        }

        paths.Insert(0, value.SafeFilename());

        return System.IO.Path.Combine(paths.ToArray());
    }

    public static string ToOneString<T>(this IEnumerable<T> list, string separator = ",")
    {
        var strList = list.Select(x => x.ToString());
        return string.Join(separator, strList);
    }

    public static int FindLastContinuousCharPosition(this string input, params char[] targets)
    {
        int lastPosition = -1;

        for (int i = 0; i < input.Length; i++)
        {
            if (targets.Contains(input[i]))
            {
                lastPosition = i;
            }
            else
            {
                break;
            }
        }

        return lastPosition;
    }

    public static string SafeFilename(this string value)
    {
        return GetValidFilename(value);
    }

    public static string GetValidFilename(string value)
    {
        string ValidFilenameCharacters = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\-_$.@:/# ";
        if (value.Contains(".."))
        {
            throw new Exception("路徑中不可包含 .. ");
        }

        string newUrl = "";
        for (int i = 0; i < value.Length; i++)
        {
            var c = value.Substring(i, 1);
            int k = ValidFilenameCharacters.IndexOf(c);
            if (k < 0)
            {
                throw new Exception($"檔名 '{value}' 中有非法的字元 '" + c + "'。");
            }
            newUrl += ValidFilenameCharacters.Substring(k, 1);
        }

        return newUrl;
    }
}
More...
梨子, 2023/8/28 上午 09:43:49
平行序處理多筆資料
由於匯入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
用遞迴查詢所有子部門的 Sql
WITH DepartmentTree AS (
    SELECT       
        Id, 
        Code,
        Name,
        UpDepartmentId,
        1 as Level
    FROM       
        SaintEir_Department
    WHERE Id  = 1
    UNION ALL
    SELECT 
        e.Id, 
        e.Code,
        e.Name,
        e.UpDepartmentId,
        o.Level + 1 as Level
    FROM 
        SaintEir_Department e
        INNER JOIN DepartmentTree o 
            ON o.Id = e.UpDepartmentId
)
SELECT * FROM DepartmentTree;
More...
Bike, 2023/5/23 上午 11:04:38
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
|< 12345678910… >|
頁數 1 / 13 下一頁
~ Uwinfo ~