2024年1月18日 星期四

在 ASP.NET Core 中建立 gRPC 用戶端與伺服器

 GRPC 是什麼?  有別於傳統的client 和 server 端的連線,而是持續性且高效能的連線, 連線上的架構是HTTP2 協定,使用Protocol Buffers 作為介面描述語言,連線模式,可以1 (SERVER) 對多 (CLIENT),也可雙向溝通,而一般REST 連線只能作到單向構通

一、 建立GRPC的前置作業

先安裝GRPC的專案, 如果畫面上沒有出現asp.net Core gRPC的服務時,請搜尋GRPC













選擇asp.net Core gRPC服務























按下一步,就完成了…   建立GRPC Server端

二、建立GRPC Server





















Protos/greet.proto:會定義 `Greeter` gRPC,並會用來產生 gRPC 伺服器協定

以下是範例:  


syntax = "proto3";

 option csharp_namespace = "GrpcService1";

 package greet;

 

// server的名稱為 Greeter

service Greeter {

  // Sends a greeting

  rpc SayHello (HelloRequest) returns (HelloReply);

}

 

// The request 參數 name

message HelloRequest {

  string name = 1;

}

 // The response 回傳 message 

message HelloReply {

  string message = 1;

} 

三、建立GRPC Client


這用於client 與server端 的協定,所以clint端也需要相同的.proto, 所以從server端的 Protos/greet.proto copy一份到client端 Protos路徑下













以下是client的內容 ,但與server端略有不同,

選擇.proto 按下右鍵,在 gprc stub Classes 選擇 client Only



syntax = "proto3";

 option csharp_namespace = "GrpcGreeterClient"; //要自已設定clientOnly

 package greet;

 

// server端的server名稱一致

service Greeter {

  // Sends a greeting

  rpc SayHello (HelloRequest) returns (HelloReply);

}

 

// The request message containing the user's name.

message HelloRequest {

  string name = 1;

}

 

// The response message containing the greetings.

message HelloReply {

  string message = 1;

}


四、執行結果

server 端的執行檔




















client 端的執行檔







2023年7月18日 星期二

VUE2 如何監聽DIV中的Scroll 事件

最近的案子是PO要求UI的DIV 要有捲軸,而且要使用者拉Scroll拉到底,才會讓下面checkbox 可以讓使用打勾同意,目的就是要讓使用者強迫看完整篇文章後,才能關閉這視窗… 呵呵,好喔,我們再看vue要如何做到

一、建立DIV 要有捲軸的畫面

 要加上@scroll就可以監聽div內的schroll事件了喔~ 對就是這麼簡單!!!!,如果網有眼尖發現為何有@@小老鼠,因為我用asp.net MVC 所以要再多一個@

<div id="PupupWindow" class="dialogbackground">

    <div class="PupupContent">

        <div class="panel panel-info">

            <div class="panel-heading popupsubject">

            </div>

            <div class="panel-body">

                <div contenteditable='true' class="scroll-div" @@scroll="handleBlScroll">

                    HELLO TEST ABCDE1<br />

                    HELLO TEST ABCDE2<br />

                    HELLO TEST ABCDE3<br />

                    HELLO TEST ABCDE4<br />

                    HELLO TEST ABCDE5<br />

                    HELLO TEST ABCDE6<br />

                    HELLO TEST ABCDE7<br />

                    HELLO TEST ABCDE8<br />

                    HELLO TEST ABCDE9<br />

                    HELLO TEST ABCDE10<br />

                    HELLO TEST ABCDE11<br />

                    HELLO TEST ABCDE12<br />

                    HELLO TEST ABCDE13<br />

                    HELLO TEST ABCDE14<br />

                    HELLO TEST ABCDE15<br />

                    HELLO TEST ABCDE16<br />

                </div>                            

            </div>

                <div class="panel-footer text-center">

                    <input type="checkbox" class="form-control" v-bind:disabled="!checkAgree" />同意

                    <button id="popup-check-button" class="btn btn-primary btn-lg">確認</button>

                </div>

            </div>

    </div>

</div>

 

二、建立監聽的事件

Index.Js

 

var DefaultPage = new Vue({

    el: '#app',

    filters: {  },

    mixins: [Global],

    data: { checkAgree: false },

methods: {

  handleBlScroll(e) {          

            if (e.srcElement.scrollTop + e.srcElement.offsetHeight >= e.srcElement.scrollHeight) {

// 碰到schroll的底

                this.checkAgree = true;

            } else {

                this.checkAgree = false;

            }

        }

})


測試畫面如下:








 

2023年6月5日 星期一

c#幾個常用的匯入方式和元件

    各位有發現EXCEL的格式有分為.CSV.XLS .XLXS 等,但作法不儘相同,所以幫各位整理起來,希望各位網友可以善加利用。

一、CLOSEXML 套件 目前不支援.CSV.XLS)


匯入excel檔案,並轉換是物件List

        public List<T> ReadExcelToList<T>(string fileName, string sheetName)

        {

            List<T> dataList = new List<T>();

            Type typeObject = typeof(T);

            using (XLWorkbook work = new XLWorkbook(fileName))

            {

                var workSheet = work.Worksheets.Where(q => q.Name == sheetName).First();

                var properties = typeObject.GetProperties();

                var colums = workSheet.FirstRow().Cells().Select((v, i) => new { Value = v.Value, Index = i + 1 });

                foreach (IXLRow row in workSheet.RowsUsed().Skip(1))

                {

                    T obj = (T)Activator.CreateInstance(typeObject); 

                    foreach (var prop in properties)

                    {

                        int colIndex = colums.SingleOrDefault(c => c.Value.ToString() == prop.Name.ToString()).Index;

                        var val = row.Cell(colIndex).Value;

                        var type = prop.PropertyType;

                        prop.SetValue(obj, Convert.ChangeType(val, type));

                    } 

                    dataList.Add(obj);

                }

            } 

            return dataList;

        }



二、NPOI 支援.XLS、.XLSX

    public List<T> ReadExcelToListForXLS<T>(string fileName)

        {

            try

            {

                List<T> dataList = new List<T>();

                Type typeObject = typeof(T); 

                IWorkbook workbook = null;  //新建IWorkbook物件

                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                workbook = new HSSFWorkbook(fileStream);  //xlsx資料讀入workbook

                ISheet sheet = workbook.GetSheetAt(0);  //獲取第一個工作表 

                // 建立一個空的 List<string> 用來儲存轉換後的資料

                var properties = typeObject.GetProperties();

                var colums = sheet.GetRow(0).Cells.Select((v, i) => new { Value = v.StringCellValue, Index = i });

                IRow row; //新建當前工作表行資料

                for (int i = 1; i <= sheet.LastRowNum + 1; i++)  //對工作表每一行

                {

                    row = sheet.GetRow(i);   //row讀入第i行資料

                    if (row != null)

                    {

                        T obj = (T)Activator.CreateInstance(typeObject); 

                        foreach (var prop in properties)

                        {

                            int colIndex = colums.SingleOrDefault(c => c.Value.ToString() == prop.Name.ToString()).Index;

                            var val = row.GetCell(colIndex);

                            var type = prop.PropertyType;

                            prop.SetValue(obj, Convert.ChangeType(val?.ToString(), type));

                        }

                        dataList.Add(obj);

                    }

                } 

                return dataList;

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }



三、CSV的匯入

  public List<T> ReadExcelToListForCSV<T>(string fileName)

        {

            try

            {

                List<T> dataList = new List<T>();

                Type typeObject = typeof(T);

                var contents = File.ReadAllText(fileName, Encoding.GetEncoding("Big5")).Split('\n');

                var csv = from line in contents

                          select line.Split(',').ToArray();

 

                var properties = typeObject.GetProperties();

                var colums = csv.ToList().First().Select((v, i) => new { Value = v.ToString().Replace("\r", string.Empty), Index = i });

                 foreach (var row in csv.Skip(1).ToList())

                {

                    T obj = (T)Activator.CreateInstance(typeObject); 

                    foreach (var prop in properties)

                    {

                        int colIndex = colums.SingleOrDefault(c => c.Value.ToString() == prop.Name.ToString()).Index;

                        var val = row[colIndex];

                        var type = prop.PropertyType;

                        prop.SetValue(obj, Convert.ChangeType(val?.ToString(), type));

                    }

                    dataList.Add(obj);

                } 

                return dataList;

            }

            catch (Exception ex)

            {

                throw ex;

            }

        }