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的部分教學視頻