2020年10月28日 星期三

未分類 NoSQL 初學

1.先了解NoSQL是什麼及優缺點,陳士杰老師簡報很清楚巨量資料技術與應用
2.NoSQL及選擇那一套軟體,[美股研究] MongoDB (MDB) — 最多人使用的NoSQL 資料庫
3.NoSQL種類,維基
4.選擇您最適合的

2020年10月15日 星期四

C# 登入網路磁碟機且輸入帳號密碼(with .net core 2024 update)

Can you explain why DirectoryInfo.GetFiles produces this IOException?
以下程式碼來源如參考網站
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace Company.Security
{
    public class ImpersonateUser : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError=true)]
        private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

        [DllImport( "kernel32", SetLastError = true )]
        private static extern bool CloseHandle(IntPtr hObject);

        private IntPtr userHandle = IntPtr.Zero;
        private WindowsImpersonationContext impersonationContext;

        public ImpersonateUser( string user, string domain, string password )
        {
            if ( ! string.IsNullOrEmpty( user ) )
            {
                // Call LogonUser to get a token for the user
                bool loggedOn = LogonUser( user, domain, password,
                    9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                    3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                    out userHandle );
                if ( !loggedOn )
                    throw new Win32Exception( Marshal.GetLastWin32Error() );

                // Begin impersonating the user
                impersonationContext = WindowsIdentity.Impersonate( userHandle );
            }
        }

        public void Dispose()
        {
            if ( userHandle != IntPtr.Zero )
                CloseHandle( userHandle );
            if ( impersonationContext != null )
                impersonationContext.Undo();
        }
    }
}
使用方法
using ( new ImpersonateUser( "UserID", "Domain", "Password" ) )
{
    // Any IO code within this block will be able to access the remote server.
}
.net Core(20240219更新) Only windows server
 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
 public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

 const int LOGON32_PROVIDER_DEFAULT = 0;
 //This parameter causes LogonUser to create a primary token. 
 const int LOGON32_LOGON_INTERACTIVE = 2;
 // Call LogonUser to obtain a handle to an access token. 
 SafeAccessTokenHandle safeAccessTokenHandle;
 public IActionResult X()
 {
            try
            {
               
                bool returnValue = LogonUser("test", "mydomain", "test123", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeAccessTokenHandle);
                if (!returnValue)
                    throw new Exception("登入unc路徑錯誤!!");

 
                WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
                {
                    var basepath = @"\\192.168.0.1\testFiles";

                    if (!Directory.Exists(basepath))
                    {
                        throw new Exception("無資料夾-" + basepath);
                    }

                    DirectoryInfo root = new DirectoryInfo(basepath);
                    FileInfo[] files = root.GetFiles();
                    foreach (var item in files)
                    {
                        try
                        {
                            
                           // item.Delete();
                                

                        }
                        catch (Exception ex)
                        {
                            throw new Exception( ex.Message);
                        }
                    }
                });
 

            }
            catch (Exception ex)
            {
                sb.Append($"error:{ex.Message}");
            }
 
 }
參考來源
Can you explain why DirectoryInfo.GetFiles produces this IOException?
How to pass unc credential in .net corev

2020年10月12日 星期一

未分類 下載M3U8影音串流

1.先了解M3U8 串流影音 — 概念 與 下載
2.下載ffmpeg與1.內容所述安裝ffmpeg
3.chrome至下載的網址後按F12 > Network > 下面的name 找到.m38s > 右鍵 > Copy > Copy Link Address
4.開啟命令提示字元cmd
ffmpeg -protocol_whitelist "file,http,https,tcp,tls" ^
-i "https://xxx.m3u8" ^
-c copy "D:\test.mp4"
-i來源
-c存放點
2021-02-19補充下載azure
1.如何下載azure的部分教學視頻先下載ffmpeg.exe跟youtube-dl.exe
2.chrome至下載的網址後按F12 > Network > 搜尋manifest > 右鍵 > Copy > Copy Link Address
3.開啟命令提示字元cmd
youtube-dl.exe --merge-output-format mp4 "https://xxxx.azure.net/xxxxxx/manifest(format=mpd-time-csf)"
參考來源
M3U8 串流影音 — 概念 與 下載
如何下載azure的部分教學視頻

2020年8月24日 星期一

ssls.com 憑證流程

https://www.ssls.com/
1.在官網上面購買
2.至Server上IIS 建立憑證要求
用cmd去產生
名稱必須要有網域跟2048加密
-----BEGIN NEW CERTIFICATE REQUEST-----
中間內容
-----END NEW CERTIFICATE REQUEST-----
名稱必須要有網域跟2048加密
-----BEGIN NEW CERTIFICATE REQUEST-----
中間內容
-----END NEW CERTIFICATE REQUEST-----
3.SSL.com上輸入CSR選擇windows按確定(勿使用自動的)
4.聯絡線上客服驗證看要怎麼驗證用DNS 他會給host and target設定一組CName一下就可以
5.下載憑證上傳至Server
6.IIS完成憑證要求
7.IIS網站更新繫結
如果在伺服器上完成憑證後按F5不見
就要重建立憑證要求重作
很久沒用搞了兩天終於可以了
給自己筆記一下

2020年7月3日 星期五

.Net Core Razor decimal 去除後面多於小數點

<input type="number" asp-for="@Model[i].Field" class="form-control text-right" required step="1" asp-format="{0:0.#}" >

自己筆記一下

2020年4月24日 星期五

.Net Core One Form MultipeSubmit with ajax

之前一個from多按鈕作法在網路上很多
MultipleButtonAttribute<=之前都用這個方式可Google就有了
使用.Net Core時單純的直接submit的話一般方法都可以
目前使用jquery.unobtrusive-ajax來做的話都送不到後端
但用習慣了還是想繼續用下去
試過了很多方法最後找到一篇文章經測試後可以使用
Html部分如下跟之前一樣只是沒特別指定asp-controller and asp-action
<form data-ajax-begin="OnBegin" data-ajax-complete="OnComplete" data-ajax-method="post" data-ajax-success="OnSuccess" data-ajax="true" id="from1" method="post">
<div class="form-group">
<button class="btn btn-primary" id="Edit" type="submit">編輯</button>
      <button class="btn btn-danger" id="Delete" type="submit">刪除</button>          
   </div>
</form>
javascript部分使用jquery在按鈕點擊後加上data-ajax-url的url
這是這次的重點部分
<script src="~/lib/Microsoft.jQuery.Unobtrusive.Ajax/jquery.unobtrusive-ajax.min.js"></script>
     <script>
        $("#Edit").on("click", function () {
            $("#from1").attr("data-ajax-url", "@Url.Action("自訂Action", "自訂Controller")" );
        });

        $("#Delete").on("click", function () {
              if (!confirm("確定刪除!!"))
                    return false;

            $("#from1").attr("data-ajax-url", "@Url.Action("自訂Action", "自訂Controller")" );
        });
    </script>
後端部分宣告兩個ActionResult來接收即可
[HttpPost]
[ValidateAntiForgeryToken]       
public IActionResult Edit()
{
    ResultViewModel result = new ResultViewModel();
    return Json(result);
}

[HttpPost,ActionName("Delete")]
[ValidateAntiForgeryToken]     
public IActionResult DeleteConfirmed()
{
     ResultViewModel result = new ResultViewModel();
return Json(result);
}
個人覺得這樣寫程式有點不好看
但目前好像就只有這方法可行
歡迎有更好方法可以提供謝謝
參考來源
jQuery Unobtrusive Ajax Helpers in ASP.NET Core
Multiple Submit Buttons

2020年3月12日 星期四

c# 基礎連接已關閉: 無法為 SSL/TLS 安全通道建立信任關係。

公司將一些網站改走SSL後發現有些POST取資料功能失效了
出現基礎連接已關閉: 無法為 SSL/TLS 安全通道建立信任關係
解法辦法

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;<=加入
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;<=加入
參考來源
[faq]解決C#呼叫有ssl憑證問題的網站出現遠端憑證是無效的錯誤問題
C# HttpReques 基礎連接已關閉: 無法為 SSL/TLS 安全通道建立信任關係 強制跳過 TLS驗證
C# 連線 HTTPS 網站發生驗證失敗導致基礎連接已關閉

2020年1月16日 星期四

未分類 Blazor 好用Component

Blazor 已經跟Angular一樣都是用Component
雖然jQuery部分還是可以是使用
但jQuery UI部分在使用上可能無法那麼順利
所以目前可能真的要走向Blazor Component方式
以下目前覺得好用的Component
如果您有不錯的可以提供謝謝

AutoComplete
Typeahead

DatePicker
BlazorDateRangePicker

Verification(自訂驗證比設定在model class來的彈性)
Integrating FluentValidation with Blazor

Pagination(我是參考以下三篇做成一個自己需要的Pagination Component)
Blazor.Pagination
Building Blazor shared pager component
8 - Blazor - Pagination with ASP.NET Core, Entity Framework Core and Blazor

Sortable(參考下篇應該就能做出了)
Exploring Blazor by Making An HTML Table Sortable in .NET Core

Third Party(可能需要付費)
Telerik
Syncfusion
Radzen
matblazor.com
Blazorise
如果有需要可以自行決定


參考來源
ASP.NET Core Blazor JavaScript interop

2019年12月30日 星期一

.Net Core Scaffold-DbContext Build failed.

承接問題4.Net Core 如何採用DB First
剛發現Build failed
如過自行修改了Scaffold-DbContext所產生的class很容易遇到
目前我是三層式架構所以有多專案在一個方案裡面
測試了兩三次
先將其他專案都移除後再執行Scaffold-DbContext
就可以順利產生class之後再將其他專案加回來
有更好辦法也可提供

2023-10-31補充更新
model的專案設定成預設專案後再執行即可

2019年12月20日 星期五

.Net Core 3.0以上版本分頁問題

今天寫了Blazor的Sample專案測試到了分頁時
 stafflist = await this._staffService.GetAll().Skip(1).Take(1).ToListAsync();

出現了下列錯誤
SqlException: 接近 'OFFSET' 之處的語法不正確。 FETCH 陳述式中的選項 NEXT 使用方式無效。 context
後來找到一堆方法
services.AddDbContext<CoreSampleContext>(options => options.UseSqlServer(ConnectionString));
改成
services.AddDbContext<CoreSampleContext>(options => options.UseSqlServer(ConnectionString,build =>build.UseRowNumberForPaging()));
很好一樣出錯,後來找到了原因,目前使用的資料庫是SQL Server 2008R2
微軟提到了已移除 UseRowNumberForPaging 目前可能只有兩條路
1.升級SQL Server
2.降低.Net Core版本
3.Dapper或其他可直接下SQL語法

2019年12月9日 星期一

.Net Core 如何採用DB First

必須安裝下列安裝(套件管理主控台)
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design -Version 1.1.6
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.0
Install-Package Microsoft.EntityFrameworkCore.SqlServer 
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design  
Install-Package Microsoft.EntityFrameworkCore.Tools  
//第一次乾淨時
Scaffold-DbContext "Server=192.168.0.1;Database=Sample;user id=sa;password=1234567;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Project sample.model
//有更新時
Scaffold-DbContext "Server=192.168.0.1;Database=Sample;user id=sa;password=1234567;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  -Project sample.model -Force
//需與原資料庫同檔名時
Scaffold-DbContext "Server=192.168.0.1;Database=Sample;user id=sa;password=1234567;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Project sample.model   -UseDatabaseNames
常遇到Build failed或是直接沒反應
方法1.將專案設為起始專案
方法2.移除其他專案再執行在加回其他專案
方法3.檢查是否其他地方有錯誤
參考來源
ASP.NET Core 3.0 如何使用 Database First
“Build failed” on Database First Scaffold-DbContext How to prevent Entity Framework Core 2.0 from Renaming Tables and Columns in Generated Classes (Database First)
Scaffold-DbContext

2019年11月21日 星期四

.Net Core 如何發佈到IIS

.Net Core最有價值的就是跨平台
不用再依附於.net framework 發佈時
以下依需求選擇
1.可選擇.net core版本
2.與Framework相依或獨立
3.發佈到linux osx win

發佈到IIS上其實跟原本設定的方式都一樣
但須特別安裝 .NET Core RunTime.Net Core Windows Server Hosting

發佈到linux可參考官網Linux 上 .NET Core 的必要條件
發佈到Max可參考官網macOS 上 .NET Core 的先決條件

如果程式發佈是winX64時在IIS上啟用32位元則要關掉
否則可能出現,HTTP Error 500.32 - ANCM Failed to Load dll 的錯誤

參考來源
IIS - 運行 ASP.NET Core 網站
[ASP.net Core] 部署 ASP.net Core 到 IIS 個人踩雷合集

.Net Core Visual Studio如何安裝JS/CSS套件問題

開了一個.Net Core 3.0專案後,
習慣性的想要安裝常用必備的套件打開Nugut套件管理員 > 套件管理主控台,
然後貼上常用的語法按Enter跑完了!!
發現疑!!怎麼js都沒安裝,
看了一下內容完全沒有任何.js的文件進來,
找了一篇文章如下參考有寫到可使用Bower,
找一下Bower發現暗黑執行序有文章寫到Bower被放生了,
多了一個Library Manager,使用起來是蠻簡單的。
專案上右鍵 > 加入 > 用戶端程式庫 > 提供者、程式庫輸入條件安裝即可

參考來源

2019年11月18日 星期一

.Net Core 3.0 WinForm 無設計畫面

看完了ASP.NET Core 值得學嗎?發覺.net Core的確有學習的必要,
於是先用winform來試試,沒想到發現居然沒設計畫面,
在網路上找到已經有擴充套件及影片C# Tutorial - NET Core 3.0 WinForms Designer | FoxLearn
套件頁面:WINDOWS FORMS: .NET CORE WINDOWS FORMS DESIGNER
使用方法:下載安裝套件,重開VS2019即可
目前尚未遇到有出問題
參考來源
C# Tutorial - NET Core 3.0 WinForms Designer | FoxLearn

2019年9月26日 星期四

c# 日期區間小撇步

單一日期查詢只需比對大於and小於
但若日期開兩個欄位,
一個是日期起,
一個是日期迄,
如何查詢區間內的資料?

舉例:
想知道2019-09-01到2019-09-30之前有哪些人在職
稍微畫個圖後有了靈感
((到職日期 <= 2019-09-30 && 離職日期 >= 2019-09-01)  || (離職日期 =null ))
會就在這個區間


2018年10月25日 星期四

c# string.Format、StringBuilder.AppendFormat 輸入字串格式不正確

今天早上發生了一個錯誤"輸入字串格式不正確"
程式從頭檢查到尾有字串相加、string.Format、StringBuilder.AppendFormat
所有都檢查過了{0},{1}...也都詳細檢查過了該帶入的都帶入了
後來程式上沒問題就將目標轉到文章上去
發現了其中一筆資料中內容文字{X}有這樣的字元出現
然後檢查了程式剛好是sb.AppendFormat(item.context);
所以{X}部分被當作要取代的索引然後就錯了
最簡單解法改為sb.Append (item.content);
單純加入文字

2018年10月24日 星期三

未分類 Blazor 相關網站整理

之前學過Angular但因公司架構關係所以一直無法使用,
當然久未使用就會漸漸淡忘掉,
直到前陣子在FB上看到保哥發表了有關Blazor文章,
一整個覺得這東西必須要學起來阿,
當然目前還在測試階段但既然可以用C#+razor來寫學習就不需要像Angulars那麼複雜,
以下是目前所看到的網站整理,
未來有開始寫時在記錄程式。
Blazor官網
ASP.NET Core – CRUD Using Blazor And Entity Framework Core
Creating an SPA Using Razor Pages With Blazor
S207 - Blazor: Modern Web development with .NET and WebAssembly - Daniel Roth