2019年6月27日 星期四

[C#] 基礎連接已關閉: 傳送時發生未預期的錯誤











最近一個爬資料程式遇到"基礎連接已關閉: 傳送時發生未預期的錯誤"

查了一下原因應是TLS舊的1.0有資安問題, 個網站已經陸續被停用
(相關文章)

因此我們可加入以下code,設定相關通訊協定

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

要注意 一下.NET版本, 4.5以上有支援



參考 : https://blog.darkthread.net/blog/webclient-and-tls12/
https://stackoverflow.com/questions/19639846/failure-on-httpwebrequest-with-inner-exception-authentication-failed-because-the/39534068#39534068

2019年6月6日 星期四

[C#] itextsharp (5.x版)

最近遇到需求要產出pdf

但又遇到server沒有office, 無法直接把word轉成PDF

所以直接用itext自己建立一份PDF

建立過程中遇到
1.建立固定Header,Footer
2.加入浮水印
3.加入圖片
4.建立表格

先記錄一下參考的網站,整體來說基本問題都能解決了~

參考
pdf footer,header :
http://kuujinbo.info/cs/itext.aspx
https://www.codeproject.com/Questions/112064/How-to-add-Header-and-Footer-in-a-pdf-using-itexts
https://stackoverflow.com/questions/39603619/footer-in-pdf-with-itextsharp?answertab=active#tab-top

add image : 
https://dotblogs.com.tw/kevinya/2016/01/07/101253


2019年5月2日 星期四

[C#] dotnetzip 打包多筆word匯出zip


使用dotnetzip 套件來打包多筆word

直接將byte存進zip並存在記憶體匯出檔案

// 測試用匯出zip 多筆word
var bytes = exportSvc.Export(ID);
var bytes2 = exportSvc.Export(ID);
 
// 打包多筆Word
using (var zip = new ZipFile())
{
    zip.AddEntry("name_of_the_file.docx", bytes);
    zip.AddEntry("name_of_the_file2.docx", bytes2);
 
    // 存記憶體並匯出
    using (MemoryStream output = new MemoryStream())
    {
        zip.Save(output);
        return File(output.ToArray(), "application/zip", "sample.zip");
    }
}


2019年4月30日 星期二

[C#] 取得有效位數 ex.0.0001234 => 0.000123

如取得有效三位數
ex. 12345 => 12300
ex. 1.2345 => 1.23
ex. 0.0001234 => 0.000123

// 取得有效位數
       private static double RoundToSignificantDigits(double d, int digits)
       {
           if (d == 0.0)
           {
               return 0.0;
           }
           else
           {
               double leftSideNumbers = Math.Floor(Math.Log10(Math.Abs(d))) + 1;
               double scale = Math.Pow(10, leftSideNumbers);
               double result = scale * Math.Round(d / scale, digits, MidpointRounding.AwayFromZero);
 
               // Clean possible precision error.
               if ((int)leftSideNumbers >= digits)
               {
                   return Math.Round(result, 0, MidpointRounding.AwayFromZero);
               }
               else
               {
                   return Math.Round(result, digits - (int)leftSideNumbers, MidpointRounding.AwayFromZero);
               }
           }
       }

參考: https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures

[加密] 記錄用 Gpg4Win

參考 : https://blog.timshan.idv.tw/2013/09/howto-gpg4win.html

2019年4月25日 星期四

[SQL] [Error] 資料表的識別欄位其外顯值只有當使用了資料行清單且 IDENTITY_INSERT 為 ON 時才能指定。

SQL 要更新trigger 內容時

出現以下內容 :

資料表的識別欄位其外顯值只有當使用了資料行清單且 IDENTITY_INSERT 為 ON 時才能指定。

這次的原因原來是 insert 時, 想要去改動 又自動增號的ID 才會這樣

解法:
1. 明確定義要insert 的欄位
2. 不明確定義欄位,就要把自動增號的值拿掉