2021年7月13日 星期二

[Http] 分享Http flow

 分享很不錯的http 流程

轉至 : https://www.loggly.com/blog/http-status-code-diagram/





2020年4月20日 星期一

[Linq] groupby vs tolookup

簡單紀錄一下

主要差異在tolookup會馬上執行, groupby 會有延遲執行的特性

ref : https://stackoverflow.com/questions/43661143/use-selectmany-and-groupby

2020年4月6日 星期一

[Resharper] short cut

基本快捷鍵紀錄

  • ReSharper Shortcuts (at least you should know)
    • Quick Action: Alt+Enter
    • Refactor This... : Ctrl+Shift+R
    • Extract Method: Ctrl+R, M
    • Rename: Ctrl+R, R
    • Introduce Variable: Ctrl+R, V
    • Introduce Field: Ctrl+R, F
    • Introduce Parameter: Ctrl+R, P
    • Inline variable/field/parameter/method/class: Ctrl+R, I
    • Move file/folder/namespace/another type/instance method: Ctrl+R, O
    • List File Members: Alt+\
    • Search Everything: Ctrl+T
    • Extend Selection: Ctrl+W, Ctrl+W
    • Shrink Selection: Ctrl+Shift+W, Ctrl+Shift+W
    • Go to Previous Function: Alt+Up Arrow
    • Go to Next Function: Alt+Down Arrow
    • Go to Previous error/highlight/issue: Alt+PageUp
    • Go to Next error/highlight/issue: Alt+PageDown
    • Run All Test: Ctrl+U, L
    • Run Last Test: Ctrl+U,U
    • Reformat Code: Ctrl+Alt+Enter
    • Clean Up: Ctrl+E, Ctrl+C
    • Duplicate Code(selection/line/block): Ctrl+D
    • Insert New Line:Shift+Enter
    • Insert Surround Template: Ctrl+E,U
    • Build Solution: Ctrl+Shift+B
    • Start without Debug: Ctrl+F5
    • Backward Navigate: Ctrl+-

2020年3月27日 星期五

[Resharper] 建立自己的Code Snippet

先簡短紀錄

1.先在cs空白處 key alt+enter
2.查詢Templates Explorer
3.進入後就可以參考既有新增

ref:https://www.jetbrains.com/resharper/features/code_templates.html

紀錄自己 :

[Test]
public void $Method$_$Scenario$_$ExpectedBehavior$()
{$END$}

2020年2月7日 星期五

[SQL] 新增大量資料 - SqlBulkCopy


最近在用一物一碼,所以會需要產生大批編號

如果使用一筆一筆insert的話, 100萬筆資料不知道要存到哪一天了

這時候建議還是直接用sql bulk insert

ex.

using (SqlConnection conn = new SqlConnection(oneGoodsCS))
{
conn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn))
{
copy.DestinationTableName = "DemoTable";
DataTable dt = new DataTable("DemoTable");
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("TraceCodeID", typeof(int));

#region sub
for (var i = 0; i < request.Count; i++)
{
var code = Guid.NewGuid().ToString().ToLower();
dt.Rows.Add(code, "traceCodeID");
}
copy.WriteToServer(dt);
#endregion
}
}


2020年1月31日 星期五

[C#] 非同步觀念紀錄

1.偏向處理IO bound(讀取記憶體/硬碟密集),但CPU Loading較低的工作,
  如:讀文件、資料庫、網路要求資料(webservice)
 
2.是並行處理 concurrent, 與平行處理不同

3.一般建議任何方法(method)超過50ms才能完成,建議改非同步

4.4~5條thread就很夠處理一般程式(ex.賽車換輪胎範例)

5.非同步目的是提高執行效能與回應速度

6.thread safey : 多執行序環境下也可以確保得到預期結果

7.Critical Section: 任意一段程式碼,不允許多執行緒同時執行這段程式碼 ex.lock

8.Deadlock: 當兩個執行緒都嘗試鎖定另一個執行緒已經鎖定的資源時,就會發生死結,導致兩個執行緒都不能繼續執行


9.Context Switch: thread 記錄當下狀態,並換成其他thread(是會消耗成本)

10.非同步進程 : APM, EAP, TPL, TAP

11.blocking thread, 建議不用 .result wait waitall .thread join等會讓執行等待的方式, 改用WhenAll(tasks),await

12.不要混用同步與非同步方法

13.正常情況,不要使用 async void MethodAsync(){}, 改用回傳Task才能捕捉異常與執行結果

14.await Task.Delay 替代 Thread.Sleep

2020年1月16日 星期四

[MVC] 自訂Authentication

複習一下 :

    public class CustomAuthenticationFilter : IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true))
            {
                return;
            }

            if (filterContext.Principal.Identity.IsAuthenticated && filterContext.Principal.Identity is FormsIdentity)
            {
             
            }
            else
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                {"controller","Default"},
                {"action","Logon"},
                {"returnUrl",filterContext.HttpContext.Request.RawUrl }
            });
            }
            //or do something , add challenge to response

        }
    }


參考:https://dotblogs.com.tw/libtong/2017/10/03/105527

2020年1月12日 星期日

[SQL] 學習 IN和EXISTS用法的差別


引用:https://www.jianshu.com/p/f212527d76ff


引用 :https://read01.com/zh-tw/ggKA5P.html#.Xhq8usgkuUk

exist會針對子查詢的表使用索引.
 not exist會對主子查詢都會使用索引.
 in與子查詢一起使用的時候,只能針對主查詢使用索引.
 not in則不會使用任何索引. 注意,一直以來認為exists比in效率高的說法是不準確的


紀錄一下

2019年12月31日 星期二

[ng] Angular note

Angular note
 
Angular CLI 實用指令
npm install -g angular-cli 安裝
ng --help 說明
ng new 建立新專案
ng g c 建立component
ng g p 建立pipe
...常用<schematic>:
class component directive enum guard interface module pipe service
ng serve --open 啟用網站
 
基本內容建立格式
  1. Import
  2. 修飾詞
  3. Output
 
 
資料綁定 4種
  {{}}
  [property] = "value" : 屬性綁定
  (event) = "hander"   : 事件綁定
  [(ngModel)] = "property" : 雙向綁定
 
<!-- 雙向綁定 -->
<input [(ngModel)]="property">
<!-- 屬性綁定 -->
<input [ngModel]="property">
<!-- 事件綁定 -->
<input (ngModelChange)="handler($event)">

裝飾結構說明
@Component :
@Pipes
@Directive :
結構型Structural Directives:*ngfor,
屬性型Attribute Directives:[(ngModel)]
@Injectable : Service 的裝飾器

Routing說明
forRoot
forChild
路由在查找的時候是有順序性:AppRoutingModule放後面
模組延遲載入 : ex.loadChildren: './feature/feature.module#FeatureModule'
預先載入 :頁面初始化的時候就把所有可延遲載入的模組透過背景非同步地下載
負責重新配置頁面中應該顯示哪些 Component
[routerLink]="['..', path.checkoutFlow.paymentInfo]"  回上層

其他:
Angular JIT vs AOT
Component 只負責處理畫面、資料綁定
Service 則負責像是取得資料、表單驗證等等的邏輯處理,

ref :
[Angular 深入淺出三十天] https://ithelp.ithome.com.tw/articles/10205808
custom pipes https://angular.io/guide/pipes#custom-pipes
[Angular 大師之路] https://ithelp.ithome.com.tw/articles/10203550
[Angular2速成班]用Angular CLI節省你的開發時間 https://dotblogs.com.tw/wellwind/2016/09/30/angular2-angular-cli
HTTP Cache 機制 https://blog.techbridge.cc/2017/06/17/cache-introduction/

好用擴充:
angular2-prettyjson

2019年12月20日 星期五

[C#] 推薦分析程式工具


推薦暗黑大筆記 : 重構筆記 - .NET 壞味道補充包

裡面有NDepend 套件內的依些壞味道rule

一些常見的壞味道

1.一個類別太大 200行以上
2.方法太大太複雜
3.方法參數過多

還有很多值得學習與思考的地方
強烈推薦可以去研究看看

2019年12月19日 星期四

[sql] 將特定欄位當作 column

最近遇到要把 資料庫某個欄位當作 column 使用

所以就查詢了一下,目前有兩種方式


1.使用PIVOT, 轉置table, 但是原始column name 不能跟欄位裡面的值重複, 不然會出錯

說明: 先動態取得要轉置成column的欄位, ColumnGroup , 組成需要的字串, 再用PIVOT轉置TABLE

2019年12月13日 星期五

[sql] 撈取所有DB 的 所有TABLE


最近有個需求是直接給一張table, 但卻不知道在眾多DB的哪一個DB裡面

因此股哥到列出所有DB 及其 Table 並整理如下:


2019年11月21日 星期四

[Nlog] 簡易config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->


    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>

  <rules>
    <!-- add your logging rules here -->
    <logger name="*" minlevel="Trace" writeTo="f" />
    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>


補充 :

如果想要自訂參數 ex.${event-context:item=Name}

程式中記得自訂log level 與參數即可

private static void WriteLog(string msg)
{
    LogEventInfo ei = new LogEventInfo(NLog.LogLevel.Trace, "", "");
    ei.Properties["Name"] = Guid.NewGuid();
    ei.Properties["msg"] = msg;
    logger.Log(ei);
}

config 加入 event-context 參數即可

    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}/${event-context:item=appName}.log"
            layout="${longdate} |${uppercase:${level}}| ${event-context:item=msg}" />
  </targets>





[pdf] [C#] 網頁匯出PDF - PuppeteerSharp

最近遇到需要將頁面轉PDF

這裡推薦一個套件,真的滿厲害的

比起自己用itext刻快多了~


參考範例 :

特別說明,如果要讓pdf完整套用跟畫面一致,請記得設定參數唷
new PdfOptions() { PrintBackground = true, PreferCSSPageSize = true }

await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
{
    Headless = true 
}))
{
    //參考頁面 https://www.puppeteersharp.com/api/PuppeteerSharp.ScreenshotOptions.html
    using (var page = await browser.NewPageAsync())
    {
        
        var loginPath = $"https://google.com";
        await page.GoToAsync(loginPath);
        await page.EmulateMediaTypeAsync(PuppeteerSharp.Media.MediaType.Screen);
        //透過SetViewport控制視窗大小決定抓圖尺寸
        await page.SetViewportAsync(new ViewPortOptions
        {
            Width = 1024,
            Height = 768
        });
 
        var outputFile = $"test.pdf";
        await page.PdfAsync(outputFile, new PdfOptions() { PrintBackground = true, PreferCSSPageSize = true });
 
    }
}



參考

黑暗blog :https://blog.darkthread.net/blog/headless-chrome/

Api說明 : https://www.puppeteersharp.com/api/PuppeteerSharp

2019年10月25日 星期五

[deploy] 遠端發佈 error - 处理程序“ExtensionlessUrlHandler-Integrated-4.0”在其模块列表中有一个错误模块“ManagedPipelineHandler”

錯誤訊息 : 处理程序“ExtensionlessUrlHandler-Integrated-4.0”在其模块列表中有一个错误模块“ManagedPipelineHandler”


解法 : 發現結果是沒有安裝 .net 4.6, 再安裝即可

1.進windows功能 啟用 .net 4.6

2.管理者權限進入 cmd

32位元:C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

64位位元:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i


ref :https://www.cnblogs.com/mrma/p/3529859.html

2019年10月18日 星期五

[sql] 切開同一欄位用逗點隔開的資訊


遇到一個狀況,資料庫顯示為

| CODE |   FK    |
-----------------------
|  A  |   1,2,3 |
我需要轉如下才能關聯....

| CODE |  FK   |
-----------------------
|  A  |     1 |
|  A  |     2 |
|  A  |     3 |

解法 :
參考 : https://stackoverflow.com/questions/13527537/sql-query-to-split-column-data-into-rows

先建立sql function
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
returns @temptable TABLE (items varchar(MAX))       
as       
begin      
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return 
end;

然後下以下sql 句即可
select t1.Code, s.items FK
from [table] t1
outer apply dbo.Split(t1.FK, ',') s

outer apply : 說明參考 https://ithelp.ithome.com.tw/articles/10195219