[Asp.Net Core] Blazor Server Side 擴展用途 - 配合CEF來製作帶瀏覽器核心的客戶端軟體 (二) 可運行版本

来源:https://www.cnblogs.com/zhgangxuan/archive/2020/05/22/asp_net_core_blazor_server_side_cef_winforms_2.html
-Advertisement-
Play Games

前言 大概3個星期之前立項, 要做一個 CEF+Blazor+WinForms 三合一到同一個進程的客戶端模板. 這個東西在五一的時候做出了原型, 然後慢慢修正, 在5天之前就上傳到github了. 地址 : https://github.com/BlazorPlus/BlazorCefApp 但是 ...


前言

大概3個星期之前立項, 要做一個 CEF+Blazor+WinForms 三合一到同一個進程的客戶端模板. 

這個東西在五一的時候做出了原型, 然後慢慢修正, 在5天之前就上傳到github了. 

地址 : https://github.com/BlazorPlus/BlazorCefApp 

但是一直在忙各種東西, 沒有時間寫博客. 

 

情況

情況是這麼一個情況 , 這個東西能運行, 夠用. 也寫了7個例子.  離當初的目標還有一些距離. 需要更多的時間去填坑. 

CEF方面, 是按需包裝, 沒有用到的功能是沒處理的.  不過按照原先設想, 大部分人都不會有去定製這個CEF的需要.

 

測試

看這篇博文的網友, 如果不想從github下載編譯, 從 http://opensource.spotify.com/ 另行下載 CEF 的資源包, 

可以直接在微雲上下載已經編譯好的版本https://share.weiyun.com/oibpnIro

 

項目模板

 

 

 

如圖, 這是一個標準的 Blazor server side 工程.  有 Program.cs , 有 Startup.cs , 有 Shared/Pages,  有 wwwroot

其中引用的包是 CefLibCore , 源代碼在  https://github.com/BlazorPlus/CefLite , 這個包里有CefLiteCore.dll, 存放著共用的代碼邏輯

 

Program.cs

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

using CefLite;

namespace BlazorCefApp
{
    public class Program
    {

        [STAThread]
        static public void Main(string[] args)
        {
            //TODO:Change the project type to "Windows Application" to hide the console
            //If you start the app via Visual Studio , the VS Command Prompt will always show
            CefWin.PrintDebugInformation = true;  //show debug information in console

            CefWin.ApplicationTitle = "MyBlazorApp"; //as the Default Title

            CefWin.ShowSplashScreen("wwwroot/splash.jpg");  //or show System.Drawing.Image from embedded resource 

            if (CefWin.ActivateExistingApp())   // Optional, only allow one instance running
            {
                Console.WriteLine("Anoter instance is running , So this instance quit.");
                return;
            }

            //CefWin.SettingAutoSetUserDataStoragePath = false;
            //CefWin.SettingAutoSetCacheStoragePath = false;

            CefWin.SetEnableHighDPISupport();

            CefWin.SearchLibCefSubPathList.Add("chromium");         // search ./chromium/ for libcef.dll
            CefInitState initState = CefWin.SearchAndInitialize();

            if (initState != CefInitState.Initialized)
            {
                if (initState == CefInitState.Failed)
                {
                    System.Windows.Forms.MessageBox.Show("Failed to start application\r\nCheck the github page about how to deploy the libcef.dll", "Error"
                       , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                return;
            }

            using IHost host = CreateHostBuilder(args).Build();
            try
            {
                host.Start();
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
                System.Windows.Forms.MessageBox.Show("Failed to start service. Please try again. \r\n" + x.Message, "Error"
                     , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                CefWin.CefShutdown();
                return;
            }

            CefWin.ApplicationHost = host;
            CefWin.ApplicationTask = host.WaitForShutdownAsync(CefWin.ApplicationCTS.Token);

            ShowMainForm();

            CefWin.RunApplication();

        }

        static void ShowMainForm()
        {
            string startUrl = aspnetcoreUrls.Split(';')[0];
            DefaultBrowserForm form = CefWin.OpenBrowser(startUrl);
            form.Width = 1120;
            form.Height = 777;
            form.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            //CefWin.CenterForm(form);
            //form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
        }

        static string aspnetcoreUrls = "http://127.12.34.56:7890";
        //static string aspnetcoreUrls = "http://127.12.34.56:7890;https://127.12.34.56:7891";
        //static string aspnetcoreUrls = "https://127.12.34.56:7891";       //Force to SSL , not so useful , just a test
        //static string aspnetcoreUrls = CefWin.MakeFixedLocalHostUrl();    //make fixed url by user name , so each user can open 1 instance
        //static string aspnetcoreUrls = CefWin.MakeRandomLocalHostUrl();   //random url allow multiple instance of this app , but cookie/localStorage will lost when open app again.


        static public IHostBuilder CreateHostBuilder(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args);

            builder.ConfigureWebHostDefaults(webBuilder =>
            {
                Console.WriteLine("aspnetcoreUrls : " + aspnetcoreUrls);
                webBuilder.UseUrls(aspnetcoreUrls);
                webBuilder.UseStartup<Startup>();
            });

            return builder;
        }

    }
}

 

這是程式入口. 它幹了挺多東西的: 

 

CefWin.PrintDebugInformation = true;

列印一些調試信息到 Console 中去.   如果項目編譯成 Console , 在啟動的時候就會顯示控制台, 能看到一些調試信息. 

 

 

 

 

 

 

CefWin.ApplicationTitle = "MyBlazorApp"; //as the Default Title

定義預設標題 , 目前的瀏覽器視窗使用這個標題.  還沒有自動顯示網頁的document.title 

 

CefWin.ShowSplashScreen("wwwroot/splash.jpg");

顯示一個啟動頁面. 自己換掉圖片就可以定製了. 

 

 

if (CefWin.ActivateExistingApp())   // Optional, only allow one instance running
{
    Console.WriteLine("Anoter instance is running , So this instance quit.");
    return;
}

監測程式是否已經在運行,  如果是的話,  那麼就激活正在運行得程式, 自己退出.  

如果想允許程式有多例執行,  那麼就不要這段代碼好了.   但下麵的  static string aspnetcoreUrls 需要制定為動態變化的地址, 以免埠衝突. 

 

//CefWin.SettingAutoSetUserDataStoragePath = false;
//CefWin.SettingAutoSetCacheStoragePath = false;
CefWin.SetEnableHighDPISupport();

一些選項 ,  以後會增加越來越多的定製化選項.     預設情況下,  瀏覽器數據會保存在磁碟里的. 

詳細看  https://github.com/BlazorPlus/CefLite/blob/master/CefLite/CefWin.cs  關於 string folder; 那一段:

 

 

CefWin.SearchLibCefSubPathList.Add("chromium");         // search ./chromium/ for libcef.dll
CefInitState initState = CefWin.SearchAndInitialize();

搜索和啟動CEF  ,  搜索方法是在指定的子目錄 , 代碼中是 "chromium" 里, 尋找 libcef.dll , 找到就載入. 

 

 

 

if (initState != CefInitState.Initialized)
{
    if (initState == CefInitState.Failed)
    {
        System.Windows.Forms.MessageBox.Show("Failed to start application\r\nCheck the github page about how to deploy the libcef.dll", "Error"
            , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
    }
    return;
}

如果狀態不是 Initialized 初始化成功,  那麼有可能是 Failed , 找不到 libcef.dll 或者其他問題,  例如這個exe是32位的,  但是下載的libcef.dll是64位的...

 

using IHost host = CreateHostBuilder(args).Build();
try
{
    host.Start();
}
catch (Exception x)
{
    Console.WriteLine(x);
    System.Windows.Forms.MessageBox.Show("Failed to start service. Please try again. \r\n" + x.Message, "Error"
            , System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
    CefWin.CefShutdown();
    return;
}

啟動 Asp.Net Core , Blazor server side 

如果啟動失敗, 最有可能是IP埠衝突了. 

 

CefWin.ApplicationHost = host;
CefWin.ApplicationTask = host.WaitForShutdownAsync(CefWin.ApplicationCTS.Token);

ShowMainForm();

CefWin.RunApplication();

啟動 WinForms , 打開預設瀏覽器, 指向blazor首頁

 

 

static void ShowMainForm()
{
    string startUrl = aspnetcoreUrls.Split(';')[0];
    DefaultBrowserForm form = CefWin.OpenBrowser(startUrl);
    form.Width = 1120;
    form.Height = 777;
    form.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    //CefWin.CenterForm(form);
    //form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
}

這是啟動這個MainForm的細節.  開發者可以定製一下. 

 


 

 

Startup.cs  

這個文件很普通, 就是標準的做法便可.  唯一要處理的是註釋掉 app.UseHttpsRedirection() 因為是本地URL無需ssl . 

 

MainLayout.razor

 這文件已經被清空了. 

 

因為本例子是 單頁應用程式 ,  不需要任何共同的Layout 

 

Index.razor 首頁

@page "/"

<div style="text-align:center;padding-top:18px;">
    <h2>BlazorCefApp!</h2>
    <p>
        <a href="https://github.com/BlazorPlus/BlazorCefApp" target="_blank">https://github.com/BlazorPlus/BlazorCefApp</a>
        <br />
        Run Blazor server side as a window application.
        <br />
        <button class="btn btn-info" style="width:100px" @onclick="()=>BlazorSession.Current.ShowDevTools()">DevTools</button>
        <button class="btn btn-info" style="width:100px" onclick="window.close()">JSClose</button>
        <button class="btn btn-info" style="width:100px" @onclick="()=>BlazorSession.Current.CloseBrowser()">CloseForm</button>
        <button class="btn btn-info" style="width:100px" @onclick="()=>CefLite.CefWin.QuitWindowsEventLoop()">CefQuit</button>
        @*<button class="btn btn-info" style="width:100px" @onclick="()=>System.Windows.Forms.Application.Exit()">AppExit</button>*@
    </p>
    <hr />
</div>

@{
    RenderFragment RenderItem<T>(string title, string comment)
        where T : ComponentBase
        =>
    @<div class="main-menu-item" @onclick="() => { BlazorSession.Current.ShowDialog<T>(null); }">
        <div class="main-menu-item-title">@title</div>
        <div class="main-menu-item-comment">@comment</div>
    </div>
    ;
}

<div class="main-menu" style="display:flex;flex-direction:row;flex-wrap:wrap;">

    @(RenderItem<Demos.Notepad.Notepad>("Notepad","OpenFileDialog and SaveFileDialog"))
    @(RenderItem<Demos.RegView.RegView>("RegView", "Local Registry and TreeView"))
    @(RenderItem<Demos.ComPort.ComPort>("ComPort", "Serial Port for Hardware"))
    @(RenderItem<Demos.ExeInfo.ExeInfo>("ExeInfo", "Show more useful information"))
    @(RenderItem<Demos.ProcList.ProcList>("ProcList", "Local Process GridView"))
    @(RenderItem<Demos.PlayMp4.PlayMp4>("PlayMp4", "ActiveX MediaPlayer"))
    @(RenderItem<Demos.MsTscAx.MsTscAx>("MsTscAx", "ActiveX RemoteDesktop"))

</div>

 

如文章一開始的截圖.  這個頁面的主要作用有 

  1.  提供一個 DevTools 按鈕, 讓開發者可以打開調試工具.  開發者可以自行寫代碼實現不同的方式打開DevTools, 例如熱鍵. 
  2. 提供3種(4種)關閉視窗退出程式的方案.  看情況自己使用. 
  3. 引入 7 種 Demo  ,  Demos.Notepad.Notepad , ...... 

所有的 demo 都是以 dialog 的方式彈出.  不是URL跳轉. 

 

Notepad 例子

這裡分析一下 Notepad 的做法 

 

HTML:

@inherits DemoDialogBase

@inject BlazorSession bses

<div class="dialog-content-full" @onkeypress="Dialog_KeyPress">
    <div style="display:flex;flex-direction:row;">
        <button onclick="history.back()">Back</button>
        <button @onclick="ShowOpenFileDialog">OpenFileDialog</button>
        <button @onclick="ShowSaveFileDialog">SaveFileDialog</button>
        <div style="flex:99999;text-align:center;padding:3px;">
            @(currentFilePath==null?"Untitled":System.IO.Path.GetFileName(currentFilePath))
            <span style="color:red">@(originalTextCode != currentTextCode?"*":"")</span>
        </div>
        @if (currentFilePath != null)
        {
            <button @onclick="ExploreCurrentFile">Explore</button>
        }
        <button @onclick="SaveCurrentFile">SaveNow(CTRL+S)</button>
    </div>
    <BlazorDomTree TagName="textarea" OnRootReady="textarea_ready" spellcheck="false" placeholder="Type text here.." style="width:100%;height:100%;overflow-y:scroll;resize:none" />
</div>

C# :

    string currentFilePath;
    string originalTextCode = "";
    string currentTextCode = "";

    PlusControl textarea;
    void textarea_ready(BlazorDomTree bdt)
    {
        textarea = bdt.Root;
        textarea.OnChanging(delegate
        {
            currentTextCode = textarea.Value;
            StateHasChanged();
        });
        textarea.SetFocus(1);
    }

    void WriteToFile(string filepath)
    {
        try
        {
            System.IO.File.WriteAllText(filepath, currentTextCode);
            originalTextCode = currentTextCode;
        }
        catch (Exception x)
        {
            bses.ConsoleError(x.ToString());
            bses.Alert("Error", x.Message);
        }
    }

    void ShowOpenFileDialog()
    {
        if (string.IsNullOrWhiteSpace(currentTextCode) || originalTextCode == currentTextCode)
        {
            ShowOpenFileDialogImpl();
            return;
        }

        bses.Confirm("Open", "Open another file without saving text?", (result) =>
        {
            if (result == true)
                ShowOpenFileDialogImpl();
            else
                textarea.SetFocus();
        });
    }

    void ShowOpenFileDialogImpl()
    {

        bses.RunBrowser(browser =>
        {
            var form = browser.FindForm();
            using (System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog())
            {
                if (currentFilePath != null)
                    dialog.FileName = currentFilePath;
                dialog.Filter = "Text Files|*.txt";
                var res = dialog.ShowDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                    return;

                bses.InvokeInRenderThread(delegate
                {
                    string txt;
                    string openfilepath = dialog.FileName;
                    try
                    {
                        txt = System.IO.File.ReadAllText(openfilepath);
                    }
                    catch (Exception x)
                    {
                        bses.ConsoleError(x.ToString());
                        bses.Alert("Error", x.Message);
                        return;
                    }

                    currentFilePath = openfilepath;
                    originalTextCode = currentTextCode = txt;
                    textarea.Value = txt;
                    textarea.SetFocus(1);
                    StateHasChanged();
                    bses.Toast("Load " + System.IO.Path.GetFileName(currentFilePath));
                });
            }
        });
    }
    void ShowSaveFileDialog()
    {
        bses.RunBrowser(browser =>
        {
            var form = browser.FindForm();
            using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
            {
                if (currentFilePath != null)
                    dialog.FileName = currentFilePath;
                dialog.Filter = "Text Files|*.txt";
                var res = dialog.ShowDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                    return;

                bses.InvokeInRenderThread(delegate
                {
                    string savefilepath = dialog.FileName;
                    try
                    {
                        WriteToFile(savefilepath);
                    }
                    catch (Exception x)
                    {
                        bses.ConsoleError(x.ToString());
                        bses.Alert("Error", x.Message);
                        return;
                    }

                    currentFilePath = savefilepath;
                    originalTextCode = currentTextCode;
                    textarea.SetFocus(1);
                    StateHasChanged();
                    bses.Toast("Save " + System.IO.Path.GetFileName(currentFilePath));
                });
            }
        });
    }
    void SaveCurrentFile()
    {
        if (currentFilePath == null)
            ShowSaveFileDialog();
        else
            WriteToFile(currentFilePath);
    }

    void ExploreCurrentFile()
    {
        System.Diagnostics.Process.Start("Explorer", "/select, \""+currentFilePath+"\"");
    }

    protected override void OnDialogCancel(string mode)
    {

        if (string.IsNullOrWhiteSpace(currentTextCode) || originalTextCode == currentTextCode)
        {
            Close();
            return;
        }

        bses.Confirm("Quit", "Quit without saving text?", (result) =>
        {
            if (result == true)
                Close();
            else
                textarea.SetFocus();
        });

    }

    void Dialog_KeyPress(KeyboardEventArgs args)
    {
        bses.ConsoleLog(System.Text.Json.JsonSerializer.Serialize(args));
        if (args.CtrlKey && args.Code == "KeyS")
        {
            SaveCurrentFile();
        }
    }

 

HTML 的代碼挺短的.  它實現了一個簡單佈局. 

 

需要留意的地方: 

  1. Back 按鈕的做法是  history.back() , 純 JavaScript 
  2. 如果是從文件讀來的, 或者已保存為文件, 那麼顯示文件名, 否則顯示 Untitled
  3. 有 originalTextCode != currentTextCode 的比較, 顯示文件已修改未保存的紅色星星
  4. 如果有文件名信息, 還提供了 ExploreCurrentFile 的便利 , 這也是與系統進行交互的例子
  5. 處理了 @onkeypress="Dialog_KeyPress" , 實現 CTRL+S 熱鍵
  6. 最下麵使用了 BlazorDomTree , 而不是用 InputTextArea , 因為需要在內容在被修改的過程中執行代碼, 而不是等到onchange觸發.

 現在回頭分析 C# 代碼: 

    string currentFilePath;
    string originalTextCode = "";
    string currentTextCode = "";

    PlusControl textarea;
    void textarea_ready(BlazorDomTree bdt)
    {
        textarea = bdt.Root;
        textarea.OnChanging(delegate
        {
            currentTextCode = textarea.Value;
            StateHasChanged();
        });
        textarea.SetFocus(1);
    }
BlazorDomTree , PlusControl 是 BlazorPlus 包里的功能.  用於像jQuery一樣寫代碼控制DOM




  呈現之後,  OnRootReady便會執行,  textarea=bdt.Root 便可得到這個 Element (<textarea/>) 的 C# 引用.  

  然後監聽 OnChanging 事件,  任何形式的改變, 例如打字, 黏貼, 刪除等等, 都會觸發, 保存內容到 currentTextCode , 並且執行 StateHasChanged()

  這個StateHasChanged 必須要手動調用,  因為這個事件不是 Blazor 的 EventCallback 編譯方式. 

 

 

    void ShowOpenFileDialogImpl()
    {

        bses.RunBrowser(browser =>
        {
            var form = browser.FindForm();
            using (System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog())
            {
                if (currentFilePath != null)
                    dialog.FileName = currentFilePath;
                dialog.Filter = "Text Files|*.txt";
                var res = dialog.ShowDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                    return;

                bses.InvokeInRenderThread(delegate
                {
                    string txt;
                    string openfilepath = dialog.FileName;
                    try
                    {
                        txt = System.IO.File.ReadAllText(openfilepath);
                    }
                    catch (Exception x)
                    {
                        bses.ConsoleError(x.ToString());
                        bses.Alert("Error", x.Message);
                        return;
                    }

                    currentFilePath = openfilepath;
                    originalTextCode = currentTextCode = txt;
                    textarea.Value = txt;
                    textarea.SetFocus(1);
                    StateHasChanged();
                    bses.Toast("Load " + System.IO.Path.GetFileName(currentFilePath));
                });
            }
        });
    }

使用 

       bses.RunBrowser(browser => {   ....  });

來實現兩個效果 : 

  1.  取得一個 ICefWinBrowser browser 對象, 使用 browser.FindForm() 來獲得 WinForm窗體
  2.  讓 delegate 代碼在 WinForms線程(主線程) 執行 ,  而不是 blazor 的  render thread 

在 WinForms線程執行時, 便可直接執行 WinForms 代碼了: 

            var form = browser.FindForm();
            using (System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog())
            {
                if (currentFilePath != null)
                    dialog.FileName = currentFilePath;
                dialog.Filter = "Text Files|*.txt";
                var res = dialog.ShowDialog(form);
                if (res != System.Windows.Forms.DialogResult.OK)
                    return;

 

 這是很標準的 SaveFileDialog 流程呀 

 獲取到要打開的文件路徑後,  要這麼乾 : 

                bses.InvokeInRenderThread(delegate
                {

這是從  WinForms 線程 , 切換回 Blazor 的 render 線程

這一點非常重要.  Blazor要活在自己的線程,  WinForms也要活在自己的線程,  兩者不能搞錯. 

 

處理 ESC/後退 命令 :

前面已經提及到,  BACK按鈕是執行 history.back() 的.  如果文件沒保存, 如何阻止返回呢? 

    protected override void OnDialogCancel(string mode)
    {

        if (string.IsNullOrWhiteSpace(currentTextCode) || originalTextCode == currentTextCode)
        {
            Close();
            return;
        }

        bses.Confirm("Quit", "Quit without saving text?", (result) =>
        {
            if (result == true)
                Close();
            else
                textarea.SetFocus();
        });

    }

這裡重寫了 DemoDialogBase.cs 的方法  OnDialogCancel

並且做出了合適的處理. 

 

如果是用戶關閉整個視窗呢?  

由於這隻是一個例子, 代碼需要足夠簡單, 所以沒有寫得太詳細. 

要解決這個問題, 需要具體工程具體解決. 

基本的原理是在 ShowMainForm 的時候就關聯  FormClosed 事件並處理. 

在 Notepad.razor 用 RunBrowser 的方式得到 form 並關聯 FormClosed 也可以. 

 

關於發佈方式

把程式發不成單一個exe , 一百多兆,  有好處也有壞處.  

實際上這是dotnet自己做的一個打包過程, 運行的時候, 是需要解壓的.. 這個解壓過程要好幾秒..

第二次運行第三次運行就快了. 

 

如果不把dotnetcore打包進去,  那麼客戶端又要另行安裝框架. 為部署增加了多一層麻煩. 

 

還是那一句, 有利有弊的東西, 要自行選擇. 

 

小結 

這個項目目前已經打通了 CEF , WinForms , Blazor (Asp.net core) 三者的關係, 

並且都在同一個進程, 同一個AppDomain里, 可以直接互相調用. 

 

 

後面有時間再繼續寫更多的例子.  

如有任何問題, 請加QQ群 

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 0. 前言 前言,暫時揮別NHibernate(雖然我突然發現這玩意還挺有意思的,不過看得人不多)。大步進入了有很多小伙伴向我安利的SQLSugar,嗯,我一直叫SugarSQL,好像是這個吧? 這是一個由國內開發者開發的ORM框架,是一個輕量級框架(最新版的sqlSugarCore大概只有290k ...
  • 需求:資料庫數據都是縱向的,呈現的時候要求是橫向(列轉行)同時看到行頭(行轉列)。 分析:很多報表呈現都要求要這樣顯示,用類是可以實現,但是代碼多,又需要建很多dto。發下Excel有轉置功能,但又不想牽扯Excel這一套組件。就使用DataTable來實現,代碼也不多。 先看看示例數據3列10行: ...
  • 同步版本示例: namespace SyncSample { class MyDownloadString { Stopwatch sw = new Stopwatch(); public void DoRun() { const int LargeNumber = 6000000; sw.Star ...
  • 在Linux上搭建基於開源技術的nuget私人保密倉庫 前言 在Linux上搭建nuget私人倉庫一直是一個老大難的問題,主要涉及到以下難點: nuget.org官方使用的Nuget.Server基於.NET Framework的ASP.NET,而不是ASP.NET Core,因此是Windows ...
  • 網上有很多Socket框架,但是我想,C#既然有Socket類,難道不是給人用的嗎? 寫了一個SocketServerHelper和SocketClientHelper,分別隻有5、6百行代碼,比不上大神寫的,和業務代碼耦合也比較重,但對新手非常友好,容易看懂。 支持返回值或回調,支持不定長度的數據 ...
  • 動手寫一個簡版 asp.net core Intro 之前看到過蔣金楠老師的一篇 200 行代碼帶你瞭解 asp.net core 框架,最近參考蔣老師和 Edison 的文章和代碼,結合自己對 asp.net core 的理解 ,最近自己寫了一個 MiniAspNetCore ,寫篇文章總結一下。 ...
  • 在微軟的Build 2020開發者大會中,微軟就正在成形的C#9.0的一些即將添加的主要特性進行了說明。 1.init屬性訪問器 對象初始化方式對於創建對象來說是一種非常靈活和可讀的格式,特別是對樹狀嵌入型對象的創建。簡單的例如 new Person { FirstName = "Scott", L ...
  • 作為一個老司機,怎能沒有自己的私人代碼倉庫? 前言 Github大家都熟悉。 除了開源的項目外,有時候,大家也會把自己或團隊、公司的項目傳到Github的私有倉庫里,把Github當成自己的私人Git Server。 但是,用Github會有一些問題: Github從國內訪問不是很穩定,有時候會很慢 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...