2017年3月19日 星期日

C#语言入门详解(特辑001)

委托、Lambda表达式、LINQ大串讲

对答如刘(004)——Git又来啦!

网友提问
---------------
1. 吉特是老师家的猫吗?
2. 老师能不能说你的开发领域啊?
3. 老师你的人生目标是什么?要是没实现呢?
4. 老师你用的什么虚拟机啊?Hyper-V,下期就讲
5. Java, C#和Python你最看好哪个?
===========
技术问题
---------------
1. 恢复状态:reset
2. 简单分支(文件和修改无冲突)
3. 查看当前分支
4. 分支出现冲突
5. MVC等架构和好处,团队任务分配的技巧

2017年3月17日 星期五

对答如刘(003)——Git来啦!

本期话题:
1. 什么是版本管理工具?
2. 什么是Git,它与GitHub是什么关系?
3. 如何下载和安装Git?
4. 如何创建本地代码库并进行代码版本管理?
5. 回答网友提问



对答如刘(002)——在Linux上支锅建灶开发.NET Core程序

对答如刘(002)——在Linux上支锅建灶开发.NET Core程序

本期问题包括:
1. 如何在Linux上使用.NET Core + VSCode搭建开发环境
2. .NET Core能不能开发跨平台GUI程序?
3. .NET Core真的能在Linux上跑吗?
4. 老刘是要“爆发”了吗?
5. 29岁开始学编程算不算晚?
6. 刘老师工作压力大的时候做点儿什么呢?

[C#] 委派/泛型委派: Delegate vs. Action vs. Func vs. Lambda

自學筆記,幫助自己記憶,以利未來回想…

感謝老師的教學視頻:C#语言入门详解(特辑001) 



Delegate 己過時,進化成 Action、Func:

委派
delegate void MyDele();

泛型委派
delegate T MyDele<T>(T a, T b);

Action: 沒有返回值的委派,用於無回傳值的方法
Func: 有返回值的委派,用於有回傳值的方法


Lambda 表達式是
1. 匿名方法
2. Inline 方法
使用時機:程式中若有很多的細算法(e .g.加減乘除),臨時算一下用完就沒了,就可以使用Lambda。

※ Inline code:將Function(函式)的內容直接以inline 的方式寫在一般的程式碼之中,省去另外定義Function。MSDN: https://msdn.microsoft.com/zh-tw/library/bb397687.aspx


[建立概念]

委派是什麼?
1. 類似C++函式指標的概念。
2. 像是一個方法的封裝器,一個函式或是一組函式的封裝器。
 https://www.youtube.com/watch?v=g1EU9gnZKOg


模擬場景:
1. 小明最近學習情緒高漲,以前買的書已經滿足不了慾望,打算去買本(一個程序員的自我修養)。可是呢以前總是跑書廠買,太遠了扛不住,就去跑去附近書店去買,小明去給錢就弄了一本書回來,這個過程就是委託。
http://www.cnblogs.com/LipeiNet/p/4694225.html

2.  貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。
程式要求:
(1). 要有聯動性,老鼠和主人的行為是被動的。
(2). 考慮可擴展性,貓的叫聲可能引發其他聯動效應。
http://www.programgo.com/article/24262282064/


[實作練習]

Delegate
1. 委派也是一種Class
2. 需要聲明
3. 參數類型要一致

Delegate(無返回值)

Example 1: 調用一個Function


    class Program {
        static void Main(string[] args) {
            MyDele dele1 = new MyDele(M1);
            dele1 += M1;   //多重委派,就是用委派變數+= 方法名稱
            dele1();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

    delegate void MyDele();

Example 2: 調用Class的Function


    class Program {
        static void Main(string[] args) {
            MyDele dele1 = new MyDele(M1);
            dele1 += new Student().SayHello;    //調用Class的Function
            dele1();

            Console.Read();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

    class Student {
        public void SayHello() {
            Console.WriteLine("Hello, I'm Riva.");
        }
    }

    delegate void MyDele();


Delegate(有返回值)

   class Program {
        static void Main(string[] args) {
            MyDele dele = new MyDele(Add);
            int result = dele(100, 200);
            Console.WriteLine(result);
        }

        static int Add(int x, int y) {
            return x + y;
        }
    }

    delegate int MyDele(int a, int b);


Generics Delegates (泛型委派):

    class Program {
        static void Main(string[] args) {
            MyDele<int> deleAdd = new MyDele<int>(Add);
            int addResult = deleAdd(100, 200);
            Console.WriteLine(addResult);

            MyDele<double> deleMul = new MyDele<double>(Mul);
            double mulResult = deleMul(3.0, 4.0);
            Console.WriteLine(mulResult);
        }

        static int Add(int x,int y) {
            return x = y;
        }

        static Double Mul(double x, double y) {
            return x * y;
        }
    }
    
    delegate T MyDele<T>(T a, T b);


Action (無參數)

    class Program {
        static void Main(string[] args) {
            Action action = new Action(M1);
            action();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

Action (有參數)

    class Program {
        static void Main(string[] args) {
            Action<string> action = new Action<string>(SayHello);
            action("Riva");
        }

        static void SayHello(string name) {
            Console.WriteLine("I'm {0}", name); //Console.WriteLine($"I'm {name}"); C# 6
        }
}


Action (多參數,不同類型)

    class Program {
        static void Main(string[] args) {
            var action = new Action<string, int>(SayHello);
            action("Riva", 3);
        }

        static void SayHello(string name, int round) {
            for (int i = 0; i < round; i++) {
                Console.WriteLine("Hello, {0}", name);
            }
        }
}



Func: 有回傳值

Func (Int類型)

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>(Add);
            int res = func(100, 200);
            Console.WriteLine(res);
        }

        static int Add(int x, int y) {
            return x = y;
        }

Func (Double類型)

    class Program {
        static void Main(string[] args) {
            var func = new Func<double, double, double>(Mul);
            double result = func(3.0, 4.0);
            Console.WriteLine(result);
        }

        static Double Mul(double x, double y) {
            return x * y;
        }



Func + Lambda (泛型委派)

原始寫法:

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a + b; });
            int res = func(100,200);
            Console.WriteLine(res);

            func = new Func<int, int, int>((int x, int y) => { return x * y; });
            res = func(3,4);
            Console.WriteLine(res);
        }
    }

進一步簡化:(省略int)

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>((a, b) => { return a + b; });
            int res = func(100, 200);
            Console.WriteLine(res);

            func = new Func<int, int, int>((x, y) => { return x * y; });
            res = func(3, 4);
            Console.WriteLine(res);
            Console.Read();
        }
    }


再簡化:(直接賦值給委派參數Lambda表達式) ★★★★★

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = (a, b) => { return a + b; };
            int res = func(100, 200);
            Console.WriteLine(res);

            func = (x, y) => { return x * y; };
            res = func(3, 4);
            Console.WriteLine(res);
        }
    }



泛型方法+泛型的委派參數+泛型參數 ★★★★★
(泛型函式的參數為"Func類型的參數")

原始寫法:
namespace Combine {

    class Program {
        static void Main(string[] args) {
            DoSomeCalc<int>((int a, int b) => { return a * b; }, 100, 200);
            Console.Read();
        }

        static void DoSomeCalc<T>(Func<T,T,T> func, T x, T y) {
            T res= func(x, y);
            Console.WriteLine(res);
        }
    }

省略int
    class Program {
        static void Main(string[] args) {
            DoSomeCalc((a, b) => { return a * b; }, 100, 200);
        }

        static void DoSomeCalc<T>(Func<T, T, T> func, T x, T y) {
            T res = func(x, y);
            Console.WriteLine(res);
        }
    }



Ref:
1. C#语言入门详解(特辑001) ★★★★★
2. C#的委派與事件的使用:
3. [C#] 快速了解泛型委派:
4. 設計模式面試與筆試題剖析(二)
5. C#之Action和Func的用法
6. C# IN DEPTH

对答如刘(001)——如何开发跨平台的C#应用程序

1. 我的硬盘空间太小,Visual Studio太大,怎么学习C#?
2. 我使用的是Apple/Linux,怎么学习C#呢?

2016年12月28日 星期三

[ASP.NET MVC] 登入後,自動導向使用者原本Request的Url

練習筆記...


User 驗証未通過,登入後,自動導向User原本Request的Url,三種作法:
1. 使用FormsAuthentication
2. 使用ViewBag
3. 使用讀寫屬性


1. 使用FormsAuthentication
FormsAuthentication.RedirectFromLoginPage(username, false);

2.使用ViewBag

@using (Html.BeginForm("index", "login", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { autocomplete = "off" }))
{
@Html.TextBoxFor(m => m.Account)
@Html.TextBoxFor(m => m.Password)

<button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>
}

[AllowAnonymous, HttpGet]
public ActionResult Index(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}


3.使用讀寫屬性

public string ReturnUrl { get; set; }


@using (Html.BeginForm("index", "login", new { ReturnUrl = Model.ReturnUrl }, FormMethod.Post, new { autocomplete = "off" }))
{
@Html.TextBoxFor(m => m.Account)
@Html.TextBoxFor(m => m.Password)

<button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>

}


[HttpGet]
public ActionResult Index(string returnUrl)
{
LoginViewModel model = new LoginViewModel() { ReturnUrl = returnUrl };
return View(model);
}


HttpPost ActionResult


[HttpPost]
public ActionResult Index(LoginViewModel data, string returnUrl)
{
//Todo something

if (string.IsNullOrWhiteSpace(returnUrl))
//RedirectToAction default url or other.
else
return Redirect(returnUrl);

return View();
}


Ref:
1. ASP.net MVC整合FormsAuthentication表單驗證登入
https://dotblogs.com.tw/shadow/archive/2014/03/01/144191.aspx
2. Asp.net MVC 實作登入驗證(1)
http://marco.easyusing.com/2013/10/mvc-1-mvc-mvc-mvc5-build-4.html

[ASP.NET MVC] Cookie與FormsAuthentication表單驗證自動登入

練習筆記...


[寫入Cookie]

寫法一:
HttpCookie cookie = new HttpCookie("UserData");
cookie.Value = JsonConvert.SerializeObject(userData);
cookie.Expires = DateTime.Now.AddDays(1d);

Response.Cookies.Add(cookie);



寫法二:
HttpCookie cookie = new HttpCookie("UserData")
{
       Value = JsonConvert.SerializeObject(userData),
       Expires = DateTime.Now.AddDays(1d),
};
Response.Cookies.Add(cookie); 


[取得Cookie]
HttpCookie authCookie = Request.Cookies["UserData”];


[FormsAuthentication寫入Cookie] 

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
      version: 1,
      name: data.Account,
      issueDate: DateTime.Now,
      expiration: DateTime.Now.AddDays(1),
      isPersistent: false,
      userData: JsonConvert.SerializeObject(userData),
      cookiePath: FormsAuthentication.FormsCookiePath);

var encryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
cookie.Expires = ticket.Expiration;
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);

※ Cookie name 一定要用FormsAuthentication的CookieName => FormsAuthentication.FormsCookieName


[取得FormsAuthentication寫入的Cookie]

HttpCookie cookie = GetCookie(FormsAuthentication.FormsCookieName);



Ref:
1. 寫入 Authentication Cookie 的 FormsAuthenticationTicket.UserData
2. session與cookies與FormsAuthentication自動登入機制
3. ASP.net MVC整合FormsAuthentication表單驗證登入

2016年12月26日 星期一

[ASP.NET MVC] 空白MVC專案實作BundleConfig

練習筆記...


[實作步驟]

1. 在「App_Start」資料夾自行建立「BundleConfig.cs」

2. 在Global.asax.cs 註冊Bundles


BundleConfig.RegisterBundles(BundleTable.Bundles);


3. Web.Config新增Optimization 命名空間

<namespaces>
    <add namespace="System.Web.Optimization"/>   
</namespaces>


[使用方法]

@Styles.Render("~/Content/css”)
@Scripts.Render("~/Scripts/bootstrap”)
@Scripts.Render("~/Scripts/jquery”)



Ref:
http://demo.tc/post/779
http://aspnetmars.blogspot.tw/2016/05/aspnet-mvc-bundleconfig.html

2016年12月25日 星期日

[MVC] Server Error "owin:AutomaticAppStartup"

遇到就筆記一下…


[問題描述]

在空白MVC專案,從NuGet Package 安裝Owin套件後執行,發生錯誤訊息「To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config…」


[錯誤訊息]

'/' 應用程式中發生伺服器錯誤。


The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.



[解決方案]

在Web.config加入
<add key="owin:AutomaticAppStartup" value="false" /> 



Ref: 
OwinStartupAttribute required in web.config to correct Server Error

2016年12月4日 星期日

[LINQ] LINQ to SQL 執行各種 Join 查詢的技巧 (轉貼)

A note to myself.

轉貼自Will 保哥:

http://blog.miniasp.com/post/2010/10/14/LINQ-to-SQL-Query-Tips-INNER-JOIN-and-LEFT-JOIN.aspx


如果要改成 LEFT JOIN 語法,則必須修改成以下 LINQ 語法:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID into ps
from o in ps.DefaultIfEmpty()
select new { c.CategoryName, o.ProductName }
因為撰在 LINQ 撰寫 LEFT JOIN 時的觀念與 T-SQL 不太一樣,要用「物件」的角度比較能理解其語法所代表的意義,所以上述的語法可以這樣解釋:
取出 Categories 資料並放入 c 變數,接著再與 Products 做 JOIN 並將 JOIN 後的結果放入 ps 變數(注意:並非第二行的 o 變數),這時再宣告一個資料來源 o 其資料來自於「修改過的 ps 變數」,且修改的方式為 ps.DefaultIfEmpty(),意即代表若 ps ( 也就是 Products 經過 join 篩選後的資料 ) 無任何資料時,還是回傳一筆 Default 的資料(也就是預設的 null 資料)。






我發現許多人對使用 LINQ 執行 JOIN 查詢並不是那麼的熟悉,而且語法也不見得像 T-SQL 那樣直覺,但事實上只是我們比較熟悉 T-SQL 的語法與資料庫架構而已,當我們換成 ORM (Object-relational mapping) 技術後所有對資料的操作必須全部改以「物件」與「實體」來思考,所以在這轉換的過程經常轉不過去,連我自己也有時會忘記怎麼寫,也經常利用 Linq Samples and the Sample Query Explorer 幫我查出適當的寫法。
由於大多數人都是先學會 T-SQL 然後才學會 LINQ 的,因此兩者的觀念難免有些模糊不清的地方,尤其是在開發的時候都會不斷的以 T-SQL 語法如何翻譯成 LINQ 語法 這樣的思路在寫 LINQ,因此多少會經歷一些痛苦的轉換期,不過,學習新技術最好的方式是先暫時放下既有的經驗,試圖去瞭解為什麼要有這個新技術的出現,再來思考之間如何做轉換以及應注意的地方。
我們先來一段最基本的 LINQ to SQL 使用類似 T-SQL 的 INNER JOIN 資料查詢語法:
from c in Categories
from o in c.Products
select new { c.CategoryName, o.ProductID, o.ProductName }
我們可以從上述 LINQ 語法上就知道有兩個資料來源(因為有兩個 from 子句),而第二個 from 使用的是第一個 from 資料來源的關連屬性,因此產生 JOIN 需求,這段 LINQ 語法所產生的 T-SQL 語句如下:
SELECT [t0].[CategoryName], [t1].[ProductID], [t1].[ProductName]
FROM [Categories] AS [t0], [Products] AS [t1]
WHERE [t1].[CategoryID] = [t0].[CategoryID]

接著我們來看看另一個 INNER JOIN 的資料查詢語法,我們使用語意更為明確的 join 子句:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID 
select new { c.CategoryName, o.ProductID, o.ProductName }
我們可以從上述 LINQ 語法上知道有一個 Categories 資料來源,並且 join 另一個 Products 資料來源,當中用這個兩個實體的其中一個 CategoryID 屬性進行 join 動作,這是一個非常明確的 join 語法,其語法與 T-SQL 的 join 語法非常相近,這段 LINQ 語法所產生的 T-SQL 語句如下:
SELECT [t0].[CategoryName], [t1].[ProductID], [t1].[ProductName]
FROM [Categories] AS [t0]
INNER JOIN [Products] AS [t1] ON ([t0].[CategoryID]) = [t1].[CategoryID]
這兩段 LINQ 語法所執行的結果資料一模一樣,不過產生的 T-SQL 不一樣,所以透過 LINQ to SQL 會自動將設定的 LINQ 語法產生出合適的 T-SQL 語法。不過,我們都知道資料庫查詢的 SQL 語法有很多調校的技巧,透過 LINQ to SQL 之後自然會變的不容易調校,所以針對某些 LINQ 語法還是有可能產生效能不彰的狀況需要自行處理。
舉個例子來說,以下 LINQ 語法除了 join 外還在 select 的地方有隱含的使用了另一個 JOIN 條件:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID 
select new { o.Category.CategoryName ,o.ProductID, o.ProductName }
因此會產生出一個詭異且無效率的 T-SQL 語法如下,同時有 INNER JOIN 與 LEFT OUTER JOIN 的狀況:
SELECT [t2].[CategoryName], [t0].[ProductID], [t0].[ProductName]
FROM [Products] AS [t0]
INNER JOIN [Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])
LEFT OUTER JOIN [Categories] AS [t2] ON [t2].[CategoryID] = [t0].[CategoryID]
這時我們修正 LINQ 語法如下:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID 
select new { c.CategoryName, o.ProductID, o.ProductName }
這時就會產生預期的 T-SQL 語法:
SELECT [t0].[CategoryName], [t1].[ProductID], [t1].[ProductName]
FROM [Categories] AS [t0]
INNER JOIN [Products] AS [t1] ON ([t0].[CategoryID]) = [t1].[CategoryID]
雖然 LINQ 出現的目的就是希望你改用「物件」與「實體」的角度來思考資料的查詢方式,不過如果你能瞭解從 LINQ 轉換到 T-SQL 的過程將有助於你寫出更有效率的 LINQ 查詢語法。

瞭解 INNER JOIN 之後,我們再來看一個 T-SQL 中常見的 LEFT JOIN 語法的 LINQ 要如何撰寫:
from o in Products
select new { o.Category.CategoryName, o.ProductID, o.ProductName }
這段 LINQ 語法我們只取出一個 Products 資料來源,但是在 select 子句卻額外取得 Category 關連實體的資料,這個關連是「多對一」的關連,所以一個 Product 實體只會取得一個 Category 實體,所以轉換 T-SQL 之後你會發現 LEFT JOIN 的左邊就是 Products,而右邊就變成 Categories,其所產生的 T-SQL 語句如下:
SELECT [t1].[CategoryName], [t0].[ProductID], [t0].[ProductName]
FROM [Products] AS [t0]
LEFT OUTER JOIN [Categories] AS [t1] ON [t1].[CategoryID] = [t0].[CategoryID]
雖然你看到的是一個 LEFT JOIN 語法,不過這並不是我們常見的那種 JOIN 狀況,比較複雜的狀況是當我們左側的實體為 Categories 以及右側的實體為 Products 的狀況,這是「一對多」的關連,複雜度相對提高一些。
由於 INNER JOIN 是 交集(AND) 的概念,當兩個 JOIN 的實體都有資料時才有資料。而 LEFT JOIN的概念卻是「左邊的資料全部都要有,即便右邊沒有資料也要以 null 代替」,因此我們的 LINQ to SQL 語法如下就要特別注意資料來源出現的順序性:
我們先重寫文章稍早出現的過的 INNER JOIN 語法如下:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID 
select new { c.CategoryName, o.ProductName }
如果要改成 LEFT JOIN 語法,則必須修改成以下 LINQ 語法:
from c in Categories
join o in Products on c.CategoryID equals o.CategoryID into ps
from o in ps.DefaultIfEmpty()
select new { c.CategoryName, o.ProductName }
因為撰在 LINQ 撰寫 LEFT JOIN 時的觀念與 T-SQL 不太一樣,要用「物件」的角度比較能理解其語法所代表的意義,所以上述的語法可以這樣解釋:
取出 Categories 資料並放入 c 變數,接著再與 Products 做 JOIN 並將 JOIN 後的結果放入 ps 變數(注意:並非第二行的 o 變數),這時再宣告一個資料來源 o 其資料來自於「修改過的 ps 變數」,且修改的方式為 ps.DefaultIfEmpty(),意即代表若 ps ( 也就是 Products 經過 join 篩選後的資料 ) 無任何資料時,還是回傳一筆 Default 的資料(也就是預設的 null 資料)。
這一段 LINQ 所產生的 T-SQL 如下:
SELECT [t0].[CategoryName], [t1].[ProductName] AS [ProductName]
FROM [Categories] AS [t0]
LEFT OUTER JOIN [Products] AS [t1] ON ([t0].[CategoryID]) = [t1].[CategoryID]
因此當你需要撰寫「多對一」關連情況下正確的使用 LINQ 查詢語法做 LEFT JOIN 就必須這樣來撰寫!
不過有一點必須注意,那就是當 o 取得的物件為 null 時,雖然 select 子句中的 o.ProductName 不會引發例外,而且會回傳 null,但是若你在 select 子句中設定 o.ProductID 的話,那就會引發例外,因為 null 並無法正確轉型成 Int32 型別,錯誤訊息是:InvalidOperationException - 無法將 Null 值指派給型別 System.Int32 的成員,該型別不可為 Null 值。
相關連結