2020年11月6日 星期五

MongoDB 07.createIndex

無論是關聯式資料庫或是NoSQL
Index都相當重要
尤其在資料量大時特別顯著
MongoDB如何建立Index
目前使用Robo 3T來連線,右鍵資料庫 > Open Shell
語法如下
降冪-1升冪 1
1.單一欄位
db.collectionName.createIndex({"age":1})
2.多重欄位
db.collectionName.createIndex({"name":-1,"age":1})
也可以使用Robo 3T > Collection上右鍵 > Add Index
經過測試百萬筆資料後有Index跟無Index速度真的差很多
參考來源
db.collection.createIndex()
MongoDB 索引

MongoDB 06.C# Filter

查詢時基本上都會需要過濾條件
目前大概會使用到的如下
var builders = Builders.Filter;//建立查詢 
var filter = builders.Eq("age", 20);//過濾條件
var query = collection.Find(filter).ToList();//抓資料
條件如下
Eq等於
Ne不等於
Gt大於
Gte大於等於
Lt小於
Lte小於等於
Regex Like
In 存在裡面的
Nin 不存在裡面的
但通常條件不會這麼簡單
情境1.找年齡20~30歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
情境2.找年齡20~30歲或年齡50~60歲
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
情境3.找年齡20~30歲或年齡50~60歲且名字有林的
var filter = builders.Gte("age",20)  & builders.Lte("age", 30);
filter = filter | builders.Gte("age", 50) & builders.Lte("age", 60);
filter = filter & builders.Regex("Name", "林");
情境4.找年齡50、60、70歲
int[] agelist = new[] { 50, 60, 70 };
var filter = builders.In(x => x.age, agelist);
參考來源
Mongo C# driver - Building filter dynamically with nesting MongoDB C# Driver - Fastest way to perform an “IN” query on _id

2020年10月30日 星期五

MongoDB 05.備份與還原

1.前言
在網路上找就會有許多備份及還原的文章
mongodump
mongorestore
mongoexport
mongoimport
在命令提示字元中照貼語法都出現在列錯誤
'mongodump' 不是內部或外部命令、可執行的程式或批次檔。
後來檢查才發現根本沒這些執行檔阿
瀏覽官方文件,內容如下才發現原來我安裝的是目前最新的4.4版的,然後工具從4.4版後不包含在原本的裡面了
Starting with MongoDB 4.4, mongodump is now released separately from the MongoDB Server and uses its own versioning, with an initial version of 100.0.0. Previously, mongodump was released alongside the MongoDB Server and used matching versioning.
至官網下載MongoDB Database Tools
2.備份
-h: MongoDB連線IP或資訊
-port: Port
-d: 資料庫名稱
-o: 備份路徑資料夾
-u: 登入帳號
-p: 登入密碼
mongodump -h {host} -port {port} -d {yourdbname} -o {outputfloder} -u {username}-p {password}
mongodump -h localhost -port 27017 -d Happen -o d:\mongodb\bak -u Happen -p 7533967
完成後會在d:\mongodb\bak\Happen裡找到備份
3.還原
-d: 資料庫名稱
-u: 登入帳號
-p: 登入密碼
--drop: 以存在資料庫刪除原有的(注意)
mongorestore -d {yourdbname} --drop -o {outputfloder} -u {username}-p {password}
mongorestore -d Happen --droup  d:/mongodb/bak/happen -u Happen -p 7533967
參考來源
mongodump
[技術研究] 如何從遠端匯出MongoDB
5.備份及還原MongoDB(mongodump , mongorestore)

2020年10月29日 星期四

MongoDB 04.建立登入驗證

1.停用MongoDB Server服務
2.建立登入帳密
開啟命令提示字元,至安裝Mongodb目錄下輸入
mongo
>use yourdbname
>switched to db yourdbname
>db.createUser(
{
    user: "username",
    pwd: "password",
    roles: [ { role: "readWrite", db: "yourdbname" } ]
})
>Successfully added....
>db.auth('username','password')
1完成代表可以登入
0登入失敗
登入成功表示帳密無誤
3.設定mongod.cfg 找到
#security: 
改成
security:
    authorization: enabled


4.啟用MongoDB Server服務,寫程式即可使用上面的帳密登入,記得readWrite權限要開才能讀寫資料庫
5.Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1
檢查一下連線字串是否正確,或是權限是否正確
mongodb://username:password@localhost:27017/dbname
PS也可直接使用工具建立帳密
參考來源
為 MongoDB 加上驗證機制
mongodb設定使用者名稱和密碼並用node連線
Built-In Roles Configuring MongoDB authentication

MongoDB 03.使用.Net Core CRUD

1.如何在.Net Core上安裝MongoDB,完全不用擔心直接有套件可以支援MongoDB真是太佛心下列安裝方法均可
a.MongoDB官網
b.Nuget
2.如何使用
a.建立Model
    public class StaffInfo
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
       
        public string Name { get; set; }

        public int age { get; set; }

         
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime birthday { get; set; }

        public string remark { get; set; }

        public int likenumber { get; set; }
    }
b.宣告Interface
    public interface IStaffInfoService
    {     
        List Get();

        void Insert( StaffInfo model);     

        void Update( StaffInfo  model);

        void Delete(StaffInfo model);
    }
c.建立Service寫CURD
    public class StaffInfoService : IStaffInfoService
    {
        private readonly IMongoCollection _staffinfo;

        public StaffInfoService()
        {
            var client = new MongoClient("mongodb://localhost:27017");
            //var client = new MongoClient("mongodb://{username}:{password}@{host}:{port}/{Database}")
            var database = client.GetDatabase("dbname");

            _staffinfo = database.GetCollection("tablename");
        }

        public void Delete(StaffInfo model)
        {
            _staffinfo.DeleteOne(x => x.Id == model.Id);
        }

        public List Get()
        {
            return _staffinfo.Find(StaffInfo => true).ToList();
        }

        public void Insert(StaffInfo model)
        {
            _staffinfo.InsertOne(model);
        }

        public void Update(StaffInfo model)
        {
            _staffinfo.ReplaceOne(x => x.Id == model.Id, model);
        }
    }
d.DI注入即可使用
參考來源
使用 ASP.NET Core 與 MongoDB 建立 Web API

2020年10月28日 星期三

MongoDB 02.開啟對外連線

剛安裝完成MongoDB後使用Robo3T連本機是沒問題的
但如果遠端要連的話會跳出錯誤
在安裝目錄下mongod.cfg 原本
# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1
修改為以下為不限制
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
修改為以下為開放本機及192.168.1.100
# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1 ,192.168.1.100
以上步驟修改完成後記得至服務重起MongoDB Server才會有效
參考來源
MongoDB 安裝完成後,開啟對外連線

MongoDB 01.安裝

一、MongoDB安裝
1.至官網下載
2.安裝點選剛剛的MSI檔基本上下一步到底,data log資料夾可依需求選擇,Install MongoDB Compass不要勾(參考網站內有指出勾選會卡住)
3.windows服務看MongoDB Server(MongoDB)有沒有執行中 4.開啟命令提示字元至剛剛安裝的路徑例如我是
cd C:\Program Files\MongoDB\Server\4.4\bin
輸入以下
mongod --version
有出現就安裝成功
db version v4.4.1
Build Info: {
    "version": "4.4.1",
    "gitVersion": "xxxx",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "windows",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}
5.4.4.1需Windows 10 or server 2016 所以如果下以下的可以使用4.2.10版
6.4.0.20版後安裝時可指定data跟log位置,之前版本可能要網路上找下指令方式
二、連線工具
1.Robomongo - Robo3T
2.下載Simple GUI for beginners 有免安裝的Download portable version for Windows 64-bit解壓後執行robo3t.exe即可使用
3.執行robo3t.exe > File > Connect > Create > Test 看是否建立成功
參考來源
Day17 - MongoDB 安裝設定
MongoDB - 詳細到讓人牙起來的安裝教學
Windows MongoDB 下載與安裝教學
MongoDB 使用Robo 3T建立資料庫

未分類 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