2017年7月9日 星期日

GoF - Singleton

  • GoF (1)
    • Creational Patterns 
  • UML
  • Code

public class Singleton
{
    // 因建立物件需要花費許多資源,此一開始就不建立物件
    private static Singleton instance; 
    // [多執行緒] 建立一個靜態惟獨的行程輔助物件
    private static object sync = new object();
    
    private Singleton()
    {
        // 這裡面跑很多 Code
        // 建立物件需要花費許多資源
    }

    public static Singleton getInstance()
    {
        // 1. 第一次被呼叫的時候,instance為null,要建立物件
        // 2. 判斷實體是否存在,不存在再加鎖處理
        if (instance == null)
        {
            // [多執行緒] 加鎖建立物件,只有一個執行緒可以進入
            lock(sync)
            {
                // [多執行緒] 雙重鎖定
                // 當兩個執行緒調用 getInstance
                // 他們都可以夠過第一重 instance == null
                // 由 lock 機制,這兩個執行緒只能一個進入,另一個在外排隊等候
                // 其中一個進入並出來後,另一個才能進入
                // 如沒有第二重 instance == null
                // 第一個執行緒建立實體,第二個執行緒還是可以繼續在建立新的實體
                if(instance == null)
                {
                    instance = new Singleton();
                }
            }
            
        }

        // 已經有物件存在,直接回傳這個物件
        return instance;
    }
}


    Ref: 
    • 7 天學會設計模式-設計模式也可以這樣學
    • 大話設計模式

    2017年4月16日 星期日

    [SQL Server] Query fast, but slow from stored procedure

    1. ANSI_NULLS Issue
    I found the problem, here's the script of the slow and fast versions of the stored procedure:
    dbo.ViewOpener__RenamedForCruachan__Slow.PRC
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS OFF 
    GO
    
    CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
        @SessionGUID uniqueidentifier
    AS
    
    SELECT *
    FROM Report_Opener_RenamedForCruachan
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
    GO
    
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
    dbo.ViewOpener__RenamedForCruachan__Fast.PRC
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
    
    CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
        @SessionGUID uniqueidentifier 
    AS
    
    SELECT *
    FROM Report_Opener_RenamedForCruachan
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
    GO
    
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
    If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
    Slow: SET ANSI_NULLS OFF
    Fast: SET ANSI_NULLS ON

    This answer also could be made to make sense, since the view does have a join clause that says:
    (table.column IS NOT NULL)
    So there is some NULLs involved.

    The explanation is further proved by returning to Query Analizer, and running
    SET ANSI_NULLS OFF
    .
    DECLARE @SessionGUID uniqueidentifier
    SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
    .
    SELECT *
    FROM Report_Opener_RenamedForCruachan
    WHERE SessionGUID = @SessionGUID
    ORDER BY CurrencyTypeOrder, Rank
    And the query is slow.

    So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.
    Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:
    Set ANSI_NULLS ON
    Go
    Create Proc spXXXX as
    ....

    2. procedure cache issue
    I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure. 
    I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.

    Slow way:
    CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
    AS
    BEGIN
        SELECT * 
        FROM orders
        WHERE customerid = @CustID
    END
    Fast way:
    CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
    AS
    BEGIN
        DECLARE @LocCustID varchar(20)
        SET @LocCustID = @CustID

        SELECT * 
        FROM orders
        WHERE customerid = @LocCustID
    END

    Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.

    REF: 
    http://chhtai.blogspot.tw/2016/01/normal-0-0-2-false-false-false-en-us-zh.html
    http://stackoverflow.com/questions/440944/sql-server-query-fast-but-slow-from-procedure

    2017年3月31日 星期五

    [MVC] Can RenderSection be used in EditorForModel ?

    Q. Sections work only in views, not in partials. An editor template is a special kind of partial. It's bad practice to put javascript in partials anyway, so I would simply declare the section in the Edit.cshtmlview.
    But if you very much insist on putting your scripts in the middle of your markup, since Razor doesn't support sections in partials, you could implement custom helpers to achieve that.

    REF: http://stackoverflow.com/questions/10810446/rendersection-and-editorformodel-in-asp-net-mvc

    2017年3月30日 星期四

    MVC DataFormatString and DisplayNameAttribute

    1. DataFormatString

    數字
    N 或 n
    以數字(包括群組分隔符號和選擇性的負號)的格式顯示數值。
     您可以指定小數位的數。
    格式:{0:N}
    1234.567 ->
    1,234.57
    格式:{0:N4}
    1234.567 -> 
    1,234.5670

    格式:{0:N0}
    1234.567 -> 
    1,234
    百分比
    P 或 p
    以百分比格式顯示數值。 您可以指定小數位的數。              
    格式:{0:P}
    1 -> 100.00%
    格式:{0:P1}
    .5 -> 50.0%

    根據預設,格式字串套用至欄位值,其中包含的資料繫結控制項時,才 BoundField 物件處於唯讀模式。 若要將格式字串套用至欄位值,在編輯模式中,設定 ApplyFormatInEditMode 屬性 true。


    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N0}")]
    public bool MisnamedProperty { get; set; }

    2.  DisplayNameAttribute 

    DisplayNameAttribute 類別來變更名稱的屬性

    [DisplayName("RenamedProperty")]
    public bool MisnamedProperty { get; set; }

    REF:

    https://msdn.microsoft.com/zh-tw/library/system.componentmodel.displaynameattribute(v=vs.110).aspx
    https://msdn.microsoft.com/zh-tw/library/system.web.ui.webcontrols.boundfield.dataformatstring(v=vs.110).aspx

    2017年3月13日 星期一

    [MVC] update edmx error on MySql


    • Q: 無法產生模型,因為發生下列例外狀況: 'System.Data.StrongTypingException: 資料表 'TableDetails' 中資料行 'IsPrimaryKey' 的值是 DBNull。 ---> System.InvalidCastException: 指定的轉換無效。
    • 1. Open Services (services.msc) and restart MySQL57 service. 
    • 2. Execute the following commands in MySQL.
      • use <<database name>>;
      • set global optimizer_switch='derived_merge=OFF';
    • 3. Update the .edmx.

    • REF: 

      • http://stackoverflow.com/questions/33575109/mysql-entity-the-value-for-column-isprimarykey-in-table-tabledetails-is





    2017年1月25日 星期三

    MVC Inputting a default image in case the src attribute of an html

    主要網站圖片有些會使用外部連結,如圖(1)為一個外部連結的圖檔,但會發生此網站中斷或者失去連線,就無法在抓取此圖片,如圖(2)會看見無發在抓取此圖片,因此需要設定預設的圖片,如圖(3)當外部網站失校將會使用預設圖片


    (1)                        (2)                             (3)

    設定如下:
    1. Add JavaScript code: 
         onerror="this.onerror=null; this.src='/Images/Default.png'" 

    2. Setting web.config
        <httpErrors errorMode="Custom" existingResponse="Replace">
          <remove statusCode="404"/>
          <error statusCode="404" path="404.html" responseMode="File"/>

        </httpErrors>


    Ref: 
    http://stackoverflow.com/questions/980855/inputting-a-default-image-in-case-the-src-attribute-of-an-html-img-is-not-vali
    http://stackoverflow.com/questions/40724854/error-page-in-asp-mvc
    http://blog.darkthread.net/post-2015-11-10-customerrors-and-httperrors.aspx

    2016年12月28日 星期三

    Visual Studio Snippet (快速鍵)


    Build
    • Ctrl+Shift+B 重建方案
    • F5 重建方案並執行(開始偵錯)
    Comment
    • Ctrl+K+C 將程式區塊註解掉
    • Ctrl+K+U 將註解還原成程式
    Other
    • Ctrl+X 剪下一整行
    • Ctrl+K+D 程式碼自動格式化,亦即依照格式將程式碼重排,自動加上間隔和縮排
    • Ctrl+R+E 產生指定變數的屬性程式碼,亦即,先輸入 private string name 然後點選 name 字再按Ctrl+R+E
    • Ctrl+- 回到先前編輯的那一段程式碼之所在。亦即,程式寫到一半,忘記某一個識別字正確的拼寫方式時,可以先切過去看一下,甚至用 Ctrl+C 複製起來,然後再同時按下 Ctrl 和 -(減號)兩個鍵,立即回到原來的畫面,繼續寫程式。
    • Ctrl+Shift+- 是 Ctrl+- 的反向,Ctrl+- 為 Previous; Ctrl+Shift+- 則是 Next
    • Ctrl+. 協助進行『自動解析』或『實作介面』,亦即為不認識的識別字補上 Using 的敘述,也可以產生實作(Implement)介面的程式碼
    • Alt + -> 可以顯示 "."下面的成員或屬性
    Tab
    • prop Tab Tab ,自動插入產生屬性(Property)的程式碼
    • ctor Tab Tab ,自動插入產生類別建構子(Constructor)的程式碼
    • for Tab Tab ,自動插入產生 for 迴圈的程式碼
    • forr Tab Tab ,自動插入產生 for 迴圈的程式碼,但是迴圈控制變數的值變成從大跑到小(倒著跑的 for 迴圈)
    • foreach Tab Tab ,自動插入產生 foreach 迴圈的程式碼
    Ref: 
    https://msdn.microsoft.com/zh-tw/library/z41h7fat.aspx
    http://mermerism.blogspot.tw/2014/05/visual-studio.html
    https://www.dotnetperls.com/snippet