2024年4月27日 星期六

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify

2024-04-27

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

因 RestSharp 於 2009 年首次推出,成為 .NET 開發者中非常受歡迎的一個選擇。在 RestSharp v107 開始,語法大改;而 .NET Framework 4.5 (2012 年推出) 開始提供 HttpClient,考慮改用這個。

********************************************************************************

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="IRESTfulServerUrl" value="https://網址/" />
    <add key="IRESTfulAccount" value="帳號" />
    <add key="IRESTfulPassword" value="密碼" />
  </appSettings>
</configuration>



********************************************************************************

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;	// NuGet 安裝,HttpClient 要使用
using System.Threading.Tasks;

namespace WebApplication1
{

    public class VerifyResult
    {
        public string message { get; set; }
        public string describe { get; set; }

        // RestSharp v106 要這樣才能運作
        //public List<VerifyData> data { get; set; }

        // RestSharp v107 開始或 HttpClient ,要這樣才能運作
        public VerifyData data { get; set; }
    }

    public class VerifyData
    {
        public string product_class { get; set; }
        public string product_account { get; set; }
        public string product_name { get; set; }
        public string contact_account { get; set; }
        public string contact_name { get; set; }
        public string contact_cellphone { get; set; }
        public string contact_mail { get; set; }
        public string contact_dept { get; set; }
        public string contact_tel { get; set; }
        public string contact_extend { get; set; }
        public string contact_title { get; set; }
        public string status { get; set; }
        public List<string> contact_category { get; set; }
    }
    public partial class Default : System.Web.UI.Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {
            string account = "略";
            string password = "略";


            VerifyResult content = new VerifyResult();
            content = await Verify_by_HttpClient("1", account, password);
        }

        #region === public async static VerifyResult Verify_by_HttpClient(string account_type, string account, string password) ===
        public async static Task<VerifyResult> Verify_by_HttpClient(string account_type, string account, string password)
        {
            string iRESTfulUrl = ConfigurationManager.AppSettings["IRESTfulUrl"];
            string iRESTfulSysId = ConfigurationManager.AppSettings["IRESTfulSysId"];
            string iRESTfulSysPass = ConfigurationManager.AppSettings["IRESTfulSysPass"];
			string acc = TextBox_Acc.Text.Trim();
			string pass = TextBox_Pass.Text.Trim();
			
            var httpClient = new HttpClient();
            try
            {
                var requestBody = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("sysid", iRESTfulSysId),
                    new KeyValuePair<string, string>("syspass", iRESTfulSysPass),
                    new KeyValuePair<string, string>("acc", acc),
                    new KeyValuePair<string, string>("pass", pass),
                });

                var response = await httpClient.PostAsync(iRESTfulUrl + "restful/verify", requestBody);

                bool isSuccessStatusCode = response.IsSuccessStatusCode;
                HttpResponseMessage ensureSuccessStatusCode = new HttpResponseMessage();
                if (isSuccessStatusCode == false)
                {
                    ensureSuccessStatusCode = response.EnsureSuccessStatusCode();
                }

                var responseStream2 = response.Content.ReadAsStreamAsync().Result;
                using (var responseStream = await response.Content.ReadAsStreamAsync())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream))
                    using (Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))
                    {
                        //不可以同時 ReadToEnd 和 Deserialize,只能擇一使用
                        //var json = streamReader.ReadToEnd(); // 讀取 JSON 資料到字串中
                        var serializer = new Newtonsoft.Json.JsonSerializer();
                        //return serializer.Deserialize<VerifyResult>(jsonTextReader);
                        VerifyResult v = serializer.Deserialize<VerifyResult>(jsonTextReader);
                        return v;
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string exMsg = "";
                if (ex != null)
                    exMsg = ex.Message.ToString();
                throw;
            }
        }
        #endregion
    }
}


Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

...(略)

實際測試,在 Visual Studio 中 Debug,v確實有拿到回傳資料。

(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(二)verify
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615_27.html

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615.html

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)
https://shaurong.blogspot.com/2024/04/aspnetsystemnet-http.html

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html



[研究]BT (.torremt、磁力) 下載工具比較

[研究]BT (.torremt、磁力) 下載工具比較

2024-04-27

比較 μTorrent (uTorrent), qBittorrent, Deluge, Transmission, BitComet 特點 ? 優點 ? 缺點 ? 佔有率 ? 用表格比較

ChatGPT

工具名稱特點優點缺點佔有率
μTorrent (uTorrent)簡潔的介面,快速的下載速度。- 輕量級,佔用系統資源少。
- 提供豐富的功能,如排程、RSS 訂閱。
- 曾因廣告和安全問題受到爭議。高(約佔 50%)
qBittorrent開源、跨平台,提供豐富的功能。- 提供排程、RSS 訂閱、IP 過濾器等功能。
- 界面簡潔易用。
- 某些高級功能可能不如其他客戶端完善。中(約佔 20%)
Deluge開源、模組化,支援插件系統。- 輕量級,跨平台,支援多種插件擴展功能。
- 界面簡單直觀。
- 可能缺乏某些高級功能。中(約佔 15%)
Transmission簡潔、輕量級,適合資源有限的系統。- 資源消耗低,適合用於舊式電腦或資源有限的系統。
- 界面簡單清爽。
- 功能相對基本,缺乏某些高級功能。中(約佔 10%)
BitComet具有內置的 P2P 文件分享功能,支援多線程下載。- 提供多線程下載、快速種子搜尋等功能。
- 內置 P2P 文件分享功能。
- 曾因廣告、隱私問題等受到批評。低(約佔 5%)

********************************************************************************

Copilot

特點μTorrent (uTorrent)qBittorrentDelugeTransmissionBitComet
輕量級
跨平台支援
加密功能
WebUI
插件系統
長效種子
磁盤緩存
邊下載邊播放
佔有率未提供具體數值未提供具體數值未提供具體數值未提供具體數值未提供具體數值

(完)

相關

[研究]ASP.NET,Response.Redirect沒執行,錯誤訊息 "執行緒已經中止。"

[研究]ASP.NET,Response.Redirect沒執行,錯誤訊息 "執行緒已經中止。"

2024-04-27

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************


執行緒已經中止。

ERRORSHELPABOUT

System.Threading.ThreadAbortException

執行緒已經中止。


System.Threading.ThreadAbortException: 執行緒已經中止。

   於 System.Web.HttpContext.InvokeCancellableCallback(WaitCallback callback, Object state)

   於 System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action)

********************************************************************************

GPT-4 Copilot

您遇到的問題是 ASP.NET 中的一個常見情況。當使用 Response.Redirect 或 Server.Transfer 時,內部會調用 Response.End,而這會中止正在執行的線程。為了解決這個問題,您可以採取以下兩種方法之一:

1.使用 HttpContext.Current.ApplicationInstance.CompleteRequest():

在使用 Server.Transfer 時,您可以使用 Server.Execute 作為替代方法。這樣可以避免 ThreadAbortException。

例如:


Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();   

這樣,您可以告訴 IIS 管道在返回控制後直接進入 EndRequest 階段。

2.使用 Response.Redirect 的多載方法:

使用多載方法 Response.Redirect(string url, bool endResponse),將 endResponse 參數設置為 false。

這樣可以隱藏對 Response.End 的內部調用。

例如:


Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();   

這樣不會引發 ThreadAbortException,但您需要負責在事件處理程序中提前返回控制,以避免其他代碼的執行。

********************************************************************************

結果 Elmah 雖然沒有報告問題,但是 Response.Redirect 無效,不太清楚外包商如何搞的,這個方案某些地方用 Response.Redirect 就是無效,外包商自己到處都是用 Response.Write,而非用 Response.Redirect。

後來用 Response.Write 代替 Response.Redirect 重導網址


Response.Write("<script>window.location='WebForm1.aspx';</script>");  

成功。


註:下面方法或可考慮(尚未實際測試)

Response.Write("<script>window.open('WebForm1.aspx', '_blank');</script>");

Response.Write("<script>window.location.href = 'WebForm1.aspx';</script>");

(完)

相關

2024年4月24日 星期三

[研究][C#]整數轉 Excel 橫列標題 26進位轉換

[研究][C#]整數轉 Excel 橫列標題 26進位轉換

2024-04-24

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

Excel的橫列標題是 A,B,C, ... Z, AA, AB, .... 依此類推,

10進位 => 26進位 ( 0->A, 1->B, ....)

using System;

class Program
{
    static string ConvertToBase26(int number)
    {
        const string base26Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string result = string.Empty;

        do
        {
            result = base26Chars[number % 26] + result;
            number /= 26;
        } while (number-- > 0);

        return result;
    }

    static void Main()
    {
        int number = 12345;
        string base26 = ConvertToBase26(number);
        Console.WriteLine($"Number {number} in base 26 is {base26}");
    }
}



26進位 => 10進位


using System;

class Program
{
    static int ConvertFromBase26(string base26)
    {
        const string base26Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int result = 0;

        for (int i = 0; i < base26.Length; i++)
        {
            result = result * 26 + base26Chars.IndexOf(base26[i]);
        }

        return result;
    }

    static void Main()
    {
        string base26 = "BCDE";
        int number = ConvertFromBase26(base26);
        Console.WriteLine($"Base 26 number {base26} is {number} in base 10");
    }
}




(完)

相關

2024年4月23日 星期二

[研究]ASP.NET,用 NuGet 安裝 ckeditor-full 4.22.1 會安裝那些套件

[研究]ASP.NET,用 NuGet 安裝 ckeditor-full 4.22.1 會安裝那些套件

2024-04-23

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

WebApplication1

正在安裝:

ckeditor-full.4.22.1

********************************************************************************

其實目的不是安裝,是移除後,瞭解一下,還有那些被 ckeditor順便安裝的相依套件,是否可以移除。

(完)

相關

2024年4月22日 星期一

[研究]比較 Newtonsoft.Json.JsonConvert、System.Text.Json、DataContractJsonSerializer

[研究]比較 Newtonsoft.Json.JsonConvert、System.Text.Json、DataContractJsonSerializer

2024-04-22

比較支援環境、特點、優點、缺點

Newtonsoft.Json.JsonConvert

System.Text.Json

DataContractJsonSerializer

ChatGPT

這三個是在C#中用於處理JSON序列化和反序列化的常見工具。以下是它們的比較:

Newtonsoft.Json.JsonConvert

支援環境: 適用於.NET Framework和.NET Core。

特點:

  • 提供了廣泛的自定義選項,如自定義序列化和反序列化行為、忽略屬性、自訂轉換器等。
  • 較高的性能和廣泛的功能。

優點:

  • 社區支持良好,文檔豐富,用戶數量眾多。
  • 擁有豐富的功能和選項,適用於各種場景。

缺點:

  • 相對於.NET Core內置的System.Text.Json,需要額外的依賴。
  • 在一些情況下可能會導致較大的組件大小。

System.Text.Json

支援環境: .NET Core 3.0及以上版本和.NET 5.0及以上版本。

特點:

  • 是.NET Core和.NET 5中的內置JSON處理庫,無需額外安裝。
  • 提供了基本的JSON序列化和反序列化功能,並提供了一些基本的自定義選項。

優點:

  • 由Microsoft開發和維護,與.NET平台整合緊密。
  • 較小的組件大小和更快的序列化/反序列化速度,特別是對於大型數據量。

缺點:

  • 功能相對較少,對於高度定制化的需求可能不足。

DataContractJsonSerializer

支援環境: 適用於.NET Framework。

特點:

  • 通過DataContract屬性來指定需要序列化的類型成員。
  • 依賴於.NET Framework的DataContract屬性,用於定義序列化和反序列化的規則。

優點:

  • 內置於.NET Framework中,無需額外安裝。
  • 適用於一些遺留應用程序或者需要與現有DataContract相集成的場景。

缺點:

  • 功能較為基本,自定義選項有限。
  • 對於新的.NET Core或.NET 5應用程序不適用,因為它只能在.NET Framework中使用。

總體來說,根據您的具體需求和環境,您可以選擇適合的JSON處理工具。如果您在.NET Core或.NET 5應用程序中工作,並且需要快速且輕量級的JSON處理,則System.Text.Json可能是更好的選擇。如果您需要豐富的功能和廣泛的社區支持,則Newtonsoft.Json可能更合適。而如果您在使用遺留的.NET Framework應用程序,則可以考慮使用DataContractJsonSerializer。

********************************************************************************

特性Newtonsoft.JsonSystem.Text.JsonDataContractJsonSerializer
支援環境支援 .NET Framework 和 .NET Core支援 .NET Core 和 .NET 5+支援 .NET Framework 和 .NET Core
特點- 彈性高,可序列化幾乎所有.NET類型
- 支援 LINQ to JSON
- 容錯性強
- 擴展性佳
- 內建於 .NET Core 和 .NET 5+
- 性能優異
- 輕量級
- 支援部分 JSON Schema 標準
- 內建於 .NET Framework
- 可與 WCF 集成
- 支援部分 JSON Schema 標準
優點- 彈性高,可處理各種情況
- 社區支援豐富
- 擴展性強
- 設定彈性
- 效能較好
- 內建於 .NET 平台
- 簡潔易用
- 安全性高
- 內建於 .NET 平台
- 可與 WCF 集成
- 整合性高
缺點- 性能較差
- 依賴較多外部套件
- 部分功能不如 Newtonsoft.Json
- 彈性較差
- 彈性較差
- 效能較差
- 可定制性不足


********************************************************************************
User

.NET Framework 為何內建提供 DataContractJsonSerializer 又內建提供  System.Text.Json ? 兩者差異 ?

ChatGPT

.NET Framework 內建提供了 DataContractJsonSerializer 和 .NET Core 之後的版本內建提供了 System.Text.Json 主要是因為這兩個工具在設計和使用上有一些差異,以及針對不同的需求和場景。

差異:

性能和效能:
  • DataContractJsonSerializer 在處理大量數據時效能較差,而 System.Text.Json 則在這方面表現更佳,特別是在處理大型 JSON 數據時。
彈性和功能:
  • DataContractJsonSerializer 主要是為了支援 WCF (Windows Communication Foundation) 和舊版 .NET 框架的需求而設計,它的彈性較差,且支援的功能相對較少。
  • System.Text.Json 則是在 .NET Core 和 .NET 5+ 中內建的 JSON 序列化工具,它提供了更多的彈性和功能,例如支援序列化和反序列化的擴展點、自定義序列化器等。
生態系統和支援:
  • 隨著 .NET Core 和 .NET 5+ 的發展,.NET Core 生態系統越來越強大,System.Text.Json 作為內建的 JSON 序列化工具受到了廣泛的支援和應用,並且有著活躍的社區支持。
  • 相比之下,DataContractJsonSerializer 主要是在舊版 .NET Framework 中使用,雖然在舊版框架中仍然受到支援,但是它的發展和更新相對較少。
總的來說,.NET Core 以及之後的版本提供了 System.Text.Json 主要是為了提高 JSON 序列化的性能和彈性,並且符合現代應用開發的需求,而 DataContractJsonSerializer 則主要是為了舊版 .NET Framework 和 WCF 的相容性考慮。

(完)

[研究]ASP.NET, RestSharp v106, v107, v108, v109, v110, v111,v112 程式寫法差異?

[研究]ASP.NET, RestSharp v106, v107, v108, v109, v110, v111,v112 程式寫法差異?

2024-04-22

ASP.NET,WebForm, 請說明 RestSharp  v106, v107, v108, v109, v110, v111,v112 程式寫法差異?

Copilot

v106:

  • v106 的變更相對較少,並且在程式碼簽名上並未造成破壞性。如果您使用的是這個版本,您可以繼續使用相同的程式寫法。
  • 請注意,v106 是較早的版本,因此如果您打算升級,建議您閱讀後續版本的變更。

v107:

  • v107 是一個重大的升級,其中包含了一些破壞性的變化。
  • 最重要的變化是,RestSharp 不再使用過時的 HttpWebRequest 類別,而改用廣泛使用的 HttpClient。這個改變解決了許多問題,例如因不正確的 HttpClient 實例緩存而導致的連接中斷、更新的協議支援等。
  • SimpleJson 從程式碼庫中完全移除。取而代之,RestSharp 現在使用 System.Text.Json 套件中的 JsonSerializer,這是 ASP.NET Core 的預設序列化程式。
  • 大部分介面已經被移除。現在您將使用 RestClient 類別實例,而大部分客戶端選項已經移到 RestClientOptions 中。

v108、v109、v110、v111、v112:

  • v108 到 v112 的程式碼變更在簽名上並不會造成破壞性,但 v110 與之前的版本不具有二進制兼容性。主要差異在於 DefaultParameters 集合現在在所有變更操作時都會使用鎖定。
  • v109 引入了 IRestClient 介面,但新介面的 API 比之前的版本要小得多。您將使用 RestClient 類別實例,而大部分客戶端選項已經移到 RestClientOptions 中。

總之,如果您正在使用 RestSharp,請確保遵循最新版本的建議和指南,以確保程式碼的正確性和效能。

https://restsharp.dev/v107/#restsharp-v107

https://github.com/restsharp/RestSharp/releases

https://restsharp.dev/intro.html#content-type

(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 升級 RestSharp 110.2.0 做 Restful API 呼叫

[研究]ASP.NET,WebForm,將 RestSharp 106.15 升級 RestSharp 110.2.0 做 Restful API 呼叫

[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(四)將 RestSharp 106.15 升級 RestSharp 110.2.0 

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

因 RestSharp 在 v107 開始,語法大改。而且 v107 至 110.2.0,疑似陸續有改,之前研究測試的 Code 部分不能用。

********************************************************************************

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="IRestfulServerUrl" value="https://網址/" />
    <add key="IRestfulAccount" value="帳號" />
    <add key="IRestfulPassword" value="密碼" />
  </appSettings>
</configuration>


Models\MyModel.cs

保留不公開


********************************************************************************

Default.aspx

using RestSharp;    // NuGet 安裝 RestSharp 106.15
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;    // HttpClient 使用
using System.Threading.Tasks;
using WebApplication1.Models;   // 自己寫的

namespace WebApplication1
{
    public class IRestfulClient
    {
        static readonly string IRestfuleServerURL = ConfigurationManager.AppSettings["IRestfulServerUrl"];
        static readonly string IRestfulAccount = ConfigurationManager.AppSettings["IRestfulAccount"];
        static readonly string IRestfulPassword = ConfigurationManager.AppSettings["IRestfulPassword"];

       ...(略)
/* 註解,v106 和 v107 無法共存 public static ProductListResult getProductList() { var client = new RestClient(IRestfuleServerURL + "rest/getProductList"); var request = new RestRequest(Method.POST); RestResponse<ProductListResult> response2; request.AddParameter("acc", IRestfulAccount); request.AddParameter("pass", IRestfulPassword); try { response2 = (RestSharp.RestResponse<ProductListResult>)client.Execute<ProductListResult>(request); } catch (Exception) { throw; } return response2.Data; } */ public static async Task<ProductListResult> getProductList_by_HttpClient()
{ var httpClient = new HttpClient(); try { var requestBody = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("acc", IRestfulAccount), new KeyValuePair<string, string>("pass", IRestfulPassword) }); var response = await httpClient.PostAsync(IRestfuleServerURL + "rest/getProductList", requestBody);
response.EnsureSuccessStatusCode(); using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (var streamReader = new StreamReader(responseStream)) using (var jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = new Newtonsoft.Json.JsonSerializer(); return serializer.Deserialize<ProductListResult>(jsonReader); } } } catch (HttpRequestException) { throw; } } public static async Task<ProductListResult> getProductList_by_RestSharp107() { // 以 Postman 測試時,參數是加在 Body 才行, // 但在本程式用 AddBody 收不到參數,要用 AddParamter 才行 var client = new RestClient(IRestfuleServerURL + "rest/getProductList"); //var request = new RestRequest(Method.POST); //RestResponse<ProductListResult> response; var request = new RestRequest() .AddHeader("Content-Type", "application/x-www-form-urlencoded") .AddParameter("code", IRestfulAccount) .AddParameter("sys_pass", IRestfulPassword); try { //response2 = (RestSharp.RestResponse<ProductListResult>)client.Execute<ProductListResult>(request); var response = await client.PostAsync<ProductListResult>(request); var json = Newtonsoft.Json.JsonConvert.SerializeObject(response); //ProductListResult responseUnitListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(responseVerifyResultString); //var responseVerifyResultString = await response.data.ReadAsStringAsync(); ProductListResult responseUnitListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(json); //var responseMessage = response.message; //var responseData = response.data; //var responseDataJson = Newtonsoft.Json.JsonConvert.SerializeObject(responseData); //ProductListData productListData = Newtonsoft.Json.JsonConvert.DeserializeObject <ProductListData>(responseDataJson);//Error return responseUnitListResultJson;
//if (response.IsSuccessStatusCode) //{ // var responseVerifyResultString = await response.Content.ReadAsStringAsync(); // ProductListResult responseProductListResultJson = Newtonsoft.Json.JsonConvert.DeserializeObject<ProductListResult>(responseVerifyResultString); // return responseProductListResultJson; //} //else //{ // return null; //} /* // 發送請求並取得回應 //---------------------------------------- RestResponse response0 = client.Execute(request); //Response.Write(response0.Content+ "<br /><br />"); //成功 //var json0 = JsonConvert.SerializeObject(response0); //Response.Write("Json0: " +json0+"<br /><br />"); // Fail Message //---------------------------------------- var response1 = await client.PostAsync<ProductListResult>(request); //Response.Write(response.message); var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(response); //Response.Write("Json : " + json+ "<br /><br />"); // 成功 //---------------------------------------- var response2 = await client.ExecuteAsync<ProductListResult>(request); //Response.Write("response2.Data.message : " + response2.Data.message+ "<br /><br />"); // 成功 //---------------------------------------- var response3 = await client.ExecutePostAsync<ProductListResult>(request); //Response.Write(response.message); var json3 = Newtonsoft.Json.JsonConvert.SerializeObject(response3); //Response.Write("Json3 : " + json3+ "<br /><br />"); // 成功 //---------------------------------------- var response4 = await client.PostAsync(request); //Response.Write(response.message); var json4 = Newtonsoft.Json.JsonConvert.SerializeObject(response4); //Response.Write("Json4 : " + json4+ "<br /><br />"); // 成功,但額外多一些怪資訊,因為沒有 Object 的 class //---------------------------------------- var response5 = await client.PostAsync<GetObjectResult>(request); //Response.Write(response.message); var json5 = Newtonsoft.Json.JsonConvert.SerializeObject(response5); //Response.Write("Json5 : " + json5 + "<br /><br />"); // 成功 //---------------------------------------- */ } catch (Exception) { throw; } //return response2.Data;
} ...(略) } }

Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <%--<asp:Button ID="Button1" runat="server" Text="用 RestSharp v106 呼叫 Restful API" OnClick="Button1_Click" /><br />--%>
        <asp:Button ID="Button2" runat="server" Text="用 HttpClient 呼叫 Restful API" OnClick="Button2_Click" /><br />
        <asp:Button ID="Button3" runat="server" Text="用 RestSharp 110.2.0 呼叫 Restful API" OnClick="Button3_Click" /><br />
        <asp:Label ID="Label_MSG1" runat="server"></asp:Label><br />
    </form>
</body>
</html>



Default.aspx.cs

using System;
using System.Net.Http;  // 要用 NuGet 安裝
using WebApplication1.Models;   // IRestfulClient 使用的 Client

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        public static readonly HttpClient client = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /* RestSharp 106 和 RestSharp v107 無法共存
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = IRestfulClient.getProductList();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " RestSharp 106.15 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }
        */

        protected async void Button2_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = await IRestfulClient.getProductList_by_HttpClient();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " HttpClient 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }

        // RestSharp v107 開始寫法大改
        protected async void Button3_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = await IRestfulClient.getProductList_by_RestSharp107();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " RestSharp 110.2.0 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }
    }
}




(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 RestSharp 110.2.0 做 Restful API 呼叫
[研究][ASP.NET]用 RestSharp v107 做 RESTful API 呼叫(四)將 RestSharp 106.15 升級 RestSharp 110.2.0
https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615-restsharp.html

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615.html

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)
https://shaurong.blogspot.com/2024/04/aspnetsystemnet-http.html

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html




[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)getProductList

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫(一)getProductList

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

因 RestSharp 於 2009 年首次推出,成為 .NET 開發者中非常受歡迎的一個選擇。在 RestSharp v107 開始,語法大改;而 .NET Framework 4.5 (2012 年推出) 開始提供 HttpClient,考慮改用這個。

********************************************************************************

Web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  如需如何設定 ASP.NET 應用程式的詳細資訊,請前往
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <appSettings>
    <add key="IRestfulServerUrl" value="https://網址/" />
    <add key="IRestfulAccount" value="帳號" />
    <add key="IRestfulPassword" value="密碼" />
  </appSettings>
</configuration>


Models\MyModel.cs


********************************************************************************

Default.aspx

using RestSharp;    // NuGet 安裝 RestSharp 106.15
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Http;    // HttpClient 使用
using System.Threading.Tasks;
using WebApplication1.Models;   // 自己寫的

namespace WebApplication1
{
    public class IRestfulClient
    {
        static readonly string IRestfuleServerURL = ConfigurationManager.AppSettings["IRestfulServerUrl"];
        static readonly string IRestfulAccount = ConfigurationManager.AppSettings["IRestfulAccount"];
        static readonly string IRestfulPassword = ConfigurationManager.AppSettings["IRestfulPassword"];

       ...(略)
public static ProductListResult getProductList() { var client = new RestClient(IRestfuleServerURL + "rest/getProductList"); var request = new RestRequest(Method.POST); RestResponse<ProductListResult> response2; request.AddParameter("acc", IRestfulAccount); request.AddParameter("pass", IRestfulPassword); try { response2 = (RestSharp.RestResponse<ProductListResult>)client.Execute<ProductListResult>(request); } catch (Exception) { throw; } return response2.Data; } public static async Task<ProductListResult> getProductList_by_HttpClient()
{ var httpClient = new HttpClient(); try { var requestBody = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("acc", IRestfulAccount), new KeyValuePair<string, string>("pass", IRestfulPassword) }); var response = await httpClient.PostAsync(IRestfuleServerURL + "rest/getProductList", requestBody);
bool isSuccessStatusCode = response.IsSuccessStatusCode; HttpResponseMessage ensureSuccessStatusCode = new HttpResponseMessage(); if (isSuccessStatusCode == false) { ensureSuccessStatusCode = response.EnsureSuccessStatusCode(); } using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (var streamReader = new StreamReader(responseStream)) using (var jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = new Newtonsoft.Json.JsonSerializer(); return serializer.Deserialize<ProductListResult>(jsonReader); } } } catch (HttpRequestException) { throw; } } ...(略) } }

Default.aspx

<%@ Page Async="true" Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="用 RestSharp v106 呼叫 Restful API" OnClick="Button1_Click" /><br />
        <asp:Button ID="Button2" runat="server" Text="用 HttpClient 呼叫 Restful API" OnClick="Button2_Click" /><br />
        <asp:Label ID="Label_MSG1" runat="server"></asp:Label><br />
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Net.Http;  // 要用 NuGet 安裝
using WebApplication1.Models;   // IRestfulClient 使用的 Client

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        public static readonly HttpClient client = new HttpClient();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = IRestfulClient.getProductList();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " RestSharp 106.15 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }

        protected async void Button2_Click(object sender, EventArgs e)
        {
            Label_MSG1.Text = "";
            ProductListResult content = new ProductListResult();
            try
            {
                content = await IRestfulClient.getProductList_by_HttpClient();
                Label_MSG1.ForeColor = System.Drawing.Color.Green;
                Label_MSG1.Text = DateTime.Now.ToString() + " HttpClient 執行成功。";
            }
            catch (Exception ex)
            {
                //throw;
                Label_MSG1.ForeColor = System.Drawing.Color.Red;
                if (ex != null)
                {
                    Label_MSG1.Text = ex.Message.ToString();
                }
                else
                {
                    Label_MSG1.Text = "不明錯誤。";
                }
            }
        }
        //---
    }
}






(完)

相關

[研究]ASP.NET,WebForm,將 RestSharp 106.15 改用 HttpClient 做 Restful API 呼叫https://shaurong.blogspot.com/2024/04/aspnetwebform-restsharp-10615.html

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)
https://shaurong.blogspot.com/2024/04/aspnetsystemnet-http.html

RestSharp Next (v107) | RestSharp
https://restsharp.dev/v107/#restsharp-v107

NuGet Gallery | RestSharp
https://www.nuget.org/packages/RestSharp/

RestSharp - Simple .NET REST Client - GitHub
https://github.com/restsharp/RestSharp

[研究][ASP.NET WebForm C#]Newtonsoft.Json 13.0.1 序列化、反序列化測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cnewtonsoftjson-1301.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(二)
https://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web_26.html

[研究][ASP.NET WebForm C#]HttpClient 呼叫 Web API、REST/RESTful API 測試(一)
http://shaurong.blogspot.com/2022/02/aspnet-webform-chttpclient-web.html

[研究][ASP.NET WebForm C#]WebClient 呼叫 Web API、REST/RESTful API 測試https://shaurong.blogspot.com/2022/02/aspnet-webform-cwebclient-web.html



[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

[研究]ASP.NET,使用 HttpClient 時 using System.Net.Http; 編譯出錯:System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

Visual Studio 2019 中編譯出錯


using System.Net.Http;   這一行編譯錯誤
 error CS0234: 命名空間 'System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

********************************************************************************

解決:

NuGet 安裝 System.Net.Http 套件。


WebApplication1

正在安裝:

  • System.IO.4.3.0
  • System.Runtime.4.3.0
  • System.Security.Cryptography.Encoding.4.3.0
  • System.Security.Cryptography.Primitives.4.3.0
  • System.Security.Cryptography.Algorithms.4.3.0
  • System.Security.Cryptography.X509Certificates.4.3.0
  • System.Net.Http.4.3.4

********************************************************************************

User

 HttpClient 從 .NET Framework 哪一版開始提供 ?

ChatGPT

HttpClient 類型最初是在 .NET Framework 4.5 中引入的。在這個版本中,它被添加到 System.Net.Http 命名空間中,並且是一個輕量級的 HTTP 客戶端,用於發送 HTTP 請求並處理響應。在後續的 .NET Framework 版本中,它已經得到了改進和擴展。

********************************************************************************

User

 .NET Framework 4.5  何時開始提供

ChatGPT

.NET Framework 4.5 於 2012 年 8 月 15 日正式發布。這個版本引入了許多新功能和改進,包括 HttpClient 類型,這是一個用於發送 HTTP 請求的新型輕量級客戶端。

********************************************************************************

User

using System.Net.Http;   編譯錯誤 error CS0234: 命名空間 'System.Net' 中沒有類型或命名空間名稱 'Http' (是否遺漏了組件參考?)

ChatGPT

看來您在 .NET Framework 的環境中遇到了這個錯誤。在 .NET Framework 4.5 中,HttpClient 位於 System.Net.Http 命名空間中,但有時在使用上可能會遇到這種問題。

這種情況通常是因為專案中沒有正確引用所需的組件。您需要確保專案中包含了正確的組件引用,以便能夠使用 System.Net.Http 命名空間中的類型。

解決方法可能是確保您的專案已經引用了 System.Net.Http 組件。您可以通過以下步驟進行檢查:

  • 在 Visual Studio 中,右鍵點擊專案,然後選擇 "管理 NuGet 程式包"。
  • 在 "已安裝" 選項卡中檢查是否已安裝了 System.Net.Http 程式包。如果沒有,請在 "線上" 選項卡中搜索並安裝。
  • 如果您不使用 NuGet,請確保專案的引用中包含了 System.Net.Http 組件。您可以在專案的屬性中的 "參考" 部分進行檢查和添加。

如果您確認了以上步驟但仍然遇到問題,請確保您的開發環境中已正確安裝了 .NET Framework 4.5 或更新版本。

********************************************************************************

User

System.Net.Http 是 Microsoft 提供的套件 ?

ChatGPT

是的,System.Net.Http 是由 Microsoft 提供的 .NET 標準庫中的一個套件。它包含了 HttpClient 類型,這是用於發送 HTTP 請求的核心類型之一。HttpClient 提供了一個簡潔且功能豐富的 API,可以用於發送 HTTP 請求並處理響應。這個套件是 .NET Framework 和 .NET Core 的一部分,所以它可以在這些平台上使用。

********************************************************************************

User

既然是 .NET Framework 提供,為何還要用 NuGet 安裝 ?

ChatGPT

您提出了一個很好的問題。在某些情況下,特別是在較早的 .NET Framework 版本中,System.Net.Http 套件可能需要通過 NuGet 來安裝,而不是作為 .NET Framework 的一部分提供。

主要的原因之一是.NET Framework 4.5 的發布時機較早,而 NuGet 作為一個套件管理工具,可以用來補充 .NET Framework 的功能。這使得 Microsoft 可以更靈活地引入和更新庫,並讓開發人員能夠在專案中使用最新的版本。

此外,即使在後續版本的 .NET Framework 中,有時開發人員也可能選擇通過 NuGet 安裝 System.Net.Http 套件,這樣可以更容易地管理依賴關係和版本。另外,NuGet 還提供了更頻繁的更新和改進,這樣開發人員就可以更快地獲得最新的功能和修復程序。

總的來說,使用 NuGet 安裝 System.Net.Http 套件的方式可以讓開發人員更靈活地管理和更新庫,並確保他們可以使用最新的功能和修復程序。

********************************************************************************


(完)

相關

[研究]ASP.NET,WebForm,HttpClient client = HttpClientFactory.Create(); 與 HttpClient client = HttpClient.Create(); 差別優缺點

[研究]ASP.NET,WebForm,HttpClient client = HttpClientFactory.Create(); 與 HttpClient client = HttpClient.Create(); 差別優缺點

2024-04-22

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

請問兩者差別?優點?缺點?

HttpClient client = HttpClientFactory.Create();

HttpClient client = HttpClient.Create();

ChatGPT

這兩種方法的差別在於 HttpClient 的建立方式不同。

HttpClientFactory.Create() 使用的是 .NET Core 中的 IHttpClientFactory,可以用來創建和管理 HttpClient 的實例,提供了一個更好的方式來處理 HttpClient 的生命週期管理、資源共享和緩存。

而 HttpClient.Create() 則是直接使用 HttpClient 的建構子建立新的 HttpClient 實例,每次調用都會創建一個新的 HttpClient 實例,並且該實例不會被重複使用。

使用 IHttpClientFactory 的優點:

  • 管理 HttpClient 的生命週期,減少連接數量和資源消耗。
  • 可以使用 HttpClient 的 Named Client 功能,方便配置和使用。
  • 可以配置 HttpClient 的行為,例如 Timeout、Headers、BaseAddress 等等。
  • 可以支援緩存和重試機制,提高可靠性。
  • 可以減少 HttpClient 實例的設定代碼,簡化開發。

使用 HttpClient.Create() 的優點:

  • 簡單易用,不需要透過 DI 等其他機制取得 HttpClient 的實例。
  • 可以快速建立一個新的 HttpClient 實例,適用於只需要臨時使用 HttpClient 的場景。

使用 IHttpClientFactory 的缺點:

  • 需要透過 DI 機制來取得 HttpClient 的實例,開發者需要理解 DI 的使用方法。
  • 需要額外進行配置和設定,比直接使用 HttpClient 的建構子複雜。
  • 需要額外的額外套件支援,例如 Microsoft.Extensions.Http。

使用 HttpClient.Create() 的缺點:

  • 每次使用都需要建立一個新的 HttpClient 實例,會導致資源浪費和效能問題。
  • 無法進行 HttpClient 的生命週期管理,容易造成連接數量過多和資源消耗。
  • 無法使用 HttpClient 的 Named Client 功能,需要額外的代碼來進行配置和管理。

總之,使用 IHttpClientFactory 可以提供更好的 HttpClient 管理方式,適用於大多數情況。只有在一些簡單的臨時場景下,使用 HttpClient.Create() 才是比較好的選擇。

********************************************************************************

WebForm, 而非 .NET Core,請問下面兩者差別?優點?缺點?

HttpClient client = HttpClientFactory.Create();

HttpClient client = HttpClient.Create();

ChatGPT

在 WebForm 中,沒有提供 HttpClientFactory 這個工具,所以這兩個方法都不能在 WebForm 中使用。

在 .NET Framework 中,可以使用 HttpClient 的建構子直接創建新的 HttpClient 實例,例如 HttpClient client = new HttpClient()。使用這種方式創建 HttpClient 實例的優點是簡單易用,不需要額外的套件或設定。

但是,使用這種方式創建 HttpClient 實例的缺點是每次調用都會創建一個新的 HttpClient 實例,會導致資源浪費和效能問題,特別是當應用程式需要與多個 Web API 進行通訊時。此外,使用這種方式,也無法進行 HttpClient 的生命週期管理,容易造成連接數量過多和資源消耗。

綜上所述,在 WebForm 中,建議使用 HttpClient 的建構子直接創建新的 HttpClient 實例,但要注意避免創建過多實例和浪費資源。如果需要進行 HttpClient 的生命週期管理和資源共享,可以使用自行實現的管理機制,例如使用 Singleton 設計模式來管理 HttpClient 實例。

********************************************************************************

下面網頁就在 WebForm 使用 HttpClientFactory

https://shaurong.blogspot.com/2023/03/aspnet-httpclientfactory-restful-api.html

ChatGPT

非常抱歉,我理解錯誤了。在 WebForm 中,實際上可以使用 HttpClientFactory 套件,以便在使用 HttpClient 時進行生命週期管理和資源共享。這是一個優點,可以幫助減少資源浪費和提高效能。另外,使用 HttpClientFactory 還可以更方便地進行配置和設定,例如在 Startup 類別中進行設定。

相比之下,直接使用 HttpClient 的建構子來創建 HttpClient 實例的缺點,包括每次調用都會創建新的 HttpClient 實例,容易導致資源浪費和效能問題,以及無法進行生命週期管理和資源共享的缺點。

********************************************************************************

(完)

[研究]ckeditor 4.22.1 的 CVE 弱點、EOS (End Of Service)

[研究]ckeditor 4.22.1 的 CVE 弱點、EOS (End Of Service)

2024-04-22

Copilot

根據 Snyk 的資料,CKEditor 4.22.1 存在兩個 Cross-site Scripting (XSS) 弱點:

CDATA 檢測不正確的 XSS 弱點:這個弱點允許惡意的 HTML 內容注入,繞過進階內容過濾機制,可能導致 JavaScript 代碼的執行。攻擊者可以利用這個漏洞來發動攻擊,特別是對於啟用了全頁面編輯模式或允許 CDATA 元素的實例。建議升級到 4.24.0 或更高版本 以修復這個問題1。

預覽功能的 XSS 弱點:這個問題影響了啟用了預覽功能的樣本,特別是在 samples/old/**/*.html 和 plugins/[plugin name]/samples/**/*.html 路徑下。同樣,建議升級到 4.24.0 或更高版本 以修復這個問題。

此外,Checkmarx 安全研究團隊也發現了一個存儲型跨站腳本(XSS)漏洞(CVE-2021-33829),影響了 CKEditor 4 的編輯模式。這個漏洞可能影響許多環境,例如博客、內容管理系統和其他接受用戶富文本內容的網站。

Snyk 的 CKEditor 4.22.0 弱點資料
https://security.snyk.io/package/npm/ckeditor4/4.22.0

Checkmarx 關於 CVE-2021-33829 的報告
https://checkmarx.com/blog/cve-2021-33829-stored-xss-vulnerability-discovered-in-ckeditor4-affects-widely-used-cms/

CKEditor 4.22.0 / 4.22.1 的變更紀錄
https://ckeditor.com/cke4/release-notes

CKEditor 4: End of Life June 2023
https://ckeditor.com/blog/ckeditor-4-end-of-life/

(完)


2024年4月21日 星期日

[研究]套件常見 License 授權有哪幾種 ? 簡介 ? 網址 ?

[研究]套件常見 License 授權有哪幾種 ? 簡介 ? 網址 ?

2024-04-21、2024-04-24更新

請說明下面授權,使用後需要對大眾開源? 商業免費使用? 優點? 缺點? 用比較表
  • AGPL (GNU Affero General Public License)
  • Apache 1.0
  • Apache 2.0
  • BSD
  • CDDL (Common Development and Distribution License)
  • CPOL (The Code Project Open License)
  • Creative Commons
  • EPL (Eclipse Public License)
  • GNU GPL(General Public License)
  • LGPL (GNU Lesser General Public License)
  • MIT (Massachusetts Institute of Technology)
  • MPL (Mozilla Public License) 2.0
  • MS-PL(Microsoft Public License)
  • Mozilla Public License
  • Proprietary License

ChatGPT 

以上是一些常見的軟體授權方式,每種授權方式都有其獨特的限制和條款,使用者需要仔細閱讀並理解授權條款,才能選擇適合自己的授權方式。

許可證 需要對大眾開源 商業免費使用 優點 缺點
AGPL(GNU Affero GPL) 鼓勵對原始程式碼的修改和改進,保護開發者貢獻。 對商業用戶可能有限制,尤其是SAAS模型的企業
Apache 1.0 允許閉源派生品,商業使用友好 需要額外的法律審查,一些公司可能存在疑慮
Apache 2.0 提供了更好的專利保護和明確的貢獻者授權 需要額外的法律審查,一些公司可能存在疑慮
BSD 靈活,幾乎沒有限制,商業使用友好 沒有強制要求開源衍生產品的源代碼
CDDL (Common Development and Distribution License) 允許在閉源軟體中使用和修改代碼 與GPL不相容,可能導致無法與部分項目共享代碼
CPOL (The Code Project Open License) 類似BSD,針對微軟的Code Project 社群認可度不高,在某些專案中可能不夠受歡迎
Creative Commons 取決於授權 主要用於非軟體創作 不適用於軟體,缺乏對軟體開發的專門支持
EPL (Eclipse Public License) 適用於Eclipse項目,允許商業使用 商業組織可能對其不夠熟悉
GNU GPL(General Public License) 鼓勵共享和開放性,保持開源 對商業實體可能被視為限制,要求公開原始碼
LGPL (GNU Lesser General Public License) 更適合用於庫和元件,允許與非開源應用程式連結 仍可能對商業公司存在一些限制
MIT (Massachusetts Institute of Technology) 簡單明了,商業友好,幾乎沒有限制 不要求修改後的程式碼公開發布
MPL (Mozilla Public License) 2.0 部分 允許商業使用,要求修改的部分必須開源 不適用於所有項目,有時被規避
MS-PL(Microsoft Public License) 適用於Microsoft的開源專案 對非Microsoft相關的專案可能不適用
Proprietary License (專有許可證) 取決於許可 可以完全控製程式碼的分發和使用 限制了程式碼的自由分發和修改,可能減緩創新和開發速度

********************************************************************************

請列出每個套件的 授權種類 (MIT,GPL,Apache,BSD,MPL,LGPL,AGPL,Creative Commons,CDDL,Proprietary License) ? 

我的程式使用該套件後,我的程式是否需要對大眾開源 ? 是否允許商業免費使用 ? 用比較表 ? 請列完,別中斷

  1. AngleSharp
  2. AngleSharp.Css
  3. AntiXSS
  4. Antlr
  5. Aspose.Cells
  6. Autofac
  7. Autofac.WebApi2
  8. bootstrap
  9. Bootstrap.Datepicker
  10. BouncyCastle
  11. BouncyCastle.Cryptography
  12. BuildBundlerMinifier
  13. ByteSize
  14. ckeditor-full
  15. ClosedXML
  16. Common.Logging
  17. Common.Logging.Core
  18. DocumentFormat.OpenXml
  19. DotNetZip
  20. DotNetZip.Reduced
  21. DynamicQuery
  22. EFUtilities
  23. elmah
  24. elmah.corelibrary
  25. EntityFramework
  26. Enums.NET
  27. ExcelDataReader
  28. ExcelDataReader.DataSet
  29. ExcelNumberFormat
  30. ExtendedNumerics.BigDecimal
  31. FastMember
  32. FastMember.Signed
  33. Font.Awesome
  34. FreeSpire.PDF
  35. html5-shiv
  36. HtmlSanitizer
  37. icheck-bootstrap
  38. Irony
  39. Irony.NetCore
  40. iTextSharp
  41. itextsharp.xmlworker
  42. JetBrains.Annotations
  43. jQuery
  44. jQuery-datetimepicker
  45. jquery.datatables
  46. jQuery.UI.Combined
  47. jQuery.Validation
  48. js-cookie
  49. K2.Workflow.Client
  50. LinqKit
  51. LinqKit.Core
  52. LogicExtensions
  53. MailKit
  54. MathNet.Numerics.Signed
  55. MimeKit
  56. Modernizr
  57. Modernizr.New
  58. Moment.js
  59. Newtonsoft.Json
  60. Newtonsoft.Json.Bson
  61. NLog
  62. NLog.Schema
  63. NPOI
  64. Npoi.Mapper
  65. NReco.PdfGenerator
  66. OdsReaderWriter
  67. Oracle.ManagedDataAccess
  68. Owin
  69. popper.js
  70. Portable.BouncyCastle
  71. Respond
  72. RestSharp
  73. Select2.js
  74. SendGrid
  75. SendGrid.CSharp.HTTP.Client
  76. SendGrid.SmtpApi
  77. SharpZipLib
  78. SixLabors.Fonts
  79. SixLabors.ImageSharp
  80. starkbank-ecdsa
  81. Swashbuckle
  82. Swashbuckle.Core
  83. vue
  84. WebActivatorEx
  85. WebGrease
  86. WkHtmlToPdf
  87. X.PagedList
  88. XLParser

ChatGPT

(敝人未全部實際驗證)

套件名稱授權種類對大眾開源需求商業免費使用允許
AngleSharpMIT
AngleSharp.CssMIT
AntiXSSMIT
AntlrBSD
Aspose.CellsProprietary License
AutofacMIT
Autofac.WebApi2MIT
bootstrapMIT
Bootstrap.DatepickerMIT
BouncyCastleMIT
BouncyCastle.CryptographyMIT
BuildBundlerMinifierApache 2.0
ByteSizeMIT
ckeditor-fullGPL
ClosedXMLMIT
Common.LoggingApache 2.0
Common.Logging.CoreApache 2.0
DocumentFormat.OpenXmlApache 2.0
DotNetZipMS-PL
DotNetZip.ReducedMS-PL
DynamicQueryMIT
EFUtilitiesMIT
elmahApache 2.0
elmah.corelibraryApache 2.0
EntityFrameworkApache 2.0
Enums.NETMIT
ExcelDataReaderMIT
ExcelDataReader.DataSetMIT
ExcelNumberFormatMIT
ExtendedNumerics.BigDecimalMIT
FastMemberMIT
FastMember.SignedMIT
Font.AwesomeMIT
FreeSpire.PDFProprietary License
html5-shivMIT
HtmlSanitizerMIT
icheck-bootstrapMIT
IronyMIT
Irony.NetCoreMIT
iTextSharpAGPL
itextsharp.xmlworkerAGPL
JetBrains.AnnotationsMIT
jQueryMIT
jQuery-datetimepickerMIT
jquery.datatablesMIT
jQuery.UI.CombinedMIT
jQuery.ValidationMIT
js-cookieMIT


LinqKitMIT
LinqKit.CoreMIT
LogicExtensionsMIT
MailKitMIT
MathNet.Numerics.SignedMIT
MimeKitMIT
ModernizrMIT
Modernizr.NewMIT
Moment.jsMIT
Newtonsoft.JsonMIT
Newtonsoft.Json.BsonMIT
NLogBSD
NLog.SchemaBSD
NPOIApache 2.0
Npoi.MapperApache 2.0
NReco.PdfGeneratorProprietary License
OdsReaderWriter (註1)GPLv2 
Oracle.ManagedDataAccessProprietary License
OwinApache 2.0
popper.jsMIT
Portable.BouncyCastleMIT
RespondMIT
RestSharpApache 2.0
Select2.jsMIT
SendGridProprietary License
SendGrid.CSharp.HTTP.ClientProprietary License
SendGrid.SmtpApiProprietary License
SharpZipLib (註2)MIT
SixLabors.FontsApache 2.0
SixLabors.ImageSharpApache 2.0
starkbank-ecdsaMIT
SwashbuckleApache 2.0
Swashbuckle.CoreApache 2.0
vueMIT
WebActivatorExApache 2.0
WebGreaseApache 2.0

註1:ChatGPT說OdsReaderWriter是MIT/否/是,不對,NuGet 版應該是 "GPL/是/否"。

How to Read and Write ODF/ODS Files (OpenDocument Spreadsheets),提供 odsreadwrite.zip
https://www.codeproject.com/Articles/38425/How-to-Read-and-Write-ODF-ODS-Files-OpenDocument-2
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

OdsReaderWriter 1.0.10 (GPL-2.0-only)
https://www.nuget.org/packages/OdsReaderWriter

NuGet OdsReaderWriter 1.0.10 相依套件 DotNetZip.Reduced.1.9.1.8 和 OdsReaderWriter.1.0.10

註2:ChatGPT說 SharpZipLib是 GPL/是/否,應是 "MIT/否/是"。

********************************************************************************

ChatGPT

套件名稱授權種類開源要求商業使用
AjaxControlToolkitProprietary License不需要對大眾開源允許商業使用
ckeditor v4 (< 4.23.0)LGPL需要對大眾開源 (需公開源碼)允許商業使用
ckeditor v4 (>= 4.23.0)GPL需要對大眾開源 (需公開源碼)商業使用需特別注意 GPL 的規範
ckeditor v5GPL需要對大眾開源 (需公開源碼)商業使用需特別注意 GPL 的規範
Froala EditorProprietary License不需要對大眾開源商業使用需購買授權,詳情需參考 Froala 官方授權條款
jHtmlAreaLGPL需要對大眾開源 (需公開源碼)允許商業使用
QuillBSD需要對大眾開源 (需保留原始授權條款)允許商業使用
SummernoteMIT需要對大眾開源 (需保留原始授權條款)允許商業使用
TinyMCELGPL需要對大眾開源 (需公開源碼)允許商業使用
TrumbowygMIT需要對大眾開源 (需保留原始授權條款)允許商業使用

Copilot

套件名稱授權種類開源商業免費使用
AjaxControlToolkitMIT License
ckeditor v4 (< 4.23.0)GPL License
ckeditor v4 (>= 4.23.0)GPL License
ckeditor v5GPL License
Froala EditorProprietary License
jHtmlAreaMIT License
QuillMIT License
SummernoteMIT License
TinyMCELGPL License
TrumbowygMIT License

********************************************************************************

https://ckeditor.com/docs/ckeditor5/latest/support/licensing/license-key-and-activation.html

CKEditor 5 (without premium features listed above) can be used without activation as open source software under the GPL license. It will then display a small “Powered by CKEditor” logo in the editor area.

********************************************************************************

https://ckeditor.com/docs/ckeditor4/latest/support/licensing/license-and-legal.html
CKEditor 4 reached its End of Life (EOL) in June 2023

Free for Open Source (CKEditor 4.22.* and below)

Licensed under the terms of any of the following licenses at your choice:

  • GNU General Public License Version 2 or later (the “GPL”) https://www.gnu.org/licenses/gpl.html (See Appendix A)
  • GNU Lesser General Public License Version 2.1 or later (the “LGPL”) https://www.gnu.org/licenses/lgpl.html (See Appendix B)
  • Mozilla Public License Version 1.1 or later (the “MPL”) https://www.mozilla.org/MPL/MPL-1.1.html (See Appendix C)

You are not required to, but if you want to explicitly declare the license you have chosen to be bound to when using, reproducing, modifying, and distributing this software, just include a text file titled “legal.txt” in your version of this software, indicating your license choice. In any case, your choice will not restrict any recipient of your version of this software to use, reproduce, modify, and distribute this software under any of the above licenses.

********************************************************************************

ckeditor v4 full, v4 standard, v5 standard 我的程式使用該套件後,我的程式是否需要對大眾開源 ?

ChatGPT

CKEditor v4 full、v4 standard 和 v5 standard 這些版本都採用 GPL 授權。根據 GPL 授權條款,如果您的程式使用了這些套件,並且將它們與您的程式一起發布或分發,那麼您的程式也必須使用 GPL 授權發布,並且源代碼必須對大眾開源。

********************************************************************************

User

froara editor我的程式使用該套件後,我的程式是否需要對大眾開源 ?

ChatGPT

Froala Editor 通常使用了一種商業授權模式,並不是免費的。當然,您需要仔細檢查您的 Froala Editor 授權,以確定您使用的是哪種授權版本,以及您是否需要對您的程式進行開源。通常情況下,商業授權模式允許您將 Froala Editor 整合到您的商業應用中,而無需對您的程式進行開源。建議您檢查 Froala Editor 的官方網站或其授權條款以獲取更詳細的信息。

********************************************************************************

User

froara editor我的程式使用該套件後,我的程式是否需要對大眾開源 ?

ChatGPT

Froala Editor 的授權取決於您所選擇的版本。Froala 提供了兩種版本:商業版和社區版(Community Edition)。

  • 商業版:商業版通常需要購買許可證,並且可能附帶了一些限制和條款。根據商業版的條款,您的程式不一定需要對大眾開源。
  • 社區版:社區版是免費提供的,並且使用了較為寬鬆的授權條款(如 MIT 授權)。通常情況下,如果您的程式使用了 Froala Editor 的社區版,您不需要對大眾開源。

請仔細檢查您所使用的 Froala Editor 的版本和相關的授權條款,以確定您的程式是否需要對大眾開源。

********************************************************************************

User

Froara editor 若是商業使用,免費? 付費 ? 我的程式使用該套件後,我的程式是否需要對大眾開源 ?

ChatGPT

Froala Editor 的商業使用通常需要購買授權。他們提供了付費的商業授權模式,這允許您在商業環境中使用 Froala Editor,而不必將您的程式開源。

因此,如果您的程式使用了 Froala Editor 的商業授權版本,您通常不需要對大眾開源。但請確保您仔細閱讀並理解 Froala Editor 的商業授權條款,以確保您的使用符合其要求。

********************************************************************************

User

ASP.NET,WebForm,所謂的套件是否商業使用如何判定? 公司的門戶網站,但該網站並非購物網站,僅是提供大眾信息,是否算商業使用?

ChatGPT

在判定 ASP.NET WebForm 中的套件是否可以商業使用時,關鍵因素是該套件的授權條款。 通常,大多數套件都會有明確的授權條款,其中規定了是否可以在商業環境中使用以及使用的條件。 常見的授權類型包括 MIT 授權、GNU 通用公共授權(GPL)、Apache 授權等。

如果您在公司的入口網站上使用的套件有明確的許可證,您需要仔細閱讀該許可證以確定您是否符合使用條件。 有些許可證可能會明確指出可以在商業環境中使用,而其他許可證則可能對商業使用施加了一些限制。

關於您提到的情況,即公司入口網站不是購物網站,而是提供資訊的網站,通常也被視為商業使用。 即使網站不直接進行商品交易,但它仍然是公司的一部分,可能用於宣傳、品牌展示或與客戶溝通。 因此,使用在這樣的網站上的套件可能被認為是商業使用。

在任何情況下,如果您對特定套件的使用條件有疑問,最好的做法是直接查閱該套件的許可證或與該套件的維護者或發布者聯繫,以獲取準確的資訊。

********************************************************************************

User

台灣,法人化單位的網站,是否算商業使用? 政府單位的網站,是否算商業使用? 內部使用的網站,是否算商業使用?政府託管經營的網站,是否算商業使用?

ChatGPT

在許多情況下,台灣的法人化單位的網站通常被視為商業使用。 這些網站可能用於宣傳公司業務、產品或服務,吸引潛在客戶、提供公司資訊等。 即使網站本身不直接進行商品銷售,但其目的通常是為了促進公司的商業活動和利益,因此通常被視為商業使用。

政府單位的網站通常不被視為商業使用,因為它們的目的不是為了盈利,而是為了提供公共服務和資訊。 這些網站可能包括政府機構的官方網站、公共服務網站等。 雖然政府網站不會被視為商業使用,但仍需要遵守相關的法律法規和規定。

內部使用的網站通常不被視為商業使用,因為它們的主要目的是為了公司內部的員工或成員提供資訊、工具或服務,而不是為了外部的獲利目的。 這些網站可能包括內部通訊、員工培訓、公司資源管理等。 雖然這些網站不被視為商業使用,但仍需要遵守公司內部的政策和規定,以及可能適用的法律法規。

政府託管運營的網站通常不被視為商業使用。 這些網站是由政府機構或相關單位運營和管理,其目的是向公眾提供公共服務、資訊和資源。 這些網站可能包括政府部門的官方網站、公共服務網站、政策宣傳網站等。

這些網站的運營通常由政府資金支持,其主要目的是為了服務公眾、提供政府資訊、執行政府計劃和政策,而不是為了盈利。 因此,它們通常不被視為商業使用。

需要注意的是,以上僅為一般性概述,並不代表法律建議。 具體情況可能會因國家/地區的法律法規、具體用途和其他因素而有所不同。 因此,如果您有具體的法律或許可證問題,最好諮詢相關的法律顧問或專業人士以獲得準確的建議。

然而,雖然政府託管經營的網站不算商業使用,但它們仍然需要遵守相關的法律法規,以確保資訊安全、隱私保護和其他相關事項。

********************************************************************************

(完)

[研究]在 CKEditor 5 中添加「View Source」按鈕

[研究]在 CKEditor 5 中添加「View Source」按鈕

2024-04-19

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

ckeditor v5 支援 View Code 或 View Source 按鈕 ?

ChatGPT

CKEditor 5 是一個先進的 WYSIWYG 編輯器,它提供了一個稱為「Source Editing」的功能,允許使用者切換到 HTML 源代碼視圖。然而,相對於 CKEditor 4,CKEditor 5 不再直接提供名為「View Code」或「View Source」的按鈕。相反,它提供了一個 API,你可以使用它來自定義和添加按鈕或其他 UI 元素來實現此功能。

要實現類似的功能,你可以通過 CKEditor 5 提供的 API 添加自定義按鈕,然後使用該按鈕觸發切換到 HTML 源代碼視圖的操作。這需要一些 JavaScript 編程,但CKEditor 5 的文檔提供了很好的指導和範例來幫助你完成這項任務。

********************************************************************************

CKEditor 5 - Source Editing Feature

https://ckeditor.com/docs/ckeditor5/latest/features/source-editing.html

註:敝人聞了 ChatGPT 和 Copilot 多次,得到的 Code 實際測試,都失敗,故提供官方的說明。

********************************************************************************

(完)

相關

[研究]ASP.NET,WebForm,常見CDN(Content Delivery Network,內容交付網路)網址

[研究]ASP.NET,WebForm,常見CDN(Content Delivery Network,內容交付網路)網址

2024-04-21

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

ASP.NET,WebForm,請推薦常見CDN網址,愈推薦的,放愈上面。

Copilot

以下是幾個常見的 CDN(內容交付網路)服務提供商,我會按照推薦程度進行排序:

  1. Cloudflare:Cloudflare 是最受歡迎的免費 CDN 之一,並且具有出色的性能。在全球 6 大洲的測試中,Cloudflare 平均加速了移動站點的加載速度達到 43%1。它在 100 多個國家擁有 275 多個數據中心,具有出色的地理覆蓋範圍。設置非常簡單,只需將您的域名解析指向 Cloudflare 即可。此外,Cloudflare 還提供免費的 SSL、DDoS 保護和防火牆規則等功能,但高級 WAF、負載平衡和其他企業級功能需要升級計劃。
  2. BunnyCDN:BunnyCDN 是一個較不知名但優秀的免費 CDN 選項,並且不像 Cloudflare 那樣存在單點故障。在我的測試中,BunnyCDN 全球加速了移動站點的加載時間達到 29%1。雖然稍遜於 Cloudflare,但對於免費服務來說仍然非常出色。它在 6 大洲擁有 50 多個點的存在,覆蓋範圍較小但仍然可觀。設置簡單,只需添加幾個 CNAME 記錄即可。它包括免費的 SSL 和入門級 DDoS 保護,但不像 Cloudflare 那樣具有高級防火牆規則或 WAF。如果您需要一個不會因問題而使整個站點癱瘓的免費 CDN,BunnyCDN 是一個不錯的選擇,您會失去一些安全保護,但獲得內置的冗餘性。
  3. StackPath:StackPath 在價格和功能之間取得了良好的平衡,並且具有適合電子商務站點的強大安全保護。在我的測試中,StackPath 全球加速了加載時間達到 36%1。考慮到涉及的額外安全層,這是非常令人印象深刻的速度。它在 5 大洲擁有 45 多個邊緣站點,足夠大的覆蓋範圍適用於大多數情況。價格從每月 20 美元起,可獲得高達 1TB 的流量。

請根據您的需求和預算選擇適合您的 CDN 服務提供商。

The 7 Best CDN Services for 2024 (Comparison & Benchmarks),March 7, 2024
https://www.33rdsquare.com/cdn-services/#google_vignette

********************************************************************************

ASP.NET,WebForm,請推薦常見CDN網址,愈推薦的,放愈上面。
ChatGPT
當你在使用ASP.NET WebForms時,CDN(Content Delivery Network)可以幫助提高你的網站的效能和載入速度。 以下是一些常見的CDN服務供應商,你可以考慮使用:
  1. Microsoft Ajax CDN - Microsoft 提供的CDN服務,提供了 ASP.NET WebForms 的 Microsoft Ajax 程式庫和其他相關資源。https://learn.microsoft.com/zh-tw/aspnet/ajax/cdn/overview
  2. Google CDN - Google 提供了一個用於常見 JavaScript 函式庫(如 jQuery、AngularJS)的 CDN。 這些庫通常也可以用於 ASP.NET WebForms 專案。https://cloud.google.com/cdn/
  3. Cloudflare CDN - Cloudflare 是一個廣泛使用的CDN服務供應商,提供了全球效能優化和安全功能。https://www.cloudflare.com/zh-tw/application-services/products/cdn/
  4. Amazon CloudFront - Amazon 的 CDN服務,提供了高度可靠的全球內容傳遞和快取。https://aws.amazon.com/tw/cloudfront/
  5. Bootstrap CDN - 如果你在專案中使用了 Bootstrap 框架,Bootstrap 提供了自己的CDN服務,用於加速 Bootstrap 資源的加載。https://www.bootstrapcdn.com/
  6. cdnjs - cdnjs 是一個託管常見 JavaScript 庫的CDN,它提供了許多流行的庫的快速加載。https://cdnjs.com/
  7. jsDelivr - jsDelivr 是一個免費開源的CDN服務,提供了許多開源項目的資源載入。https://www.jsdelivr.com/
這些CDN服務提供了快速、可靠的內容傳遞,可幫助提高你的 ASP.NET WebForms 網站的效能。 當然,根據你的具體需求和項目配置,你可能會更偏好某些CDN服務供應商。
********************************************************************************
ASP.NET,WebForm,對於在台灣的使用者,請推薦常見CDN網址,愈推薦的,放愈上面。

Copilot

對於在台灣使用 ASP.NET Web Forms 的使用者,以下是一些常見的 CDN 網址,您可以根據推薦程度將它們放在您的網頁上:
  1. Microsoft Ajax Content Delivery Network (CDN):這是由 Microsoft 提供的官方 CDN,用於提供 ASP.NET Web Forms 中的 jQuery 和其他前端資源。
  2. Google Hosted Libraries:Google 提供的 CDN,包含了許多流行的 JavaScript 函式庫,例如 jQuery、Angular、React 等。
  3. cdnjs:這是一個社群維護的 CDN,提供了大量的前端資源,包括 CSS、JavaScript 等。
  4. jsDelivr:另一個社群維護的 CDN,支援許多流行的前端框架和函式庫。
您可以根據您的需求選擇適合的 CDN,並將它們添加到您的 ASP.NET Web Forms 專案中。
********************************************************************************
ASP.NET,WebForm,對於在台灣的使用者,請推薦常見CDN網址,愈推薦的,放愈上面。
ChatGPT
對於在台灣的使用者,以下是一些常見的 CDN(Content Delivery Network)網址,這些 CDN 在提供靜態資源(如圖片、CSS、JavaScript)時通常都具有良好的效能和可用性:
這些 CDN 都有在台灣地區部署伺服器,能夠提供更快速的資源傳送,對於提升網站的性能和用戶體驗非常有幫助。
********************************************************************************

(完)

相關

2024年4月20日 星期六

[研究]ASP.NET,WebForm,試用 jHtmlArea 1.0.0 WYSIWYG HTML editor 套件

[研究]ASP.NET,WebForm,試用 jHtmlArea 1.0.0 WYSIWYG HTML editor 套件

2024-04-19

Awesome WYSIWYG EDITORS 

https://github.com/JefMari/awesome-wysiwyg-editors


環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

********************************************************************************

NuGet 安裝 jHtmlArea 套件,jQuery 可安裝或用 CDN 的

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
   <%-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>--%>
    <script src="Scripts/jquery-1.4.1.min.js"></script>
    <%--<link href="Content/jHtmlArea/jHtmlArea.Editor.css" rel="stylesheet" />不是,黑底,一堆黑點--%>
    <%--<link href="Content/jHtmlArea/jHtmlArea.ColorPickerMenu.css" rel="stylesheet" />不是,白底,一堆黑點--%>
    <link href="Content/jHtmlArea/jHtmlArea.css" rel="stylesheet" />
    <script src="Scripts/jHtmlArea.min.js"></script>

    
</head>
<body>
    <form id="form1" runat="server">
        <textarea id="editor" runat="server" style="width: 100%; height: 500px;"></textarea>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </form>

    <script type="text/javascript">
        //$(function () {
        //    $("textarea").htmlarea({
        //        toolbar: ["html", "|",
        //            "forecolor",  // <-- Add the "forecolor" Toolbar Button
        //            "|", "bold", "italic", "underline", "|", "h1", "h2", "h3", "|", "link", "unlink"] // Overrides/Specifies the Toolbar buttons to show
        //    });
        //});

        $(document).ready(function () {
            $("#editor").htmlarea({
                toolbar: [
                    ["bold", "italic", "underline", "strikethrough"],
                    ["p", "h1", "h2", "h3", "h4", "h5", "h6"],
                    ["link", "unlink", "image"],
                    ["html"] // 添加 HTML 按鈕到工具欄
                ],
                loaded: function () {
                    //this.toggleHtmlEditor("bold"); // 將粗體按鈕設置為按下狀態
                    //this.toggleView(); // 切換到 HTML 編輯視圖; 無效
                }
            });
        });

        editor.htmlarea("insertHtml", "<p>Initial content</p>"); // 設置初始內容

        // 將 HTML 按鈕設置為按下狀態
        //setTimeout(function () {
        //    editor.htmlarea("toggleHtmlEditor", "html");    //無效
        //}, 0);

        // 使用 execute 方法模擬點擊 HTML 按鈕
        //setTimeout(function () {
        //    editor.htmlarea("execute", "html");//無效
//}, 0); // 使用 jQuery 將 HTML 按鈕設置為按下狀態 setTimeout(function () { $(".jHtmlArea .toolset button[name=html]").addClass("active");//無效
}, 0); </script> </body> </html>

Default.aspx.cs

using System;
namespace WebApplication3
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string content = editor.Value;
            // 在此處處理編輯器的內容
        }
    }
}

 下圖,toolbar會在TextArea左邊,原因不明,待解決

(完)

相關

[研究]ASP.NET,WebForm,試用Froala 4.2.0 WYSIWYG HTML editor 套件

[研究]ASP.NET,WebForm,試用Froala 4.2.0 WYSIWYG HTML editor 套件

2024-04-20

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 19

官方網站:https://froala.com/wysiwyg-editor/

Pricing (價格):https://cart.froala.com/。Free Trial 只提供 自架服務 (Self-Hosted)

範例:https://froala.com/wysiwyg-editor/docs/overview/

https://froala.com/wysiwyg-editor/examples/

********************************************************************************

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.2.0/css/froala_editor.pkgd.min.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <textarea id="editor" runat="server"></textarea><br />
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
        </div>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.2.0/js/froala_editor.pkgd.min.js"></script>
    <script> 
        var editor = new FroalaEditor('#editor');
    </script>
</body>
</html>


Default.aspx.cs

using System;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string quillContent = Request.Form["editor"];
            Response.Write("<script>alert('" + quillContent + "')</script>");
        }
    }
}






********************************************************************************
Froala 4.2.0 WYSIWYG HTML editor 可免費使用 ? 可免費商用使用 ?

ChatGPT

Froala Editor 4.2.0是一款商業產品,提供了免費版本和付費版本。 免費版本包含了基本功能,而付費版本則提供了更多高級功能和技術支援。

根據Froala的官方授權協議,免費版本主要適用於個人專案、非商業專案以及非營利組織。 如果你的專案是商業用途或是為獲利目的,那麼你可能需要購買Froala Editor的許可證。 商業許可證的價格取決於你的專案規模和需要的功能。

在任何情況下,建議在使用Froala Editor之前查看其最新的許可協議,以確保你的使用符合其規定。 你可以在Froala的官方網站上找到最新的授權資訊和購買選項。

********************************************************************************
下圖,NuGet安裝版

下圖,F5執行index.html會出錯





嚴重性 程式碼 說明 專案 檔案 隱藏項目狀態
錯誤 Build:索引簽章參數類型必須為 'string' 或 'number'。 WebApplication2 C:\CodeTemp\WebApplication2\WebApplication2\Scripts\froala-editor\index.d.ts 1534
錯誤 Build:索引簽章參數類型必須為 'string' 或 'number'。 WebApplication2 C:\CodeTemp\WebApplication2\WebApplication2\Scripts\froala-editor\index.d.ts 1535
警告 元素 'html' 需要有結束標記。 WebApplication2 C:\CodeTemp\WebApplication2\WebApplication2\Scripts\froala-editor\index.html 2


NuGet的 Froala 4.2.0 安裝版有問題,無法使用。

********************************************************************************

(完)

相關